用法如下:
MainActivity.java
package com.example.flowercatswets.myapplication; import android.graphics.Color; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.*; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LinearLayout rootLayout=(LinearLayout)findViewById(R.id.root); View view; LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.childlayout, null); TextView childtext=(TextView)view.findViewById(R.id.text); childtext.setText("I am child view"); ImageView ivColor= (ImageView)view.findViewById(R.id.mycolor); ivColor.setBackgroundColor(Color.GREEN); rootLayout.addView(view); } }
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/root" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textAppearance="?android:attr/textAppearanceMedium" android:id="@+id/test" android:text="in the main layout" /> </LinearLayout>
childlayout.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/text" /> <ImageView android:id="@+id/mycolor" android:layout_width="100dp" android:layout_height="100dp" /> </LinearLayout>
執行結果:
參考資料:
http://stackoverflow.com/questions/2335813/how-to-inflate-one-view-with-a-layout
沒有留言:
張貼留言