Tom
Tom

Reputation: 63

Moving button in application dynamically

 public void changeposition (int button){
    int whichPos = rand.nextInt(3) + 1;
    if(button == 1){
        switch(whichPos) {
            case 1: dirup.setPadding(0, 0, 284, 128);
            case 2: dirup.setPadding(0, 0, 156, 88);
            case 3: dirup.setPadding(0, 0, 24, 128);
        }
    }
}

I am using Relative layout and I have 2 buttons which can move to 3 different locations each with random chance. How can I do it in Java code, the code above does nothing almost, it just makes the text inside my button disappear but leave it on the same place.

 <Button
    android:id="@+id/buttonDirection"
    android:layout_width="70dp"
    android:layout_height="70dp"
    android:layout_alignBaseline="@+id/button4"
    android:layout_alignBottom="@+id/button4"
    android:layout_alignParentEnd="true"
    android:layout_alignParentRight="true"
    android:layout_marginBottom="88dp"
    android:layout_marginEnd="156dp"
    android:background="@drawable/circlered"
    android:rotation="90"
    android:text="@string/direction"
    android:textAlignment="center"
    android:textSize="50sp"
    android:visibility="gone"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    android:layout_marginRight="156dp" />

This is how the button is defined in XML now.

Upvotes: 0

Views: 381

Answers (1)

Tim Freiheit
Tim Freiheit

Reputation: 246

if you set the padding larger than the size of the widget (in your case 70dp * 70dp) the button have not enough space for the text.

in your xml you specify margin which does not change the view bounds and is dependent on the outside view.

to update the margin of a view you need to manipulate the LayoutParams.

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) dirup.getLayoutParams();
params.setMargins(left, top, right, bottom);
dirup.setLayoutParams(params);

Upvotes: 1

Related Questions