Android - Hide button during an onClick action

2019-09-10 08:58发布

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

2条回答
Fickle 薄情
2楼-- · 2019-09-10 09:06

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;
    }
}
查看更多
相关推荐>>
3楼-- · 2019-09-10 09:11

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;
}
}
查看更多
登录 后发表回答