To increase a button's size when it is pressed in Android

寵の児 提交于 2020-01-02 14:30:11

问题


How can I make my button's size to increase slightly when it is pressed and decrease again when it is released? This is for highlighting the pressed button, by using size in addition to a different color.

Regards, Kiki


回答1:


Make your Button a field, and modify its size in the OnTouchListener associated with it. Using an OnTouchListener you can listen for different MotionEvents, such as ACTION_DOWN and ACTION_UP.




回答2:


button.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)v.getLayoutParams();

            //Code to convert height and width in dp.
            int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 35, getResources().getDisplayMetrics());
            int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 140, getResources().getDisplayMetrics());

            if(event.getAction() == MotionEvent.ACTION_DOWN){
                layoutParams.width = width + 5;
                layoutParams.height = height + 5;
                SearchButton.setLayoutParams(layoutParams);
            }
            if(event.getAction() == MotionEvent.ACTION_UP){
                layoutParams.width = width;
                layoutParams.height = height;
                SearchButton.setLayoutParams(layoutParams);
            }

            return false;
        }
    });



回答3:


In your activity

Private Button myButton;

//...

protected void onCreate(Bundle savedInstanceState) {

//...

myButton = (Button) findViewById(R.id.my_button);
    _button.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        myButton.setWidth(50);
        myButton.setHeight(50);
        }
      });
    }


来源:https://stackoverflow.com/questions/3778401/to-increase-a-buttons-size-when-it-is-pressed-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!