在Android开发过程中,我们可能会做一个对话框,让用户输入一个值,例如:如果想添加一个相册,让用户输入相册的名字“XXX”,然后生成一个名字为“XXX”的相册。可是在做练习的时候却遇到了取不到对话框里值的问题。

想理解这个问题,首先需要了解在Android中有输入框的对话框是怎么生成的,如下:

在类的开始声明:

private EditText etname;

private View dialogView;

private EditText etname;

private String newName;

在类A中代码:

LayoutInflater factory = LayoutInflater.from(A.this);
dialogView = factory.inflate(R.layout.f, null);

AlertDialog f_new = new AlertDialog.Builder(A.this)
.setTitle("新建")
.setIcon(R.drawable.star)
.setView(dialogView)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
etname= (EditText)dialogView.findViewById(R.id.etname);
newName=etname.getText().toString();

}
}

)//确定设置完
.setNegativeButton("取消",null)//取消设置完
.show();

类A的布局文件是:f_menu.xml

setContentView(R.layout.f_menu);

对话框里的布局文件f.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:background="#ffffffff"
android:orientation="horizontal">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="@+id/f_rname"
android:text="名字:"
android:textSize="20sp"
/>
<EditText
android:id="@+id/etname"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:minWidth="200dip"
/>
</LinearLayout>

在对话框中又输入框,其实是在对话框中加入了一个布局文件用对话框的serView()方法实现的,如:.setView(dialogView)。

布局文件里有EditText,让用户输入值。

因此如果要想取到对话框里EditText里的值,就需要findViewById的上下文环境是对话框。这样在找标签的时候就是去到对话框的布局文件里找,即dialogView,而不是在对话框所在的类A的布局文件即f_menu.xml里找,因此该用如下语句:etname= (EditText)dialogView.findViewById(R.id.etname);而不能用默认的etname= (EditText)findViewById(R.id.etname);

更多相关文章

  1. 一款常用的 Squid 日志分析工具
  2. GitHub 标星 8K+!一款开源替代 ls 的工具你值得拥有!
  3. RHEL 6 下 DHCP+TFTP+FTP+PXE+Kickstart 实现无人值守安装
  4. Linux 环境下实战 Rsync 备份工具及配置 rsync+inotify 实时同步
  5. android源码下载及编译
  6. Android移动安全(一)Android混淆机制
  7. 2011/06/13 android使用html做UI的方法---js与java的相互调用
  8. Android(安卓)仿qq聊天界面之一
  9. Android:让WebView支持元素,实现文件上传

随机推荐

  1. android下面res目录使用
  2. android动态壁纸学习
  3. Android中使用OpenCV检测人脸(Android stu
  4. android animation的两种应用实例
  5. Android学习之ProgressDialog
  6. Android中文API(128) —— HandlerThread
  7. listview 左滑弹出删除按钮,需要折腾一下
  8. Activity从入门到放弃
  9. android opengl es 蒙版效果
  10. Unity-Android通信:AndroidJava 使用Unity