2

アクションバーにメニュー項目があります。onOptionsItemSelected で、メニュー項目の画像を変更したい。

これが私のコードです

    @Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle presses on the action bar items
    switch (item.getItemId()) {
    case R.id.todaySched:{
        viewTodaySched();
        item.setIcon(R.drawable.calendarselected);
        infoLog=(MenuItem)findViewById(R.id.infoLog);
        infoLog.setIcon(R.drawable.book);

        return true;}
    case R.id.infoLog:{
        viewInfoLog();
        item.setIcon(R.drawable.bookselected);
                    todaySched=(MenuItem)findViewById(R.id.todaySched);
        todaySched.setIcon(R.drawable.calenderselected);
        return true;}
    default:
        return super.onOptionsItemSelected(item);
    }
}

しかし、アイコンをクリックしてもアイコンが変わらず、実行時エラーが発生しました。例: todaySched アイコンをクリックすると、infoLog アイテム ID を取得できないようです。

マイ LogCat: LogCat

4

2 に答える 2

6

logcat によると、クラス キャスト例外が発生し、 sharlockactionbarを使用しました。したがって、次のような正しい MenuItem と Menu をインポートしたかどうかを確認してください。

import com.actionbarsherlock.view.MenuItem;
and
import com.actionbarsherlock.view.Menu; 

それ以外の

import android.view.MenuItem;
and
import android.view.Menu;

編集:

ワンクリックで両方のアイコンを変更する方法は次のとおりです。

  private Menu menu;
private MenuItem item1, item2;
Boolean original = true;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getSupportMenuInflater().inflate(R.menu.menu, menu);

    this.menu = menu;
    return true;

}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    if (id == R.id.todaySched) {
        update();

    } else if (id == R.id.infoLog) {

        update();
    }

    return true;

}

private void update() {

    item1 = menu.findItem(R.id.todaySched);
    item2 = menu.findItem(R.id.infoLog);

    if (original) {
        item1.setIcon(getResources().getDrawable(
                android.R.drawable.ic_menu_search));
        item2.setIcon(getResources().getDrawable(
                android.R.drawable.ic_menu_report_image));
        original = false;
    } else if (!original) {

        item1.setIcon(getResources().getDrawable(
                android.R.drawable.ic_menu_my_calendar));
        item2.setIcon(getResources().getDrawable(
                android.R.drawable.ic_menu_info_details));
        original = true;
    }

}

チェックされ、動作しています。今すぐあなたの要件に従ってそれを使用してください..

乾杯....

于 2013-08-18T09:41:55.120 に答える
4

アクション バーの項目を変更するたびに、invalidateOptionsMenu() 関数を呼び出す必要があります。次に、メソッド public boolean onPrepareOptionsMenu(Menu menu) をオーバーライドすると、メニュー項目が取得され、アイコンを設定したり、新しいアクションを作成したり、それらを削除したりできます。それが役に立てば幸い。

于 2014-04-04T11:42:45.470 に答える