一、前言:
最近,在做社区的时候,遇到点击评论的时候,弹起输入框,填写文字,键盘的弹起和隐藏一直控制不好,借用同事的方法,总结使用一下。 效果图如下:二、代码:
1. 主类方法调用:
public class MainActivity extends AppCompatActivity {
//输入弹窗 private InputTextMsgDialog inputTextMsgDialog; private Timer timer; @Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn = findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
showSoft(); } }); } /** * 弹起键盘 */ private void showSoft() {
try {
if (inputTextMsgDialog == null) {
inputTextMsgDialog = new InputTextMsgDialog(MainActivity.this, R.style.dialog_center); inputTextMsgDialog.setHint("请输入聊天内容"); } if (timer == null) {
timer = new Timer(); } timer.schedule(new TimerTask() {
@Override public void run() {
runOnUiThread(new Runnable() {
@Override public void run() {
inputTextMsgDialog.showKeyboard(); } }); } }, 100); inputTextMsgDialog.show(); inputTextMsgDialog.setmOnTextSendListener(new InputTextMsgDialog.OnTextSendListener() {
@Override public void onInputTextString(String msg) {
// LogUtils.d("msg===========" + msg); } @Override public void onClickSend(String message) {
String comment = message.replace(" ", ""); if (!TextUtils.isEmpty(comment)) {
Toast.makeText(MainActivity.this, comment, Toast.LENGTH_SHORT).show(); } else {
Toast.makeText(MainActivity.this, "请输入聊天内容", Toast.LENGTH_SHORT).show(); } } }); } catch (Exception e) {
e.printStackTrace(); } }}
注意:
键盘弹起必须主线程,而且是要延时弹起;
2. stytle 风格 dialog_center
<style name="dialog_center" parent="Theme.AppCompat.Light.Dialog.Alert"> <item name="android:windowFrame">@nullitem> <item name="android:screenOrientation">portraititem> <item name="android:windowIsFloating">trueitem> <item name="android:windowBackground">@nullitem> <item name="android:backgroundDimEnabled">trueitem> <item name="android:windowCloseOnTouchOutside">trueitem> style>
3.InputTextMsgDialog文件
public class InputTextMsgDialog extends AppCompatDialog {
private Context mContext; private InputMethodManager imm; private ScrollViewEditText messageTextView; private TextView confirmBtn; private KeyboardLayout rlDlg; private int mLastDiff = 0; private int maxNumber = 150; public interface OnTextSendListener {
void onInputTextString(String msg); void onClickSend(String message); } private OnTextSendListener mOnTextSendListener; public InputTextMsgDialog(@NonNull Context context, int theme) {
super(context, theme); this.mContext = context; init(); setLayout(); } /** * 最大输入字数 默认200 */ @SuppressLint("SetTextI18n") public void setMaxNumber(int maxNumber) {
this.maxNumber = maxNumber; } /** * 设置输入提示文字 */ public void setHint(String text) {
messageTextView.setHint(text); } /*设置输入的文字*/ public void setText(String text) {