Search code examples
androidlayoutviewgravityprogrammatically-created

Android: How to change the gravity of an ImageButton placed into a dynamically created layouts


I have a main dynamically generated LinearLayout containing 4 items : - A TextView (dynamic width) - An ImageView (static width) - A TextView (dynamic width) - An ImageButton (static width)

The 3 first items should be stuck together and the last one should float on the right of the screen.

Name - Rating starts - Number of reviews................. Gmap icon 

Current : Current screen

Expected : Expected screen

I have found a solution calculating the width of the generated items and then using that value to set the width of a layout containing the items 2 and 3 together.


Solution

  • You can try to add a linearlayout instead of your "Gmap icon" and give him following settings

    LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.HORIZONTAL);
    
    layout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
    layout.setGravity(Gravity.RIGHT);
    

    and then put your button in this linearLayout

    layout.addView(myImgButton);