在操作栏主页图标上设置OnClickListener会使图标松开按下状态

时间:2012-11-29 09:48:32

标签: android android-actionbar

设置以下内容使主页图标显示按下状态:

actionBar.setHomeButtonEnabled(true);

但是,在设置OnClickListener后,主页图标停止显示按下状态:

ImageView iconImage = (ImageView) activity.findViewById(android.R.id.home);
iconImage.setOnClickListener(new android.view.View.OnClickListener() {
    @Override
    public void onClick(View v) {
    }
});

如何防止禁用按下状态?

2 个答案:

答案 0 :(得分:8)

要处理home图标上的点击,您无需设置onClickListener,您需要执行以下操作。

public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId() == android.R.id.home) { //app icon in action bar clicked; go back
        //do something
        return true;
    }

    return super.onOptionsItemSelected(item);
}

答案 1 :(得分:0)

public class MainActivity extends Activity {

     Fragment fr;
      FragmentManager fm;
      Button btn1,btn2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

          ActionBar actionBar = getActionBar();
         actionBar.setHomeButtonEnabled(true);

        btn1=(Button)findViewById(R.id.button1);
        btn2=(Button)findViewById(R.id.button2);
        fm = getFragmentManager();


        btn1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                     fr = new frag22();
                     FragmentTransaction ft = fm.beginTransaction();
                     ft.replace(R.id.fragment, fr);
                     ft.commit();

            }
        });
    }

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.main, menu);
    // TODO Auto-generated method stub
    return super.onCreateOptionsMenu(menu);
}

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub

          if(item.getItemId() == android.R.id.home) { //app icon in action bar clicked; go back
                //do something

              Toast.makeText(getApplicationContext(), "set click", Toast.LENGTH_LONG).show();
                return true;
            }


        return super.onOptionsItemSelected(item);
    }
}