Click the button does nothing

1

I put a button on activity_main and made a second screen. The idea was to click the button to load that other screen. And in class MainActivity.java I put it on clicking the button, it would load the screen. However, clicking the button does not happen at all.

Does anyone have any idea what it can 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);
}
    
asked by anonymous 28.05.2014 / 15:58

2 answers

4

The problem in this case is that you can not use setContentView after initializing Activity in onCreate .

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

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

    startActivity(intent);
}

Yes, in this CadastroActivity , it will have its telacadastro layout. 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 separating the logics from each screen much more easily.

As you mentioned I was a beginner, I recommend reading the Android guides, especially the Activity

    
28.05.2014 / 16:13
2

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

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

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

In case you would have to create Activity Activity .

I recommend taking a look at the Android documentation in startActivity (Intent intent)

    
28.05.2014 / 16:06