现在的位置: 首页 > 综合 > 正文

android 从xml中读出一个View再添加到另一个xml中

2013年08月21日 ⁄ 综合 ⁄ 共 1747字 ⁄ 字号 评论关闭

比如现在有两个xml文件main1.xml和main2.xml,需要将main2.xml中的一个view添加到main1.xml中

例如main1.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:id="@+id/relative">
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world"
        tools:context=".MainActivity" />
</RelativeLayout>   
   main2.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" 
    android:id="@+id/linear"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    >
     <com.symbol.seekbartest.SeekBar
      android:id="@+id/verseekbar"
      android:layout_width="40dp"
      android:layout_height="180dp"
      android:layout_marginLeft="15dp"
      android:layout_marginTop="72dp"
      android:maxHeight="40dip"
      android:minHeight="40dip"
      android:thumb="@drawable/thumbround1"   
      android:thumbOffset="0dip" 
      android:progressDrawable="@layout/seekbar_style"
      />   
</LinearLayout>
解决该问题的思路:
(当以main1.xml为主界面时)
在Activity中:
1、首先应该用LayoutInflater获取到main2.xml
View view=LayoutInflater.from(this).inflate(R.layout.main2, null);
2、得到main2中要添加的对象
SeekBar seek = (SeekBar) view.findViewById(R.id.verseekbar); 
3、实例化main1.xml和main2.xml中的布局对象
RelativeLayout relative = (RelativeLayout) findViewById(R.id.relative);
LinearLayout linear = (LinearLayout) view.findViewById(R.id.linear);
4、先从main2.xml中的布局文件中将要添加的控件remove掉
linear.removeView(seek);
5、最后将该控件添加到main1.xml布局当中就ok了
relative.addView(seek);

抱歉!评论已关闭.