【问题标题】:How to add a listener for the up button in ActionBar on Android?如何在 Android 上的 ActionBar 中为向上按钮添加监听器?
【发布时间】:2016-05-23 22:02:20
【问题描述】:

我以这种方式在我的 android 活动的操作栏中添加了向上按钮:

活动:

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

清单:

android:parentActivityName=".MenuActivity">

它工作正常,但现在我想在活动之间添加一个过渡效果。 这种过渡效果很好:

Intent 意图 = new Intent(getApplicationContext(), MenuActivity.class); 开始活动(意图); overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);

但是我应该把这个转换代码放在哪里呢?我没有任何监听操作栏中的后退按钮。

谢谢大家的建议

【问题讨论】:

    标签: java android android-actionbar


    【解决方案1】:

    操作栏中的向上按钮被视为 ID 为 android.R.id.home 的菜单项,您可以在 the docs 中阅读。在那里你可以发现你可以使用这个代码来处理点击它:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            // Respond to the action bar's Up/Home button
            return false;
        }
        return super.onOptionsItemSelected(item);
    }
    

    【讨论】:

      【解决方案2】:

      在命令 setSupportActionBar(toolbar); 之后添加这个;

      toolbar.setNavigationOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                  // your code
              }
          });
      

      【讨论】:

        【解决方案3】:

        如果您的操作栏中有后退按钮,那么您必须在 menu.xml 文件中定义。所以我们必须在java文件中为那个按钮添加监听器。

        menu.xml 的外观如下:

        <menu 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"
        tools:context="com.sknandroidapps.skn.ptternlock.LockScreen">
        <item
            android:id="@+id/action_settings"
            android:orderInCategory="100"
            android:title="@string/action_settings"
            app:showAsAction="never" />
        

        因此,如果您想将侦听器添加到您的 action_settings 按钮,那么您必须这样做:

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            int id = item.getItemId();
        
            noinspection SimplifiableIfStatement
               if (id == R.id.action_settings) {
                 //here you have to put the transiction code.
                 return true;
               }
        
            return super.onOptionsItemSelected(item);
        }
        

        将此应用到您的代码中,让我知道它是否有效。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-07-02
          • 2013-06-29
          • 2014-12-28
          • 2013-10-03
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多