简体   繁体   English

让后退键在自定义工具栏中工作

[英]Getting the Back Key to Work in a Custom Toolbar

I created a toolbar with its own XML layout file. 我创建了一个带有自己的XML布局文件的工具栏。 I include the toolbar in the activity_main layout file. 我在activity_main布局文件中包含工具栏。 In the secondary activity, where the back key on the toolbar should appear, I write: 在辅助活动中,应该出现工具栏上的后退键,我写道:

getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);

I also tried: 我也尝试过:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);

For both, the back arrow appears but does nothing when pressed. 对于两者,后退箭头出现但按下时不执行任何操作。

if you need more info some of my .java files are below: 如果您需要更多信息,我的一些.java文件如下:

MainActivity: 主要活动:

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

public class MainActivity extends AppCompatActivity  {

    private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);


        // Get the ViewPager and set it's PagerAdapter so that it can display items
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        viewPager.setAdapter(new MainFragmentPageAdapterForTabs(getSupportFragmentManager(),
                MainActivity.this));

        // Give the SlidingTabLayout the ViewPager
        SlidingTabLayout slidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
        // Center the tabs in the layout
        slidingTabLayout.setDistributeEvenly(true);
        slidingTabLayout.setViewPager(viewPager);

    }

    public void bodyButtonAction(View view){
        Intent intentBody = new Intent(MainActivity.this, SecActivityBody.class);
        startActivity(intentBody);
    }

    public void mindButtonAction(View view){
        Intent intentMind = new Intent(MainActivity.this, SecActivityMind.class);
        startActivity(intentMind);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.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;
        }

        return super.onOptionsItemSelected(item);
    }


}

My secondary activity where the back arrow should go: 我的辅助活动应该是后退箭头:

import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;


public class SecActivityBody extends AppCompatActivity {

    private Toolbar toolbar;
    //private RecyclerView recyclerView;
    //private SecAdapterBody bodyAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sec_activity_body);
        toolbar = (Toolbar) findViewById(R.id.app_bar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);


        // Get the ViewPager and set it's PagerAdapter so that it can display items
        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        viewPager.setAdapter(new SecFragmentPageAdapterForBody(getSupportFragmentManager(),
                SecActivityBody.this));

    }

activity_main.xml: activity_main.xml中:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.integrativestudios.application.recommender.MainActivity">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <include
            android:id="@+id/app_bar"
            layout="@layout/app_bar" />

        <com.integrativestudios.application.recommender.SlidingTabLayout
            android:id="@+id/sliding_tabs"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="0px"
            android:layout_weight="1"
            android:background="@android:color/white" />

    </LinearLayout>

</RelativeLayout>

secondary xml: 辅助xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.integrativestudios.application.recommender.SecActivityBody">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <include
            android:id="@+id/app_bar"
            layout="@layout/app_bar" />

        <android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="0px"
            android:layout_weight="1"
            android:background="@android:color/white" />


    </LinearLayout>

</RelativeLayout>

In your onOptionsItemSelected() check if the selected button is back by the id, 在你的onOptionsItemSelected()检查所选按钮是否由id返回,

@Override
public boolean onOptionsItemSelected(MenuItem item) {

      int id = item.getItemId();

      if(id == android.R.id.home)
      {
           //perform your operation
      }

      return super.onOptionsItemSelected(item);
}

You need to set the second activity as the child activity of the main(parent) activity for navigating to the logical parent screen in the app's hierarchy by pressing the Up button in the action bar. 您需要将第二个活动设置为主(父)活动的子活动,以便通过按操作栏中的向上按钮导航到应用程序层次结构中的逻辑父屏幕。

For example, here's how you can declare an activity's parent in the manifest: 例如,以下是如何在清单中声明活动的父级:

<application ... >
...
<!-- The main/home activity (it has no parent activity) -->
<activity
    android:name="com.example.myfirstapp.MainActivity" ...>
    ...
</activity>
<!-- A child of the main activity -->
<activity
    android:name="com.example.myfirstapp.DisplayMessageActivity"
    android:label="@string/title_activity_display_message"
    android:parentActivityName="com.example.myfirstapp.MainActivity" >
    <!-- Parent activity meta-data to support 4.0 and lower -->
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.example.myfirstapp.MainActivity" />
</activity>

Then enable the app icon as the Up button by calling setDisplayHomeAsUpEnabled(): 然后通过调用setDisplayHomeAsUpEnabled()启用app图标作为Up按钮:

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_displaymessage);

getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// If your minSdkVersion is 11 or higher, instead use:
// getActionBar().setDisplayHomeAsUpEnabled(true);
}

You need to specify the code that executes the Up navigation. 您需要指定执行Up导航的代码。 Don't forget to add the parent-activity meta-data to the android manifest. 不要忘记将父活动元数据添加到android清单中。

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            Intent parentIntent = NavUtils.getParentActivityIntent(this);
            parentIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
            startActivity(parentIntent);
            finish();
            return true;
    }
    return super.onOptionsItemSelected(item);
}

This is what worked for me with launchMode="singleTop" , but if it works for you, you can try using NavUtils.navigateUpFromSameTask(this) . 这对我来说对launchMode="singleTop" ,但如果它适合你,你可以尝试使用NavUtils.navigateUpFromSameTask(this)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM