Search code examples
androidbuttondynamicposition

Change only buttons position programmatically


I have activity with 3 buttons on the right side of the screen in relative layout, except buttons I have very "fragile" fragment with barcode scanner(happens to throw up when touched programmatically) and custom ListView.

Typical button looks like this:

    <Button
    android:id="@+id/typical"
    android:layout_height="wrap_content"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:onClick="typical"
    android:text="@string/typical" />

Depending on the preference of handedness I want to set button layout parent align from right/end to left/start without touching anything else. How can I do that?

I tried:

    Button typical = (Button) findViewById(R.id.typical);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
    params.addRule(RelativeLayout.ALIGN_PARENT_START);
    params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
    typical.setLayoutParams(params);

But it made my barcode fragment change parameters and cry :( .


Solution

  • Two ideas:

    1. Instead of creating a new layout-params, try instead to use the layout params inside the button already, removing the align right rule, and adding the align left rule.

    2. Instead of playing around with the button's layout params (messing with layout params inside a relative layout can really hurt performance), why not make 2 buttons - one on each side, and always hide one of them?

    Hope this helps.