1

我有一个使用 ActionBar Sherlock 的 Android 应用程序。我创建了一个具有 ImageButton 的菜单,其状态在可绘制资源文件中定义。(所有这些都粘贴在下面)。

虽然我能够切换 ImageButton 的选定/未选定状态,但单击侦听器似乎没有触发。

创建活动时,我膨胀菜单,获得 ImageButton 并注册事件侦听器。我进行了调试,一切似乎都很好(我正在正确的 ImageButton 上注册事件)。

您认为什么会导致 ImageButton 无法获得 onClick 回调?

干杯....

这是一些代码:

菜单:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@+id/menu_save"
          android:showAsAction="always|withText"           
          android:actionLayout="@layout/menu_my_activity"
          />     
</menu>

menu_my_activity:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/button_with_states"
        android:clickable="true" />    
</LinearLayout> 

和听众的注册:

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = (MenuInflater) this.getMenuInflater();
    inflater.inflate(R.menu.menu_watchlist, menu);
    menu.getItem(0).getActionView().findViewById(R.id.imageButton).setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
      Log.d("Test", "Hello");   
    }
        });

    return super.onCreateOptionsMenu(menu);
}
4

2 回答 2

3

这是我建议的修复方法。确实不需要单独的 actionLayout,因为您想要的结果非常简单。请注意,我们不需要为 ActionBar 创建“ImageView”...该android:icon属性为我们设置了它。用于android:title设置图标的文本。

menu_watchlist.xml:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@+id/image_button"
          android:showAsAction="always|withText"           
          android:title="title"
          android:icon="@drawable/button_with_states" />     
</menu>

设置选项菜单:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_watchlist, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.image_button:
            Log.d("Test", "Hello");
            break; 
    }
    return super.onOptionsItemSelected(item);
}

希望这对你有用!

于 2012-01-17T21:46:02.033 回答
1

当您在 ABS 或本机系统 ActionBar 中按下 ActionView 时,将调用onOptionsItemSelected方法。您不需要手动附加事件侦听器,实际上这种方法不会始终如一地工作。

要侦听 ActionItem 选择:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.menu_save:
            //Save was pressed, call a method
            break;
        case R.id.menu_another_item:
            //A different item was pressed
            break;
    }
    return super.onOptionsItemSelected(item);
}

onOptionsItemSelected 的使用有点违反直觉,但可以追溯到使用菜单的日子,onCreateOptionsMenu 也是如此。

于 2012-01-17T21:32:50.357 回答