Click on the button does nothing

Asked

Viewed 382 times

1

I put a button on activity_main and I made a second canvas. The idea was, by clicking the button, to press this other screen. And in the class MainActivity.java I put that when I hit the button, I would load the screen. But when you click the button, absolutely nothing happens.

Does anyone there have any idea what it might be?

public class MainActivity extends Activity {
Button btCadastro;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btCadastro = (Button) findViewById(R.id.btCadastro);
    btCadastro.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            chamaCadastro();

        }
    });
    if (savedInstanceState == null) {
        getFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }

}
public void chamaCadastro(){

    setContentView(R.layout.telacadastro);
}

2 answers

4


The problem in this case is that you will not be able to use the setContentView after initializing the Activity in the onCreate.

You will have to start a new Activity with that layout. And it can be done that way:

public void chamaCadastro(){
    Intent intent = new Intent(this, CadastroActivity.class);

    startActivity(intent);
}

Oh yeah, in that CadastroActivity, will have its layout of the telacadastro. Initializing as:

public class CadastroActivityextends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.telacadastro);
    }
}

I recommend this approach because you can make your application much more modular and with low coupling and reuse, as well as separate the logic of each screen much more easily.

As you mentioned that was beginner, recommend reading the guides Android, in particular the about Activity

  • @Walkim I’ll take a look at this part of the documentation. Thanks for the help!

2

Apparently you want to start a new screen (Activity). right?

To start a new screen(Activity on android) you have to do so:

public void chamaCadastro(){
    Intent intent = new Intent(getApplicationContext(), CadastroActivity.class);
    this.startActivity(intent);
}

In case you would have to create the Activity CadastroActivity.

I recommend taking a look at the Android documentation, the method startActivity(Intent Intent)

  • Got it. I’m going to create this new Activity and test it. Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.