0

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

Villat
  • 1,455
  • 1
  • 16
  • 33

2 Answers2

3

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;
}
}
younes zeboudj
  • 856
  • 12
  • 22
  • That works! Another question, there are 3 thread in total, one for set the visibility to GONE, other to do my work, and the last for set the visibility back again. Is it possible to do the same in 2 threads? – Villat Jul 29 '16 at 22:54
  • 1
    in reality there is just 2 thread, the UI Thread and the second thread for your work, `runOnUiThread` doesn't create a new thread but just post the code inside its `run` method to the UI Thread. from the doc about `runOnUiThread` method : _Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread._ – younes zeboudj Jul 30 '16 at 08:21
0

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;
    }
}
Md Sufi Khan
  • 1,751
  • 1
  • 14
  • 19