How can I detect a click on the ActionBar title?

后端 未结 3 1921
感动是毒
感动是毒 2020-12-03 06:33

For specific customer requirement, I need to allow the user of my app ( won\'t be published in Market) to click on the ActionBar title to execute some actions.

I hav

3条回答
  •  遥遥无期
    2020-12-03 07:13

    You can set up a custom toolbar from Support Library by declaring in your layout (see Chris Banes' answer for full toolbar layout example).

    
    
            
            
    
           
    
    
    
    

    After you can add on click listener in your activity just like to most other Views.

    Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
    setSupportActionBar(toolbar);
    toolbar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(MyActivity.this, "Test", Toast.LENGTH_LONG).show();
                }
            });
    

    If you want to capture touch events on title:

    toolbar.setOnTouchListener(new View.OnTouchListener() {
                Rect hitrect = new Rect();
                public boolean onTouch(View v, MotionEvent event) {
                    if (MotionEvent.ACTION_DOWN == event.getAction()) {
                        boolean hit = false;
                        for (int i = toolbar.getChildCount() - 1; i != -1; i--) {
                            View view = toolbar.getChildAt(i);
                            if (view instanceof TextView) {
                                view.getHitRect(hitrect);
                                if (hitrect.contains((int)event.getX(), (int)event.getY())) {
                                    hit = true;
                                    break;
                                }
                            }
                        }
                        if (hit) {
                            //Hit action
                        }
                    }
                    return false;
                }
            });
    

提交回复
热议问题