How to keep expanded SearchView on the right side of ActionBar (while using custom icon)?

前端 未结 3 782
梦谈多话
梦谈多话 2020-12-18 01:15

My question is closely related to SearchView wrong alignment and SearchView positions when expanded in ActionBar but the answers posted there do not work.

So, I\'m u

相关标签:
3条回答
  • 2020-12-18 01:45

    Alright, I found a way:

    In onCreateOptionsMenu(), after the standard menu inflating stuff, set ActionBar.LayoutParams with Gravity.RIGHT for the SearchView instance:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {        
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_activity_actions, menu);
    
        // ...
    
        // Find the SearchView; make it aligned to right, also in expanded mode:
        MenuItem item = menu.findItem(R.id.action_search);
        SearchView search = (SearchView) item.getActionView();
        search.setLayoutParams(new ActionBar.LayoutParams(Gravity.RIGHT));
    }
    

    (In the menu definition XML, I still use android:showAsAction="ifRoom|collapseActionView".)

    Now the SearchView opens on the right, in the same place where the icon is, and the custom icon is still in use.

    0 讨论(0)
  • 2020-12-18 01:52

    Try editing this line

    android:showAsAction="ifRoom|collapseActionView"
    

    to:

    android:showAsAction="ifRoom"
    

    it will align the edittext to the right.

    0 讨论(0)
  • 2020-12-18 02:00

    Using this worked for me:

    final SearchView searchView = (SearchView) searchMenuItem.getActionView();
    searchView.setOnSearchClickListener(new View.OnClickListener()
    {
         @Override
         public void onClick(View v)
         {
             searchView.setLayoutParams(new Toolbar.LayoutParams(Gravity.END));
         }
    });
    
    0 讨论(0)
提交回复
热议问题