0

I have an activity_main.xml with

tools:context="com.example.android.newwine.MainActivity"

and

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="goToNext"/>

In my MainActivity.java file I have

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

and

public void gaNaarNext(View view){
    setContentView(R.layout.activity_main2);
}

I have an activity_main2.xml file with

tools:context="com.example.android.newwine.MainActivity"

When I touch the button next now the activity_main2.xml will be used as ContentView, so that's correct, but when I do anything then (like touching a RadioButton or doing doesn't matter what) in my activity_main2.xml file what calls a method, it says: "New Wine is stopped." Whatever I do what calls a method, the app crashes. I tried much and if I'm going to paste everything I tried here this will be a long, long question:).

But has someone an answer? I really don't know what to do now, so I thought; let's ask something on Stackoverflow. Thanks already!

3 Answers3

1

You might prefer to use another activity or fragments to change your UI as using the method setContentView() multiple times is not recomended because of all the drawing involved.

Since it seems like you don't want to switch activities fragments may be the easiest to use.

This stackoverflow question addresses that matter as well.

Community
  • 1
  • 1
0

After you change your content view, the UI Elements on the screen have changed. All of the variables that you previously set up now point to the old screen - which no longer exists. Once you change your content view, you must set these variables to the correct elements on that layout file. Also, you may want to check out Fragments like Carlos Sifuentes said.

TheAnonymous010
  • 725
  • 7
  • 19
0

When I do anything then (like touching a RadioButton or doing doesn't matter what) in my activity_main2.xml file what calls a method, it says: "New Wine is stopped." Whatever I do what calls a method, the app crashes.

The problem is you have used activity_main2.xml but you did'nt get the reference of RadioButton of activity_main2.xml. You should get all the view reference after setting new layout using setContentView() and then use as per your needs.

Update your gaNaarNext() method as below:

public void gaNaarNext(View view){
    setContentView(R.layout.activity_main2);

    // For example: If your activity_main2 contains radio_button then do this
    RadioButton radioButton = (RadioButton) findViewById(R.id.radio_button);

    radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            // Do something
        }
    });
}

Hope this will help~

Ferdous Ahamed
  • 21,438
  • 5
  • 52
  • 61