Dynamically fill the predefined Relative layout
so i have an relative layout which looks like this..
Click for screenshot
and it's code is:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/imageView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="@drawable/image"
android:scaleType="fitXY" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="New Button"
android:id="@+id/button"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#60000000"
android:textSize="30dp"
android:textAlignment="textEnd"
android:textColor="#ffffff" />
</RelativeLayout>
I've got two things to do firstly use this relative layout again and again dynamically and fill the imageview and textview with different content.
Secondly I want to arrange the Relativelayout dynamically one after another like this.
Use RecyclerView for that
you Can learn them from
http://developer.android.com/reference/android/support/v7/widget/RecyclerView.html
and
http://www.androidhive.info/2016/01/android-working-with-recycler-view/
Best practice is using RecyclerView
for this kind of need. But still you should achieve this by inflating and adding this layout to parent layout.
Imagine you have a model that contains background and text
public class Item {
private String text;
private int background;
public Item (String text_, int background_) {
this.text = text_;
this.background = background_;
}
public String getText() { return this.text; }
public int getBackground() { return this.background; }
}
Let's say you have an ArrayList<Item>
of this object. And you have a parent linear layout.
LinearLayout parentLayout = (LinearLayout)findViewById(R.id.parent_layout);
for (Item item: items) {
View view = getLayoutInflater(null).inflate(R.layout.your_button_layout, parentLayout, false);
TextView text= (TextView) view.findViewById(R.id.text);
ImageView background= (ImageView) view.findViewById(R.id.image);
text.setText(item.getText());
background.setBackground(item.getBackground());
parentLayout.addView(view);
}
You can apply margin & padding attributes to your child layout to have similar look like RecyclerView
下一篇: 动态填充预定义的相对布局