简体   繁体   English

Android:在Actionbar中为SearchView Widget添加自定义按钮

[英]Android: Add a custom button to SearchView Widget in Actionbar

I would like to add a custom button to SearchView widget. 我想为SearchView小部件添加一个自定义按钮。

Going through source code of search_view layout file I found out that it has a LinearLayout ( submit_area ) that contains submit button and voice button. 通过search_view布局文件的源代码,我发现它有一个包含提交按钮和语音按钮的LinearLayoutsubmit_area )。

So I added a dynamic button to submit_area. 所以我在submit_area中添加了一个动态按钮。 But it doesn't show my dynamically added button because if either submit button or voice button is not enabled then submit_area is invisible. 但它没有显示我动态添加的按钮,因为如果未启用提交按钮或语音按钮,则submit_area将不可见。 So it doesn't matter if I add anything dynamically. 因此,如果我动态添加任何内容都没关系。

SearchView searchView = (SearchView) menuItem.getActionView(); 

int
submit_areaId = searchView.getContext().getResources()
    .getIdentifier("android:id/submit_area", null, null);

Button btnScan = new Button(getActivity());
btnScan.setText(getString(R.string.scan)); submitArea.addView(btnScan);  

However if I just set submit button enabled then it shows submit button as well as my dynamic button, like in the attached photo. 但是,如果我只是设置了提交按钮,那么它会显示提交按钮以及我的动态按钮,如附图所示。

I just want to show my dynamic button only. 我只是想显示我的动态按钮。 Any clue how to achieve that? 任何线索如何实现?

在此输入图像描述

searchView.setSubmitButtonEnabled(false);    
LinearLayout linearLayoutOfSearchView = (LinearLayout) searchView.getChildAt(0);
Button yourButton = new Button(mContext); // and do whatever to your button
linearLayoutOfSearchView.addView(yourButton);

Since a private SearchView class method is setting submit_area Visibility.Gone so we can't do much about it. 由于私有的SearchView类方法正在设置submit_area Visibility.Gone因此我们无法做很多事情。

A quick dirty trick is to set of the default buttons enabled and then set its width and height to 0. Setting Visibility didn't work so have to set height/width. 一个快速的肮脏技巧是设置默认按钮,然后将其宽度和高度设置为0.设置Visibility不起作用,因此必须设置高度/宽度。

I enabled search button and then set its height/width to zero. 我启用了搜索按钮,然后将其高度/宽度设置为零。

int submit_areaId = searchView.getContext().getResources().getIdentifier("android:id/submit_area", null, null);

ImageView submitImage = (ImageView) searchView.findViewById(search_go_btnId);

searchView.setSubmitButtonEnabled(true);

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(0, 0);

submitImage.setLayoutParams(layoutParams);

Now SearchView will show anything that you add in submit_area. 现在,SearchView将显示您在submit_area中添加的任何内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM