Question

I want to position a View horizontally centered in a Layout. My code below fails. How can I fix this?

See my code:

LinearLayout LLT = new LinearLayout(context);
LLT.setOrientation(LinearLayout.VERTICAL);
LLT.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

//get booktheme by bookID 
theme = db.getthemeByID(id);
String themePath = theme.getFilepath();
int resid = getResources().getIdentifier(themePath, "drawable", getPackageName());
//imageView
ImageView imageTheme = new ImageView(context);
imageTheme.setLayoutParams(new LayoutParams(500, 700));
imageTheme.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageTheme.setPadding(0, 20, 0, 10);
imageTheme.setAdjustViewBounds(true);
imageTheme.setImageResource(resid);

LLT.addView(imageTheme);
// add view 
VF.addView(LLT);
Was it helpful?

Solution

Use Gravity feature in your LayoutParams as following:

LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(500, 700);
layoutParams.gravity=Gravity.CENTER_HORIZONTAL;
imageTheme.setLayoutParams(layoutParams);

Replace your code with this one and try:

LinearLayout LLT = new LinearLayout(context);
    LLT.setOrientation(LinearLayout.VERTICAL);
    LLT.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));



    //get booktheme by bookID 
    theme = db.getthemeByID(id);
    String themePath = theme.getFilepath();
    int resid = getResources().getIdentifier(themePath, "drawable", getPackageName());
    //imageView
    ImageView imageTheme = new ImageView(context);
    LinearLayout.LayoutParams layoutParams=new LinearLayout.LayoutParams(500, 700);
    layoutParams.gravity=Gravity.CENTER_HORIZONTAL;
    imageTheme.setLayoutParams(layoutParams);
    imageTheme.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    imageTheme.setPadding(0, 20, 0, 10);
    imageTheme.setAdjustViewBounds(true);
    imageTheme.setImageResource(resid);

    LLT.addView(imageTheme);
    // add view 
    VF.addView(LLT);

OTHER TIPS

have you tried using relative layout instead of linear layout ?

EDIT : if u want to use relative layouts ,

RelativeLayout.LayoutParams layoutParams = 
    (RelativeLayout.LayoutParams)imageview.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
imageview.setLayoutParams(layoutParams);

( did not test the code btw but i used it in one of my app so this shld do the job )

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top