如何在导航栏中添加返回按钮箭头功能

9

我是一名初学者程序员,最近刚开始学习安卓开发。看了很多答案,但都不适合我。我已经在我的操作栏中添加了返回箭头按钮,但是无法弄清如何将导航添加到首次加载的屏幕。

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_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include
    layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    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_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="lt.simbal.drawer.MainActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        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_width="wrap_content"
    android:layout_height="wrap_content"
    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_width="match_parent"
android:layout_height="match_parent"
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_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="MAIN_ACTIVITY" />

fragment_demo.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:id="@+id/text"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

nav_header_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="@dimen/nav_header_height"
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_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/nav_header_vertical_spacing"
    android:src="@android:drawable/sym_def_app_icon" />

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/nav_header_vertical_spacing"
    android:text="Android Studio"
    android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    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>


因为不知道想做什么,所以投反对票。是要烤面包还是去上一个或下一个活动。 - Stanojkovic
我需要在选择导航抽屉中的片段时进入我的活动。使用返回按钮,我需要返回到我的activity_main。 - JonasSeputis
在你的DemoFragment中,在onCreateView()方法中添加一行代码setHasOptionsMenu(true); - Stanojkovic
@Stanojkovic:还是没有结果。也许我可以把我的代码发给你,或者在这个问题中发布所有的代码?我猜如果有了所有的代码,你就能告诉我哪里出了问题 :/ - JonasSeputis
将所有活动和清单文件的代码全部添加到此处。 - Stanojkovic
显示剩余3条评论
5个回答

4

请确保按照以下方式声明活动布局 -

<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即可。 - djdance

4

您需要调用setHomeAsUpIndicatorsetDisplayHomeAsUpEnabled

在启用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
@Stanojkovic 谢谢。 - IntelliJ Amiya

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);
}

否则你的代码完美无缺!不需要做任何改变。


@JonasSeputis:我使用了你的活动并在安卓设备上运行,它显示toast "Back button clicked"。请查看下面的代码,并暂时注释其他代码。

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 语句移除,并像之前一样在 if 逻辑中使用 R.id.home。 - Stanojkovic
@Stanojkovic:android.R.id.home是在单击操作栏图标时使用的,而R.id.home是从xml文件中获取其id后使用的。所以无论我在答案中写什么都是正确的。 - Dhaval Parmar
要显示一个Toast,请尝试使用以下代码:Toast.makeText(getActivity(),"Back button clicked", Toast.LENGTH_SHORT).show(); - Stanojkovic
我从未说过你的答案是错误或不正确的。 - Stanojkovic
@Stanojkovic:你是在阅读答案还是随处评论而没有阅读? - Dhaval Parmar
当视图更改为片段时,返回按钮不再显示 Toast :( - JonasSeputis

2
在你的


@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);

        }
}

1
onCreate中添加这一行:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接