最近我在以编程方式包含布局方面遇到了一个问题。
场景:
- 我有主布局和一个子布局。
- 我想以编程方式将子布局包含到主布局中。
- 主布局根是相对布局,子布局根是
framelayout
。 - 我想在主布局底部添加子布局,因为我已将属性添加到子布局。
- 奇怪的是,如果我将子布局静态添加到主布局(在 xml 中使用 include 标记),那么它会按预期工作(坚持到底部)但在以编程方式添加时不起作用。
主布局.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/ly_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AppintroActivity">
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
子布局.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true">
<RelativeLayout
android:id="@+id/ly_bottom_holder"
android:layout_width="match_parent"
android:gravity="bottom"
android:layout_height="@dimen/_50sdp"
android:layout_gravity="bottom">
<View
android:layout_width="match_parent"
android:layout_height="0.5dp"
android:background="@color/dull_black" />
<TextView
android:id="@+id/txt_skip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_centerVertical="true"
android:layout_marginLeft="@dimen/_10sdp"
android:padding="@dimen/_5sdp"
android:text="Skip"
android:textAllCaps="true"
android:textColor="@color/white" />
<ImageView
android:id="@+id/img_next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:padding="@dimen/_5sdp"
android:src="@drawable/forward" />
<LinearLayout
android:id="@+id/dots"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:orientation="horizontal" />
</RelativeLayout>
</FrameLayout>
这就是我使用 java 的方式
LayoutInflater inflater = (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
View bottomlayout = inflater.inflate(R.layout.bottom,(ViewGroup) findViewById(R.id.frame));//bottom is mysublayout.xml
ly_root.addView(bottomlayout);//ly_root is my mainlayout.xml's root element's id
所以请给我建议,我怎样才能通过使用 java 代码获得与使用 xml 完全相同的结果。
最佳答案
我认为您必须使用“LayoutParams”将 View 添加到布局。像这样:
RelativeLayout.LayoutParams par=new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
par.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
ly_root.addView(bottomlayout,par);
关于java - 以编程方式而不是 xml 方式包含时无法获得相同的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38091276/