Search code examples
androidandroid-linearlayoutandroid-relativelayout

Creating multiple views


I am trying to inflate a view multiple times. my view consists of one imageview and a textview below it and placing it at particular position.

Below is my item.xml which I am inflating multiple times:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="100dp"
    android:background="@android:color/holo_blue_dark"
    android:layout_height="100dp">

    <ImageView
        android:layout_gravity="center"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:background="@mipmap/ic_launcher"
        android:id="@+id/imageView"/>

    <TextView
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="20dp"
        android:textSize="12sp"
        android:textStyle="bold"
        android:text="Large Text"
        android:id="@+id/textView" />
</LinearLayout>

Here is my code with inflate:

for (int i = 0; i < 1; i++) {

    final View v = linf.inflate(R.layout.item, null);
    TextView tvs = (TextView) v.findViewById(R.id.textView);
    ImageView ivs = (ImageView) v.findViewById(R.id.imageView);
    tvs.setText(i+"");

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100, 100);

    int w = (mWidth/2)-50;
    int h =(mHeight/2)-50;
    params.leftMargin = w;
    params.topMargin = h;
    Log.e("W-H", mWidth + "-" + mHeight);
    rr.addView(v,params);
}

I am able to place the item.xml successfully but its not fitting screen properly I have set height and width fixed 100dp.

Here is what I am getting here


Solution

  • The constructor for LayoutParams is in pixels, so you have to convert to dps for it to display correctly on your screen. This can be accomplished as in this stackoverflow answer:

    int width_dps = 100;
    int height_dps = 100;
    final float scale = MainActivity.this.getResources().getDisplayMetrics().density;
    int width_pixels = (int) (width_dps * scale + 0.5f);
    int height_pixels = (int) (height_dps * scale + 0.5f);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(width_pixels, height_pixels);
    

    Alternatively, if you are using a fixed size, you can update your xml to allow wrap_content to work correctly. You will be overriding the LinearLayout params, so you can update your subviews:

    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    

    and update a subview (android:layout_width="100dp"):

    <TextView
        android:gravity="center"
        android:layout_width="100dp"
        android:layout_height="20dp"
        android:textSize="12sp"
        android:textStyle="bold"
        android:text="Large Text"
        android:id="@+id/textView" />