Using a selector for a MenuItem in the ActionBar

后端 未结 3 1754
时光说笑
时光说笑 2020-12-17 05:42

I\'m using ActionBarSherlock. I have a MenuItem, and I want to use a custom selector with only that MenuItem, not the others in the ActionBar. This is the menu code:

3条回答
  •  温柔的废话
    2020-12-17 06:14

    You can change the selector of a particular action bar item by setting a custom ActionView in the code:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getSupportMenuInflater().inflate(R.menu.activity_main, menu);
        MenuItem menuItem = menu.findItem(R.id.menu_include_location);
        ImageView image = new ImageView(this);
        image.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        image.setPadding(16, 0, 16, 0);
        image.setImageResource(R.drawable.ic_launcher);
        image.setBackgroundResource(R.drawable.icon_place_selector);
        image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // ...
            }
        });
        menuItem.setActionView(image);
        return true;
    }
    

    Apply these styles if you want to change the selector for all action bar items:

    
    

提交回复
热议问题