自定义Layout xml文件转换成View对象和Activity关联的实现

如何把一个layout文件转换成view对象添加到对应的容器内呢?

下面以一个例子来说明这一点:

主布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="实现Layout和Activity关联"
/>
<Button android:id="@+id/mybutton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="测试"/>
</LinearLayout>

把下面一个xml布局文件添加到AlertDialog中:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/relativeLayout1" android:layout_height="fill_parent" android:layout_width="fill_parent" android:padding="10dip">
<TextView android:id="@+id/textView1" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="TextView"></TextView>
<EditText android:background="@android:drawable/editbox_background" android:id="@+id/entry" android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_below="@+id/textView1" android:layout_alignLeft="@+id/textView1">
<requestFocus></requestFocus>
</EditText>
<Button android:text="确定" android:id="@+id/button1" android:layout_height="wrap_content"
android:layout_width="wrap_content" android:layout_toLeftOf="@id/button1"
android:layout_alignTop="@id/button1"></Button>
<Button android:text="取消" android:id="@+id/button1" android:layout_height="wrap_content"
android:layout_width="wrap_content" android:layout_below="@+id/entry"
android:layout_marginLeft="10dip" android:layout_alignParentRight="true"></Button>
</RelativeLayout>

在Activity如何实现上面布局文件和dialog之间的关联呢 ?

public class Layout_Activity_DialogActivity extends Activity {
private Button mybutton=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mybutton=(Button)findViewById(R.id.mybutton);
mybutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LayoutInflater inflater=(LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view=inflater.inflate(R.layout.view_dialog,null);
new AlertDialog.Builder(Layout_Activity_DialogActivity.this)
.setTitle("My Dialog")
.setMessage("Layout和Dialog关联")
.setView(view)
.show();

}
});
}
}

红色部分的功能就是把一个xml布局文件解析成View对象,然后我们就可以把它添加到任何我们想添加到的容器内。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


php输出xml格式字符串
J2ME Mobile 3D入门教程系列文章之一
XML轻松学习手册
XML入门的常见问题(一)
XML入门的常见问题(三)
XML轻松学习手册(2)XML概念
xml文件介绍及使用
xml编程(一)-xml语法
XML文件结构和基本语法
第2章 包装类
XML入门的常见问题(二)
Java对象的强、软、弱和虚引用
JS解析XML文件和XML字符串详解
java中枚举的详细使用介绍
了解Xml格式
XML入门的常见问题(四)
深入SQLite多线程的使用总结详解
PlayFramework完整实现一个APP(一)
XML和YAML的使用方法
XML轻松学习总节篇