android中自定义的dialog中的EditText无法弹出输入法解决方案

1.解决无法弹出输入法:

在show()方法调用之前,用dialog.setView(new EditText(context))添加一个空的EditText,由于是自定义的AlertDialog,有我们指定的布局,所以设置这个不会影响我们的功能,这样就可以弹出输入法了……

2.可以弹出输入法了,但了为了增强用户体验性,当dialog中含有editText时应该,在显示dialog的同时自动弹出键盘:

(1) 可以在自定义的dialog中增加如下方法:


public void showKeyboard() { 

      if(editText!=null){ 
            //设置可获得焦点 
            editText.setFocusable(true); 
            editText.setFocusableInTouchMode(true); 
            //请求获得焦点 
            editText.requestFocus(); 
            //调用系统输入法 
            InputMethodManager inputManager = (InputMethodManager) editText 
                    .getContext().getSystemService(Context.INPUT_METHOD_SERVICE); 
            inputManager.showSoftInput(editText, 0); 
        } 
    }

 

 

public void showKeyboard() {
		if(editText!=null){
			//设置可获得焦点
			editText.setFocusable(true);
			editText.setFocusableInTouchMode(true);
			//请求获得焦点
			editText.requestFocus();
			//调用系统输入法
			InputMethodManager inputManager = (InputMethodManager) editText
					.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
			inputManager.showSoftInput(editText, 0);
		}
	}
其中editText为自定义dialog中的输入框的view
(2) 在dialog.show()后,调用这个方法显示输入法,由于在调用时可能dialog界面还未加载完成,editText 可能还为空,所以需要加上一个延时任务,延迟显示:

dialog.show(); 
Timer timer = new Timer(); 
timer.schedule(new TimerTask() { 
 
    @Override 
    public void run() { 
        dialog.showKeyboard(); 
    } 
}, 200); 

dialog.show();
Timer timer = new Timer();
timer.schedule(new TimerTask() {

	@Override
	public void run() {
		dialog.showKeyboard();
	}
}, 200);










 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章