我想動態地將佈局添加到MainActivity(Android Studio創建的默認Android應用程序)中,但未顯示新佈局。 我已經嘗試過不同的佈局,但是在〜450px高度後剪裁了一個。當動態添加布局時未顯示
我很新的Android UI編程,我有一種感覺,我在添加函數中做錯了什麼。下面是添加代碼(這是從this answer啓發):
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linlayout);
View v = vi.inflate(R.layout.test_layout, null);
// insert into main view
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(
1000,//ViewGroup.LayoutParams.FILL_PARENT,
1000);//ViewGroup.LayoutParams.FILL_PARENT);
linearLayout.addView(v, 0, layoutParams);
這是activity_main.xml中:
<include
android:id="@+id/include"
layout="@layout/content_main" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
app:srcCompat="@android:drawable/ic_dialog_email" />
<LinearLayout
android:id="@+id/linlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<!--<include layout="@layout/test_layout"/>-->
</LinearLayout>
而這裏的我想補充的佈局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<ImageView
android:id="@+id/imageView2"
android:layout_width="188dp"
android:layout_height="191dp"
app:srcCompat="@mipmap/ic_launcher" />
</RelativeLayout>
如果我添加layou靜態地(在xml中添加<include layout="@layout/test_layout"/>
),test_layout
顯示正確。
我在這裏做錯了什麼?
(使用的Nexus 5X的Android 7.1.2)
你爲什麼不做出ImageView的編程和佈局設置。不需要額外的相對佈局 –
@DivyeshPatel有很多原因。 @Nitay嘗試'linearLayout.addView(v);' – Doomsknight
@Doomsknight剛試過,同樣的問題。 – Nitay