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

5
我想在SearchView控件中添加一个自定义按钮。
通过查看search_view布局文件的源代码,我发现它有一个LinearLayout(submit_area),其中包含提交按钮和语音按钮。
因此,我将动态按钮添加到submit_area中。但是,如果提交按钮或语音按钮未启用,则submit_area不可见。所以,我添加任何内容都没有意义。
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);  

然而,如果我只设置提交按钮为启用状态,则它会显示提交按钮和我的动态按钮,就像附图中所示。我只想显示我的动态按钮。有什么方法可以实现吗?

你的代码中的"submitArea"是什么?submitArea.addView(btnScan); - pavan kvch
2个回答

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

请在您的答案中添加一些描述,以帮助原帖作者理解解决方案。 - Zo Has
你在问题中没有理解重点。按钮已经添加到视图中了。如果你禁用提交/语音按钮,那么视图将根本不会显示。在我的下面的答案中,展示了如何在不禁用默认按钮的情况下显示自定义按钮。 - Sharjeel

2

由于私有的SearchView类方法设置了submit_areaVisibility.Gone,所以我们无法做太多事情。

一个快速而不太优雅的解决方法是启用默认按钮,然后将其宽度和高度设置为0。设置Visibility没有起作用,因此必须设置高度/宽度。

我启用了搜索按钮,然后将其高度/宽度设置为零。

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);

现在,SearchView会显示您在submit_area中添加的任何内容。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接