android RecyclerView 里面嵌套editText,点击RecyclerView内部其他控件不会收起键盘
时间: 2023-07-27 10:11:05 浏览: 205
这个问题可以通过对RecyclerView和EditText的事件监听来解决。
首先,需要在RecyclerView的Adapter中为EditText设置焦点变化监听器,当EditText失去焦点时,隐藏软键盘。示例代码如下:
```java
public class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
private Context mContext;
private List<String> mData;
public MyAdapter(Context context, List<String> data) {
mContext = context;
mData = data;
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_layout, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
holder.editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
hideKeyboard(v);
}
}
});
}
@Override
public int getItemCount() {
return mData.size();
}
private void hideKeyboard(View view) {
InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
```
接下来,在RecyclerView的Item布局中,为除EditText外的其他控件设置点击事件监听器,当点击其他控件时,隐藏软键盘。示例代码如下:
```xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hide Keyboard"
android:onClick="hideKeyboard"/>
</LinearLayout>
```
在Activity中,定义hideKeyboard方法,用于隐藏软键盘。示例代码如下:
```java
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
List<String> data = new ArrayList<>();
for (int i = 0; i < 20; i++) {
data.add("Item " + i);
}
MyAdapter adapter = new MyAdapter(this, data);
mRecyclerView.setAdapter(adapter);
}
public void hideKeyboard(View view) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
```
这样,当点击RecyclerView内部的其他控件时,软键盘就会被隐藏。
阅读全文