How to set a button visible from another activity in android

前端 未结 3 1004
北恋
北恋 2021-01-25 03:19

I have a very simple problem. I have a invisible button in my Main Activity, and I have a second Activity that makes that button visible. In the second activity I don´t have a p

3条回答
  •  时光说笑
    2021-01-25 04:00

    You should set up a communication between the 2 activities. You can achieve this with startActivityForResult() and onActivityResult()

    MainActivity:

    public class MainActivity extends Activity {
    
        public static final int REQUEST_CODE_SECOND_ACTIVITY = 100; // This value can be any number. It doesn't matter at all. The only important thing is to have the same value you started the child activity with when you're checking the onActivityResult.
        public static final String SHOW_BUTTON = "shouldShowButton";
    
        private Button mMyButtonToBeHidden;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            mMyButtonToBeHidden = (Button) findViewById(R.id.buttonToBeHidden);
    
            findViewById(R.id.openSecondActivity).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivityForResult(new Intent(MainActivity.this, SecondActivity.class), REQUEST_CODE_SECOND_ACTIVITY);
                }
            });
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == REQUEST_CODE_SECOND_ACTIVITY && resultCode == RESULT_OK) {
                //Check if you passed 'true' from the other activity to show the button, and also, only set visibility to VISIBLE if the view is not yet VISIBLE
                if (data.hasExtra(SHOW_BUTTON) && data.getBooleanExtra(SHOW_BUTTON, false) && mMyButtonToBeHidden.getVisibility() != View.VISIBLE) {
                    mMyButtonToBeHidden.setVisibility(View.VISIBLE);
                }
            }
        }
    }
    

    SecondActivity:

    public class SecondActivity extends Activity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_second);
    
            findViewById(R.id.hide_main_activity_button).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.putExtra(MainActivity.SHOW_BUTTON, true);
                    setResult(RESULT_OK, intent);
                    finish();
                }
            });
        }
    }
    

提交回复
热议问题