How can I loop this process? I want to shrink the size of a textview with each button click

45 Views Asked by At

How can I loop this process? I want to shrink the size of a textview with each button click. It will work for one button click, but will not shrink for each click.

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    Button button2;
    TextView foxHealth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button2 = findViewById(R.id.button2);
        foxHealth = findViewById(R.id.foxHealth);
        int foxStartHealth = 150;
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ViewGroup.LayoutParams params = foxHealth.getLayoutParams();
                params.width = foxStartHealth - 5;
                foxHealth.setLayoutParams(params);
            }
        });
    }
}
2

There are 2 best solutions below

6
sigma1510 On
int foxStartHealth = 150;
    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ViewGroup.LayoutParams params = foxHealth.getLayoutParams();
            params.width = foxStartHealth - 5; //you always restart at 150 here
            foxHealth.setLayoutParams(params);
        }
    });

You always shrink from that original value (foxStartHealth = 150) instead of the newest value.

params.width = params.width - 5;
0
Danny Villa On

params.width = foxHealth.getMeasuredWidth() - 5;

//Using the textview foxHealth instead of the integer foxStartHealth