Java method for android:layout_gravity

前端 未结 6 2048
别跟我提以往
别跟我提以往 2020-12-03 21:07

I would like to know if is there a way to call android:layout_gravity property from a Java method. I didn\'t found any method in Android documentation to do it.

相关标签:
6条回答
  • 2020-12-03 21:21

    Maybe I misunderstand you, but here it is:

    http://developer.android.com/reference/android/widget/TextView.html#setGravity(int)

    0 讨论(0)
  • 2020-12-03 21:24

    before adding the button, you should change the orientation of your layout

    yourbutton.setGravity(Gravity.RIGHT);
    LayoutParams layout = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.RIGHT);
    layout.gravity = Gravity.RIGHT;
    yourbutton.setLayoutParams(layout);
    
    
    yourlayout.setGravity(Gravity.RIGHT);
    yourlayout.addView(yourbutton);
    
    0 讨论(0)
  • 2020-12-03 21:26

    Watchout! This wouldn't work with LinearLayout though. Because LinearLayout.LayoutParams(...) constructor is different from FrameLayout.LayoutParams(...) constructor. The third parameter is not gravity but weight.

         LinearLayout.LayoutParams(int width, int height, float weight)
    

    as opposed to

         FrameLayout.LayoutParams(int width, int height, int gravity)
    

    and this call, despite not producing compiler error is actually wrong:

    lparams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, Gravity.LEFT);
    
    0 讨论(0)
  • 2020-12-03 21:30
    button.setBackgroundResource(R.drawable.sound_on);
            button.setText("On");
            button.setGravity(Gravity.CENTER_VERTICAL| Gravity.RIGHT);
            button.invalidate();
    
    0 讨论(0)
  • 2020-12-03 21:33

    To change the layout_gravity attribute for an existing view:

    Button button = (Button) findViewById(R.id.some_button);
    FrameLayout.LayoutParams params;
    params = (LayoutParams) button.getLayoutParams();
    
    params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
    button.setLayoutParams(params);
    

    The button is contained in a FrameLayout which has a gravity attribute corresponding to the layout_gravity XML attribute. Documentation link.

    0 讨论(0)
  • 2020-12-03 21:41

    Well as far as I understand you looking for this It is for FrameLayout for other layout see appropriate LayoutParams classes. For setting gravity like in your XML use something like:

    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,Gravity.LEFT | Gravity.CENTER_VERTICAL)
    

    followed by addView with newly constructed LayoutParams

    0 讨论(0)
提交回复
热议问题