[英]android: add view to an inflated View
我想從res / layout目錄中擴展一個布局,並在我的activity類中添加一些視圖。
我的布局xml文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_marginTop="30dip"
android:layout_height="fill_parent" >
<Button
android:id="@+id/reg_button"
style="@style/simple_button"
android:onClick="clickButton"
android:text="@string/reg_button" />
<!-- I WANT TO PUT CONTENT HERE ! -->
</LinearLayout>
在我的java代碼中,我嘗試膨脹上面的布局並添加一個帶有Button的linearLayout。
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = getApplicationContext();
//inflate xml
LinearLayout mainLayout = (LinearLayout) LayoutInflater.from(getBaseContext()).inflate(R.layout.regions_search, null);
//Create a new LinearLayout
LinearLayout newLinear = new LinearLayout(mContext);
newLinear.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
//create a new Button
Button test = new Button(mContext);
test.setText("My button");
//first , I add button to the LinearLayout
newLinear.addView(test);
//Then, I add layout to the inflated layout
mainLayout.addView(newLinear);
//display
setContentView(mainLayout);
但是新的線性視圖(及其子視圖)沒有顯示出來。
在你的活動中使用它,
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// display
setContentView(R.layout.activity_main);
Context mContext = getApplicationContext();
LinearLayout mainLayout = (LinearLayout) findViewById(R.id.regions_search);
// Create a new LinearLayout
LinearLayout newLinear = new LinearLayout(mContext);
newLinear.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
// create a new Button
Button test = new Button(mContext);
test.setText("My button");
// first , I add button to the LinearLayout
newLinear.addView(test);
// Then, I add layout to the inflated layout
mainLayout.addView(newLinear);
}
並在您的xml文件(activity_main.xml)中寫入如下所示,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/regions_search"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginTop="30dip"
android:orientation="vertical">
<Button
android:id="@+id/reg_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="clickButton"
android:text="RegButton" />
<!-- I WANT TO PUT CONTENT HERE ! -->
</LinearLayout>
試試這個它將100%工作。
您可以嘗試為新添加的LinearLayout
和Button
添加寬度和高度參數嗎? 創建視圖時需要這些參數。
像這樣。
newLinear.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
test.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,1f));
評論行
的setContentView(mainLayout);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.