安卓(Android)在AlertDialog中的EditText获取焦点并弹出、隐藏软键盘(输入法软件)

该代码片段是通过AlertDialog实现文件(文件夹)的重命名,弹出AlertDialog后选中文件名,并弹出输入法软件,最终完成重命名。

LayoutInflater inflater = LayoutInflater.from(context);

View dialogview = inflater.inflate(R.layout.create_new_folder_dialog,
null);
Button cancel = (Button) dialogview.findViewById(R.id.create_cancel);
Button ensure = (Button) dialogview.findViewById(R.id.create);
TextView title = (TextView) dialogview.findViewById(R.id.title);
TextView title2 = (TextView) dialogview.findViewById(R.id.title2);
title.setText("重命名");
title2.setText("输入新名字");
ensure.setText("确认");
final EditText newfilename = (EditText) dialogview
.findViewById(R.id.title3);
String filePath = ((NetDiskFragment) getFragment(0)).getFileInfo(p)
.getPath();
filePath = filePath.substring(filePath.lastIndexOf("/") + 1);
try {
filePath = URLDecoder.decode(filePath, "utf-8");
newfilename.setText(filePath);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}


newfilename.setSelection(
0,
(filePath.lastIndexOf(".") == -1 ? filePath.length() : filePath
.lastIndexOf(".")));
newfilename.setFocusable(true);
newfilename.setFocusableInTouchMode(true);

newfilename.requestFocus();

//******************************************************************************************

//弹出输入法软键盘

final InputMethodManager imm = (InputMethodManager) newfilename.getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);

imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,

InputMethodManager.HIDE_NOT_ALWAYS);

//******************************************************************************************

final AlertDialog mDialog = new AlertDialog.Builder(context).create();

mDialog.setView(dialogview, 0, 0, 0, 0);
mDialog.show();
cancel.setOnClickListener(new OnClickListener() {


@Override

public void onClick(View v) {

//***********************************************************************************************

//取消重命名时候隐藏软键盘

imm.hideSoftInputFromWindow(newfilename.getWindowToken(), 0);

mDialog.dismiss();

//*********************************************************************************************

}
});
ensure.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {
String filename = newfilename.getText().toString();
// get download file list.
NewMyInfoDB dlFileDB = new NewMyInfoDB(context);
ArrayList list = dlFileDB.getDownloadFileList();


if (filename.matches(StaticInfo.FILE_NAME_REG_EXP)) {
if (((NetDiskFragment) getFragment(currentFragment))

.newname(filename)) {

//***************************************************************************************************************

//重命名成功时隐藏软键盘

imm.hideSoftInputFromWindow(newfilename.getWindowToken(), 0);

mDialog.dismiss();

//***************************************************************************************************************

} else {


}
} else {

//提示命名不合法

fileNameIllegalReminder(filename);

}
}
});

你可能感兴趣的:(安卓开发)