很多项目中会用到评论功能,用户点击评论,一般都会弹出一个输入框,进行输入,例如下图:
这里记录一下这个小demo:
demo地址:https://github.com/midux001/InputDialog
主页面就是用的一个RecyclerView,模拟一些评论数据,当用户点击某一条评论,便自动弹出评论的dialog,并同时dialog被输入法给顶起,便于输入。RecyclerView的用法便不在说了,可以在网上找到很多大神对它的详细介绍与使用。
这里有三个点需要注意的:
1. 自定义的dialog
public class CustomDialog extends Dialog {
EditText et_input;
public CustomDialog(@NonNull Context context) {
this(context, 0);
}
public CustomDialog(@NonNull Context context, int themeResId) {
super(context, themeResId);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.module_dialog_layout);
setCanceledOnTouchOutside(true);
setCancelable(true);
Window window = getWindow();
window.setGravity(Gravity.BOTTOM);//dialog底部弹出
WindowManager.LayoutParams params = window.getAttributes();
params.width = WindowManager.LayoutParams.MATCH_PARENT;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
window.setAttributes(params);
et_input = findViewById(R.id.et_input);
}
}
- activity中对dialog进行初始化的时候,需要设置它的OnKeyListener,如下:
adapter.setmOnItemClickListener(new CustommRecyclerViewAdapter.OnItemClickListener() {
@Override
public void onClick(View view, int position) {
mCustomDialog = new CustomDialog(MainActivity.this, R.style.customdialogstyle);
mCustomDialog.setOnKeyListener(keylistener);
mCustomDialog.show();
}
});
其中的keylistener就是我们需要监听到的按键事件
DialogInterface.OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
Log.i("TAG", "键盘code---" + keyCode);
if (keyCode == KeyEvent.KEYCODE_BACK) {
dialog.dismiss();
return false;
} else if(keyCode == KeyEvent.KEYCODE_DEL){//删除键
return false;
}else{
return true;
}
}
};
关于Android中keyCode的值,在上一篇文章中已经了解过了,转载了其他朋友的博客,有兴趣的朋友可以了解一下,链接如下:https://blog.csdn.net/midux/article/details/80064054
这里有个注意点,在项目中测试的时候,我没有判断keyCode == KeyEvent.KEYCODE_DEL的情况,当在键盘中按推个键时EditText没有反应,只有当我加上判断之后才有对退格键的相应。(回车键也是一样)。