android从Dialog对话框中取得文本文字
android中Dialog对话框获取文本文字,只需要使用editor的getText方法就可以获得,示例如下:
final EditText et = new EditText(this);
et.setText(mSharedPreferences.getString("ipadd", "127.0.0.1"));
//获取ip而已,不用在乎
new AlertDialog.Builder(this).setTitle("请输入IP地址")
.setIcon(android.R.drawable.ic_dialog_info).setView(et)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
//数据获取
//Toast.makeText(TestTabActivity.this, et.getText().toString(),
// Toast.LENGTH_LONG).show();
mEditor.putString("ipadd", et.getText().toString());
//关键在这儿,获取输入框的数据,原来很简单!!
mEditor.commit();
}
}).setNegativeButton("取消", null).show();
1、View注意设置成final类型如final View layout=。。。
2、获取文本框对象时候格式EditText e = (EditText)layout.findViewById(R.id);//这里记好了那个layout 是上面final View对象
不注意上面的你就无法获得对话框中的文本了哦!
private void getWifiInfo() {
// TODO Auto-generated method stub
/**
* 当按返回键时的提示对话框,采用默认样式
*/
LayoutInflater inflater=getLayoutInflater();
final View layout=inflater.inflate(R.layout.dialog, (ViewGroup)findViewById(R.id.dialog));
new AlertDialog.Builder(this).
setTitle("自定义布局").
setView(layout).
setPositiveButton("确定",
new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
EditText et1 = (EditText)layout.findViewById(R.id.wifiname);
EditText et2 =(EditText)layout.findViewById(R.id.wifipassword);
wifiname = et1.getText().toString();
wifipassword=et2.getText().toString();
}})
.setNegativeButton("取消", null).show();
}
实例:
package com.example.mytest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getdialog();
}
private void getdialog(){
final EditText et=new EditText(this);
new AlertDialog.Builder(this).setTitle("请输入面积").setView(et).
setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1){
String size=et.getText().toString();
Log.i("size",size);
}
}).setNegativeButton("取消",null).show();
}
}