How to open layout on button click (android)

前端 未结 3 1453
自闭症患者
自闭症患者 2020-12-28 16:48

How can I open another layout xml file when I click on a button in main.xml file?

so if I have main.xml which has a button sying click here and I click it, it opens

3条回答
  •  感情败类
    2020-12-28 17:14

    First Create your two layout:

    main.xml

    
    
    
        
    
               
    
    
    

    second.xml

    
    
    
        
    
               
    
    
    

    Second Add your Activity to the manifest file

    
    
        
            
                
                    
                    
                
            
            
        
        
    
    

    Activity1.java

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    
    public class Activity1 extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
    
            Button next = (Button) findViewById(R.id.Button01);
            next.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    Intent myIntent = new Intent(view.getContext(), Activity2.class);
                    startActivityForResult(myIntent, 0);
                }
    
            });
        }
    }
    

    To switch to Activity2 you have to:

    1. Gets a reference to the button with ID Button01 on the layout using (Button) findViewById(R.id.Button01).

    2. Create an OnClick listener for the button.

    3. And the most important part, creates an “Intent” to start another Activity. The intent needs two parameters: a context and the name of the Activity that we want to start (Activity2.class)

    Activity2.java

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    
    public class Activity2 extends Activity {
    
        /** Called when the activity is first created. */
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.second);
    
            Button next = (Button) findViewById(R.id.Button02);
            next.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    Intent intent = new Intent();
                    setResult(RESULT_OK, intent);
                    finish();
                }
    
            });
        }
    

提交回复
热议问题