Tarikhelian Tarikhelian - 10 days ago 5
Android Question

Dynamiclly create Imgeviews

I have to create Dynamically list of Imageview in a row, There is an other Imageview (dot Drawable) under Each Imageview.
see below pic which is my desired view.

enter image description here

Here is my source.

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

RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
ImageView catImg = new ImageView(getApplicationContext());
catImg.setImageResource(bottDrawableArr[i]);
catImg.setId(View.generateViewId());
int dp = (int) utiles.convertDpToPixel(27, getApplicationContext());
params1.height = dp;
params1.width = dp;
ImageView dotImg = new ImageView(getApplicationContext());
dotImg.setImageResource(R.mipmap.dot);
dotImg.setId(View.generateViewId());

params2.addRule(RelativeLayout.BELOW, dotImg.getId());
dockBg.addView(catImg, params1);
dockBg.addView(dotImg, params2);

}


But I am Unable to get my desire view,

while my views show like this

enter image description here

I tried to put dot under each image but unable to achieve that. any help will be appriciated

Answer

The best way is working with some LinearLayout, something like this:

LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.HORIZONTAL);

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

    LinearLayout layoutChild = new LinearLayout(this);
    layoutChild.setOrientation(LinearLayout.VERTICAL);

    RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
    ImageView catImg = new ImageView(getApplicationContext());
    catImg.setImageResource(bottDrawableArr[i]);
    catImg.setId(View.generateViewId());
    int dp = (int) utiles.convertDpToPixel(27, getApplicationContext());
    params1.height = dp;
    params1.width = dp;
    ImageView dotImg = new ImageView(getApplicationContext());
    dotImg.setImageResource(R.mipmap.dot);
    dotImg.setId(View.generateViewId());

    params2.addRule(RelativeLayout.BELOW, dotImg.getId());
    layoutChild.addView(catImg, params1);
    layoutChild.addView(dotImg, params2);
    layout.addView(layoutChild);
}

dockBg.addView(layout);

Note: it's better to delete the unnecessary properties like setting some rules...

Comments