这个问题在小米Miui 9.2上出现了,设置SearchView固定高度为30dp,看下面的布局文件和大红图片中的文字显示效果。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff0000"
tools:context="android.touwho.myapplication.MainActivity">
<SearchView
android:id="@+id/subject_search_view"
android:layout_width="match_parent"
android:layout_height="30dp"
android:iconifiedByDefault="false"
android:focusable="false"
android:layout_marginRight="5dp"
android:layout_marginLeft="5dp"
android:background="@drawable/shape_corner"
android:layout_centerInParent="true" />
</RelativeLayout>
解决方法:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SearchView searchView = findViewById(R.id.subject_search_view);
int search_mag_icon_id = searchView.getContext().getResources().getIdentifier("android:id/search_mag_icon", null, null);
ImageView mSearchViewIcon = (ImageView) searchView.findViewById(search_mag_icon_id);
//可以看到左边搜索图标的布局不存在这个问题,这里可以将这个图标的布局参数调出来对比
android.widget.LinearLayout.LayoutParams layoutParams = (android.widget.LinearLayout.LayoutParams) mSearchViewIcon.getLayoutParams();
int id = searchView.getContext().getResources().getIdentifier("android:id/search_src_text",null,null);
TextView searchTextView = (TextView) searchView.findViewById(id);
//获取出SearchView中间文本的布局参数,跟上面的图标布局文件进行对比
android.widget.LinearLayout.LayoutParams textLayoutParams = (android.widget.LinearLayout.LayoutParams) searchTextView.getLayoutParams();
//发现textLayoutParams中的高度是固定108的,而图标的布局文件的高度是-2也就是WrapContent,将文本的高度也改成WrapContent就可以了
textLayoutParams.height = textLayoutParams.WRAP_CONTENT;
searchTextView.setLayoutParams(textLayoutParams);
searchTextView.setTextSize(15);
searchTextView.setHint("搜索关键字");
// 去掉searchView输入框的横线
if (searchView != null) {
try { //--拿到字节码
Class<?> argClass = searchView.getClass();
//--指定某个私有属性,mSearchPlate是搜索框父布局的名字
Field ownField = argClass.getDeclaredField("mSearchPlate");
//--暴力反射,只有暴力反射才能拿到私有属性
ownField.setAccessible(true);
View mView = (View) ownField.get(searchView);
//--设置背景
mView.setBackgroundColor(Color.TRANSPARENT);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}