简体   繁体   English

如何在Android的操作栏中添加ImageButton?

[英]How can I add an ImageButton to an Actionbar in Android?

I want to customize my Actionbar. 我要自定义我的操作栏。 I want to add an ImageButton in Actionbar, which when clicked goes to another activity. 我想在操作栏中添加一个ImageButton,单击该按钮将转到另一个活动。 My code is as below. 我的代码如下。 I don't know to proceed forward. 我不知道继续前进。 can anyone suggest me step by step what to do. 谁能建议我一步一步去做。

    final ActionBar actionBar = getActionBar();
    actionBar.setBackgroundDrawable(getResources().getDrawable(R.color.blue));

To add a button to action bar, locate the onCreateOptionsMenu method in the activity with the action bar that you want to add the button to. 要将按钮添加到操作栏,请在活动中找到要向其添加按钮的操作栏的onCreateOptionsMenu方法。 Next go to res>menu>main and add the item based on this example: 接下来转到res> menu> main并根据此示例添加项目:

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

    <item
        android:id="@+id/action_settings" //<-- id of the view
        android:orderInCategory="100" //<-- not important for the moment (importance)
        android:showAsAction="never" //<-- this will always put it in overflow. set always to show as action
        android:icon="@drawable/ic_launcher"/> //<-- Icon to display in action bar
        android:title="@string/action_settings"/> //<-- not really important

</menu>

next, we will want to listen for item clicks, so add this method to your activity: 接下来,我们将要侦听项目的点击,因此将此方法添加到您的活动中:

    @Override
      public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        // action with ID action_settings was selected
        case R.id.action_settings:
        // this is where you put your own code to do what you want.
break;
        default:
          break;
        }

        return true;
      } 

And there ya go! 你们去!

You should add a custom view to you action bar inside your activity. 您应该在活动中向操作栏添加自定义视图。

See this : https://stackoverflow.com/a/16029214/713778 看到这个: https : //stackoverflow.com/a/16029214/713778

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

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