专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > 移动开发

创设自定义对话框

发布时间:2010-05-30 05:29:37 文章来源:www.iduyao.cn 采编人员:星星草
创建自定义对话框

如果你想自定义一个对话框,你可以使用布局元素来创造你的对话框的布局。定义好布局后,将根View对象或者布局资源ID传给setContentView(View).
例如,创建如图所示的对话框:
创建一个xml布局custom_dialog.xml:
view plain
http://schemas.android.com/apk/res/android" 
              android:id="@+id/layout_root" 
              android:orientation="horizontal" 
              android:layout_width="fill_parent" 
              android:layout_height="fill_parent" 
              android:padding="10dp" 
              > 
                   android:layout_width="wrap_content" 
               android:layout_height="fill_parent" 
               android:layout_marginRight="10dp" 
               /> 
                  android:layout_width="wrap_content" 
              android:layout_height="fill_parent" 
              android:textColor="#FFF" 
              /> 
该xml定义了一个LinearLayout中的一个ImageView 和一个TextView。
将以上布局设为对话框的content view,并且定义ImageView 和 TextView的内容:
view plain
Context mContext = getApplicationContext(); 
Dialog dialog = new Dialog(mContext);  
dialog.setContentView(R.layout.custom_dialog); 
dialog.setTitle("Custom Dialog"); 
TextView text = (TextView) dialog.findViewById(R.id.text); 
text.setText("Hello, this is a custom dialog!"); 
ImageView image = (ImageView) dialog.findViewById(R.id.image); 
image.setImageResource(R.drawable.android); 
在初始化Dialog之后,使用setContentView(int),将布局资源id传给它。现在Dialog有一个定义好的布局,你可以使用findViewById(int)来找到该元素的id并修改它的内容。
  使用前面所讲的方法显示对话框。
  一个使用Dialog类建立的对话框必须有一个标题。如果你不调用setTitle(),那么标题区域会保留空白。如果你不希望有一个标题,那么你应该使用AlertDialog类来创建自定义对话框。然而,由于一个AlertDialog使用AlertDialog.Builder类来建立最方便,所以你没有方法使用setContentView(int),而是只能使用setView(View)。该方法接受一个View对象,所以你需要从xml中展开你的根View。
  要展开一个xml布局,使用 getLayoutInflater() (或 getSystemService())取得LayoutInflater,然后调用inflate(int, ViewGroup),第一个参数为布局id,而第二个参数为根view的id。现在,你可以使用展开后的布局来找到View对象并定义ImageView和TextView元素的内容。然后实例化AlertDialog.Builder并使用setView(View)来为对话框设置展开后的布局。例如:
view plain
AlertDialog.Builder builder; 
AlertDialog alertDialog;  
Context mContext = getApplicationContext(); 
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE); 
View layout = inflater.inflate(R.layout.custom_dialog, 
                               (ViewGroup) findViewById(R.id.layout_root)); 
TextView text = (TextView) layout.findViewById(R.id.text); 
text.setText("Hello, this is a custom dialog!"); 
ImageView image = (ImageView) layout.findViewById(R.id.image); 
image.setImageResource(R.drawable.android); 
builder = new AlertDialog.Builder(mContext); 
builder.setView(layout); 
alertDialog = builder.create(); 
使用AlertDialog来自定义对话框,可以利用其内置特性例如按钮、选择列表、标题、图标等。
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: