Top Menu

Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Thursday 15 January 2015

Open a new activity for each button of the GridView

This is  a GridView setup to act as a main menu for any application. Now you've to manage to get an intent working using OnItemClickListener() or OnClickListener(). However all 6 of my images when clicked go to the same Activity class. How do I go about giving each image an intent to different activities?
MyOnClickListener.class
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;

public class MyOnClickListener implements OnClickListener {


private final int position;  

    public MyOnClickListener(int position)  
    {  
        this.position = position;  
    }  

    public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent intent = new Intent(v.getContext(), WordsList.class);
        v.getContext().startActivity(intent);
    }

}
The Solution for this are:
1. 
public class MyOnClickListener implements OnClickListener {


private final int position;  

public MyOnClickListener(int position)  
{  
    this.position = position;  
}  

public void onClick(View v) {
    // TODO Auto-generated method stub
    switch(position){
        case 0:
        Intent a = new Intent(v.getContext(), WorldList.class);
        v.getContext().startActivity(a);
        break;
    case 1:
        Intent b = new Intent(v.getContext(), About.class);
        v.getContext().startActivity(b);
        break;  

     }
  }
}
2. Or something like :
private Class[] activities = {
    Activity1.class,   // position=0
    Activity2.class,   // position=1
    //...
    };

public void onClick(View v) {
    Intent intent = new Intent(v.getContext(), activities[position]);
    v.getContext().startActivity(intent);
}
3. public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
           Toast.makeText(nclApp2.this, "" + position, Toast.LENGTH_SHORT).show();
           //Intent i = new Intent(nclApp2.this, Screen2.class);

           Intent myIntent = null;
           if(position == 0){
               myIntent = new Intent(v.getContext(), Screen1.class);
           }
           if(position == 1){
               myIntent = new Intent(v.getContext(), Screen2.class);
           }
           if(position ==2){
               myIntent = new Intent(v.getContext(), Screen3.class);
           }
           startActivity(myIntent);
       }
4. One more 
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
so make use of the int position part of it...
switch (position) {
case 0:
// start one activity
break;
case 1:
// start another activity
break;
// etc.

No comments:

Post a Comment