How to switch beteen Multiple Activities in Android

余生长醉 提交于 2019-12-06 05:29:06

Here's 1 way you could do it below. In this example, you'd put 3 buttons on the screen. These are buttons I defined and laid out in my XML file. Click on any of the 3 different buttons, and it takes you to the corresponding activity.

    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

      // Here is code to go grab and layout the Buttons, they're named b1, b2, etc. and identified as such.     
    Button b1 =(Button)findViewById(R.id.b1);
    Button b2 =(Button)findViewById(R.id.b2);
    Button b3 =(Button)findViewById(R.id.b3);

// Setup the listeners for the buttons, and the button handler      
    b1.setOnClickListener(buttonhandler);
    b2.setOnClickListener(buttonhandler);   
    b3.setOnClickListener(buttonhandler);
}           
    View.OnClickListener buttonhandler=new View.OnClickListener() { 

   // Now I need to determine which button was clicked, and which intent or activity to launch.         
      public void onClick(View v) {
   switch(v.getId()) { 

 // Now, which button did they press, and take me to that class/activity

       case R.id.b1:    //<<---- notice end line with colon, not a semicolon
          Intent myIntent1 = new Intent(yourAppNamehere.this, theNextActivtyIwant.class);
    YourAppNameHere.this.startActivity(myIntent1);
      break;

       case R.id.b2:    //<<---- notice end line with colon, not a semicolon
          Intent myIntent2 = new Intent(yourMainAppNamehere.this, AnotherActivtyIwant.class);
    YourAppNameHere.this.startActivity(myIntent2);
      break;  

       case R.id.b3:  
                Intent myIntent3 = new Intent(yourMainAppNamehere.this, a3rdActivtyIwant.class);
    YourAppNameHere.this.startActivity(myIntent3);
      break;   

       } 
    } 
};
   }

Basically we're doing several things to set it up. Identify the buttons and pull them in from the XML layout. See how each has an id name assigned to it. r.id.b1 by example is my first button.

Then we set up a handler, which listens for clicks on my buttons. Next, need to know which button was pushed. The switch / case is like an "if then". If they press button b1, the code takes us to what we assigned to that button click. Press on b1 (Button 1), and we go to that "intent" or activity we've assigned to it.

Hope this helps a little Don't forget to vote up the answer if it's of any use. I'm just getting started on this stuff myself.

Thanks,

Senthil Mg

let's try to use the code snippet from below url and go through flags from developer guide.

Android; How can I initialise state in one activity, then have another refresh that?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!