Use two SetOnClickListener in the MainActivity

82 Views Asked by At

I am developing an Android app. The topic is a cost manager. I want to use two SetOnClickListener in the mainactivity for two buttons. The first button change the view to a second page (activity). And on this page there is a second button, which just print out an log message. But the app break down and do not throw an error message. The failure has to be in the second onClickListener, because without it, it works. Here is my code:

public class MainActivity extends AppCompatActivity {

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

        // Init all Elements
        Button btn_hinzufügen = (Button) findViewById(R.id.btn_add);
        Button btn_speichern = (Button) findViewById(R.id.btn_speichern);



        btn_hinzufügen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                open_add_data();

            }
        });

        btn_speichern.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("Info", "Say Hello");
            }
        });
    }


    public void open_add_data() {
        setContentView(R.layout.add_data);
    }
}
2

There are 2 best solutions below

2
Hitesh Manwani On

Instead of using setContentView(R.layout.add_data); on button click you should try to manage visibility of both layout.

0
Ajay J G On

Make sure both of your buttons are contained in activity_main.xml layout then only you can instantiate two buttons in same activity. If not move second button to your second activity.