Just a beginner at Android development. I've currently got a GridView setup to act as a main menu for my application. I've managed to get an intent working using OnItemClickListener(). 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?
MainActivity:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener() {
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);
startActivity(i);
}
});
ImageAdapter:
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to our images
private Integer[] mThumbIds = {
R.drawable.icon, R.drawable.icon,
R.drawable.icon, R.drawable.icon,
R.drawable.icon, R.drawable.icon,
};
class MyOnClickListener implements OnClickListener
{
private final int position;
public MyOnClickListener(int position)
{
this.position = position;
}
public void onClick(View v)
{
}
}
Edit: After hours searching, I found that this works!:
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);
}
You have
so make use of the
int position
part of it...