Android - Hide button during an onClick action

假如想象 提交于 2019-12-12 03:49:59

问题


I need to hide a button during an onClick action like this:

    public void onClick(View view) {
    switch (view.getId()){
        case R.id.button1:

            Button button2 = (Button) findViewById(R.id.button2);
            button2.setVisibility(View.GONE);

            //Some methods
            //...

            button2.setVisibility(View.VISIBLE);

            break;
    }

But the visibility changes only after the onClick, what could I do to hide the button during the onClick?

Thanks


回答1:


of course because you are executing all operation in the same thread you may notice the visibility changement, try this :

public void onClick(View view) {
switch (view.getId()){
    case R.id.button1:

        final button2 = (Button) findViewById(R.id.button2);
        button2.setVisibility(View.GONE);

        setVisibility(GONE);
        new Thread(new Runnable() {
            @Override
            public void run() {
                //your work

                runOnUiThread(new Runnable() { //resetting the visibility of the button
                    @Override
                    public void run() {
                        //manipulating UI components from outside of the UI Thread require a call to runOnUiThread
                        button2.setVisibility(VISIBLE);
                    }
                });
            }
        }).start();

        break;
}
}



回答2:


You may try like below:

@Override
public boolean onTouch(View v, MotionEvent event) {
    switch(v.getId()){
    case R.id.button1: {
        if(event.getAction() == MotionEvent.ACTION_DOWN){

            Button button2 = (Button) findViewById(R.id.button2);
            button2.setVisibility(View.GONE);

            return true;
        } else if(event.getAction() == MotionEvent.ACTION_UP) {

            // some methods

            Button button2 = (Button) findViewById(R.id.button2);
            button2.setVisibility(View.VISIBLE);

            return true;
        }
    return false;
    }
}


来源:https://stackoverflow.com/questions/38667833/android-hide-button-during-an-onclick-action

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