如何在导航栏中添加返回按钮箭头功能
Posted
技术标签:
【中文标题】如何在导航栏中添加返回按钮箭头功能【英文标题】:How to add back button arrow functionality in navigation bar 【发布时间】:2016-05-05 13:47:47 【问题描述】:我是初学者程序员,刚刚开始开发 android。 看了很多答案,找不到适合我的答案。 我在操作栏中添加了后退箭头按钮,但不知道如何将导航添加到第一个加载的屏幕。
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null)
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener()
@Override
public void onBackStackChanged()
toggle.setDrawerIndicatorEnabled(getSupportFragmentManager().getBackStackEntryCount() == 0);
);
@Override
public void onBackPressed()
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START))
drawer.closeDrawer(GravityCompat.START);
else
super.onBackPressed();
@Override
public boolean onCreateOptionsMenu(Menu menu)
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
@Override
public boolean onOptionsItemSelected(MenuItem item)
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings)
return true;
switch (item.getItemId())
// Respond to the action bar's Up/Home button
case android.R.id.home:
Toast.makeText(getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
return true;
return super.onOptionsItemSelected(item);
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item)
// Handle navigation view item clicks here.
int id = item.getItemId();
TextView text = (TextView) findViewById(R.id.container_text);
Fragment fragment = null;
if (id == R.id.nav_about)
fragment = DemoFragment.newInstance("about");
text.setText("1");
else if (id == R.id.nav_settings)
fragment = DemoFragment.newInstance("nav settings");
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.container, fragment)
.addToBackStack(fragment.getClass().getSimpleName())
.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
DemoFragment.java
public class DemoFragment extends Fragment
public static final String TEXT = "text";
public static DemoFragment newInstance(String text)
Bundle args = new Bundle();
args.putString(TEXT, text);
DemoFragment fragment = new DemoFragment();
fragment.setArguments(args);
return fragment;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
View view = inflater.inflate(R.layout.fragment_demo, container, false);
String text = getArguments().getString(TEXT);
return view;
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_
android:layout_
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="@layout/app_bar_main"
android:layout_
android:layout_ />
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_
android:layout_
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />
app_bar_main.xml
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_
android:layout_
android:fitsSystemWindows="true"
tools:context="lt.simbal.drawer.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_
android:layout_
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_
android:layout_
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include
android:id="@+id/container"
layout="@layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_
android:layout_
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_dialog_email" />
content_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_
android:layout_
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="lt.simbal.drawer.MainActivity"
tools:showIn="@layout/app_bar_main">
<TextView
android:id="@+id/container_text"
android:layout_
android:layout_
android:text="MAIN_ACTIVITY" />
fragment_demo.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_
android:layout_>
<TextView
android:id="@+id/text"
android:layout_
android:layout_ />
nav_header_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_
android:layout_
android:background="@drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark">
<ImageView
android:id="@+id/imageView"
android:layout_
android:layout_
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:src="@android:drawable/sym_def_app_icon" />
<TextView
android:layout_
android:layout_
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:text="Android Studio"
android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="@+id/textView"
android:layout_
android:layout_
android:text="android.studio@android.com" />
activity_main_drawer.xml
<group android:checkableBehavior="single">
<item
android:id="@+id/nav_about"
android:icon="@drawable/ic_menu_camera"
android:title="@string/about" />
<item
android:id="@+id/nav_settings"
android:icon="@drawable/ic_menu_manage"
android:title="@string/settings" />
</group>
【问题讨论】:
投反对票,因为您不知道自己想做什么。敬酒或前往上一个或下一个活动 当我在导航抽屉中选择片段时,我需要进入我的活动。使用后退按钮,我需要访问我的 activity_main。 在你的 DemoFragment 中, onCreateView() 添加行 setHasOptionsMenu(true); @Stanojkovic:仍然没有结果。也许我可以将我的代码发送给您,或者在这个问题中发布所有内容?我想所有代码你都可以告诉我出了什么问题:/ 在此处添加所有代码,包括所有活动和清单文件。 【参考方案1】:您需要调用 setHomeAsUpIndicator 和 setDisplayHomeAsUpEnabled
设置备用drawable显示在图标/徽标/标题旁边 DISPLAY_HOME_AS_UP 已启用。如果您正在使用,这可能很有用 此模式显示向上导航的备用选择,例如 一个滑动抽屉。
ActionBar actionBar = getSupportActionBar();
if (actionBar != null)
......
actionBar.setDisplayHomeAsUpEnabled(true); //Set this to true if selecting "home" returns up by a single level in your UI rather than back to the top level or front page.
actionBar.setHomeAsUpIndicator(R.drawable.Your_Icon); // set a custom icon for the default home button
现在
对于这个处理需要在你的 Activity 中重写 onOptionsItemSelected(MenuItem item)
方法。
@Override
public boolean onOptionsItemSelected(MenuItem item)
switch(item.getItemId())
case R.id.home:
// Add your LOGIC Here
break;
default:
return super.onOptionsItemSelected(item);
return true;
【讨论】:
他在他的代码中设置了这一点。他只需要在他的 R.id.home 中设置意图。 @Stanojkovic 谢谢。【参考方案2】:好的,请确保您声明活动布局如下 -
<activity
android:name="com.example.myfirstapp.DisplayMessageActivity"
android:parentActivityName="com.example.myfirstapp.MainActivity" >
<!-- The meta-data element is needed for versions lower than 4.1 -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MainActivity" />
</activity>
现在在每个活动中添加以下代码
@Override
public boolean onOptionsItemSelected(MenuItem item)
switch (item.getItemId())
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
return super.onOptionsItemSelected(item);
【讨论】:
好!而如果你不使用片段,你甚至不需要在任何代码中,xml就足够了【参考方案3】:在 onCreate 中添加以下代码
final ActionBar actionBar = getSupportActionBar();
if (actionBar != null)
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.back_dark);
R.drawable.back_dark
是返回按钮图片
从您的代码中删除此 actionBar.setHomeButtonEnabled(true);
已编辑:发现一件事,更改以下方法
@Override
public boolean onOptionsItemSelected(MenuItem item)
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
//if (id == R.id.action_settings)
//return true;
//
switch (item.getItemId())
// Respond to the action bar's Up/Home button
case android.R.id.home:
Toast.makeText(getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_settings:
return true;
return super.onOptionsItemSelected(item);
否则你的所有代码都是完美的!不需要改变 naythig
@JonasSeputis:我已经使用了你的活动并在 android 设备中运行它显示的 toast “单击后退按钮”检查下面的代码并评论其他代码一段时间
public class MainActivity extends AppCompatActivity
private DrawerLayout mDrawerLayout;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null)
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
/*DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener()
@Override
public void onBackStackChanged()
toggle.setDrawerIndicatorEnabled(getSupportFragmentManager().getBackStackEntryCount() == 0);
);*/
@Override
public boolean onOptionsItemSelected(MenuItem item)
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
//int id = item.getItemId();
//noinspection SimplifiableIfStatement
/*if (id == R.id.action_settings)
return true;
*/
switch (item.getItemId())
// Respond to the action bar's Up/Home button
case android.R.id.home:
Toast.makeText(getApplicationContext(), "Back button clicked", Toast.LENGTH_SHORT).show();
return true;
case R.id.action_settings:
return true;
return super.onOptionsItemSelected(item);
【讨论】:
从 onOptionsItemSelected(MenuItem item) 中删除您的 switch 语句,并像以前一样将 R.id.home 放入您的 if 逻辑中。 @Stanojkovic: android.R.id.home 在点击操作栏图标时使用 R.id.home 在其 id 来自 xml 文件时使用。所以我在答案中写的都是正确的 要显示吐司试试这个 Toast.makeText(getActivity(),"Back button clicked", Toast.LENGTH_SHORT).show(); 我从来没有说过你的答案是错误的或不正确的。 @Stanojkovic:您是在阅读答案还是只是在没有阅读的情况下评论所有地方?【参考方案4】:在你的
@Override
public boolean onOptionsItemSelected(MenuItem item)
if (id == android.R.id.home)
// add intent to class you wish to navigate
Intent i = new Intent("com.your.package.classname");
startActivity(i);
【讨论】:
【参考方案5】:只需添加这一行
onCreate
:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
【讨论】:
以上是关于如何在导航栏中添加返回按钮箭头功能的主要内容,如果未能解决你的问题,请参考以下文章