Android: Hide button from another activity

2019-09-11 04:54发布

问题:

I have 2 activities. Initially the button in first activity is invisible. What I want is that when I click a button in the second activity then the button in my first activity should become visible.

This is my second activity code till now.

this.promodeimage.setOnClickListener(new OnClickListener() {
    public void onClick(View view) {
        ///What should i do in here 
     }
});

回答1:

Do one thing ! its easy .. just make the button in your first activity as public static

public class Activity_One extends Activity {

public static Button btnOne ;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_one);


       btnOne = (Button) findViewById(R.id.btnOne);
}

Now all you need to do is that from Second Activity just access it using the class name of the first activity i.e Activity_One.btnOne

public class Activity_Two extends Activity {

     Button btnTwo ;

    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_one);


           btnTwo = (Button) findViewById(R.id.btnTwo);

btnTwo.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Activity_One.btnOne.setVisibility(View.GONE);
            }
        });
    }

Let me know if this works for you ! :)



回答2:

To solve this problem make your button static in your first activity like:

public class FirstActivity extends Activity { 

public static Button yourButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yourlayout);

        yourButton = (Button) findViewById(R.id.yourButtonId);
    }
}

this way u can get to the button in ur second activity like this:

FirstActivity.yourButton.setVisibility(View.GONE);    //Make it invisible
FirstActivity.yourButton.setVisibility(View.VISIBLE); //Make it visible

Hope this solves your problem.



回答3:

In your First Activity, check in the onCreate() using

if(getIntent().getExtras().getString("modepro").equals("yes")){

    yourButton.setVisibilty(View.VISIBLE)
}


回答4:

You can use something like this whenever you need to implement your logic.

 yourButton.setEnabled(true)--->Here is enabled.
 yourButton.setEnabled(false)---> Here is disabled.

Good Luck.!