12

I have an action bar that puts everything in a menu in the top right, which the user clicks and the menu options open up.

I inflate the action bar menu with this on each activity I use it:

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main2, menu);

        return true;
    }

And my xml for main2.xml is:

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

    <item
        android:id="@+id/action_searchHome"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:title="Seach"/>



</menu>

My question is do I put an onclick in the item in the xml and if so where do I put the onclick method it calls? Do I need to put it in every activity I launch this action bar in?

4

2 回答 2

32

如果您在菜单项上添加 onClick 属性,如下所示:

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

    <item
        android:id="@+id/action_searchHome"
        android:orderInCategory="100"
        android:showAsAction="never"
        android:onClick="doThis"
        android:title="Seach"/>



</menu>

然后在您的活动中:

public void doThis(MenuItem item){
    Toast.makeText(this, "Hello World", Toast.LENGTH_LONG).show();
}

笔记:

ActionBarSherlock 已弃用。除非您正在为 Android 4.0 或更早版本开发应用程序,否则请不要使用它。但是如果您使用的是库,则必须导入

import com.actionbarsherlock.view.MenuItem;

并不是

import com.android.view.MenuItem;

此外,您可以执行以下操作:ActionBar Sherlock Menu Item OnClick

@adneal 提到的。

于 2013-07-01T03:02:04.993 回答
0

在我看来

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    add_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onCreateDialog(getTaskId());
        }
    });
}


<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=".MainActivity">
<item android:id="@+id/action_settings" android:title="@string/action_settings"
    android:orderInCategory="100" app:showAsAction="never" />
<item android:id="@+id/add_text_id" android:title="Add"
    android:icon="@drawable/ic_add_btn"
    android:orderInCategory="100" app:showAsAction="ifRoom" />

于 2015-06-23T01:09:24.713 回答