Skip to content Skip to sidebar Skip to footer

Android Studio Onclick And Onclicklistener Not Working Once Changed To Another Activity

I've added my acivity class in this link Click MeI am fairly new to Android and am having difficulty trying to add a button on my second activity. I am able to place a button in my

Solution 1:

just try to do this:

publicclassFirstActivityextendsAppCompatActivity {

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.first_activity);
    findViewById(R.id.about_us).setOnClickListener(newView.OnClickListener() {
        @OverridepublicvoidonClick(View v) {
            startActivity(newIntent(FirstActivity.this, SecondActivity.class));
        }
    });

   }
}

and in second activity again find your button in second activity xml by id and write onClickListener for it

Solution 2:

You need to implement two separate methods for two different buttons. I would suggest do these things in the Java code instead of XML.

You can do some thing like this:

Buttonbutton= findViewById(R.something.something);
button.setOnClickListener(newView.OnClickListener() {

    @OverridepublicvoidonClick(View v) {
        //perform your operation(s) here.
    }
});

Solution 3:

As I understand you try to use one layout.xml for both activities.

You need to declare method click1 in both activities, not only in first.

It means that your first activity has to have method public void click1() and the second activity has to duplicate method public void click1()

Solution 4:

I know it's old however,

@Meikiem idea is great. When you use setContentView(View View) you are just setting the activity's content to another view (xml), and thus not really using the other .java file which has another onClick method defined for the second button. Activity's setContentView(view)

You need to create an Intent and pass it along the startActivity method. Intent Definition

Post a Comment for "Android Studio Onclick And Onclicklistener Not Working Once Changed To Another Activity"