android SearchView move searchIcon to right
时间: 2023-06-17 19:08:45 浏览: 223
To move the search icon to the right in an Android SearchView, you can use the following steps:
1. Create a new XML file named `searchview_layout.xml` in your `res/layout` folder.
2. Add the following code to the XML file:
```
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<SearchView
android:id="@+id/search_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:iconifiedByDefault="false"
android:queryHint="Search"
android:layout_gravity="center_vertical" />
<ImageView
android:id="@+id/search_close_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_close"
android:layout_gravity="center_vertical" />
</LinearLayout>
```
3. In your Java code, you can inflate this layout and use the `SearchView` and `ImageView` as you would normally. For example:
```
SearchView searchView = findViewById(R.id.search_view);
ImageView closeButton = findViewById(R.id.search_close_btn);
// Move the search icon to the right
int searchIconId = searchView.getContext().getResources()
.getIdentifier("android:id/search_mag_icon", null, null);
ImageView searchIcon = searchView.findViewById(searchIconId);
searchIcon.setLayoutParams(new LinearLayout.LayoutParams(0, 0));
// Set the close button to close the search view
closeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
searchView.setQuery("", false);
searchView.clearFocus();
}
});
```
This code will move the search icon to the right and add a close button to the left of the search view. When the close button is clicked, the search view will be cleared and the focus will be removed.
阅读全文