如何把一个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对象,然后我们就可以把它添加到任何我们想添加到的容器内。 (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|