简体   繁体   中英

OnClick() isn't working

I'm having trouble taking in text from a few text boxes with one button. I can't seem to get OnClick() to work. I have setContentView(R.layout.activity_load_xactivity); as a test I know it doesn't have anything to do with input.

Button button = (Button)findViewById(R.id.create);
button.setOnClickListener(new View.OnClickListener(){
     public void onClick(View v){
         setContentView(R.layout.activity_load_xactivity);
     }
});

Is in my protected void onCreate(Bundle savedInstanceState). Doesn't work. No errors, just doesn't do anything.

Button button = (Button)findViewById(R.id.create);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v){
        setContentView(R.layout.activity_home2);
    }
});

On It's own Doesn't resolve setOnClickListener. I have import android.view.View.OnClickListener set. I've tried entering different code where it says setContentView(R.layout.activity_home2);

Try adding an ID to the Layout holding the Views, Buttons ( RelativeLayout , ContrasintLayout ect...) in XML. Then in java make a new Layout , and use layout.addContentView(XML) in your button:

Layout a = findViewById(R.id.layout_name);//Use whatever layout TYPE is used in XML

Button button = (Button)findViewById(R.id.create);
button.setOnClickListener(new View.OnClickListener(){
  public void onClick(View v){
    a.addContentView(R.layout.activity_load_xactivity);
 }
});

Also, In you XML, you should give an ID to your layout then define it in java.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/layout_name">
 <!--You can use any Layout Type -->                                                      
 ...

</RelativeLayout>

EDIT:

I know this has nothing to with your question, but if you want to switch activity's use this instead:

Intent b = new Intent(this, JavaActivtyName.class);
startActivity(b);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM