I am working on a project where I am showing multiple image in SwipeView with a button. So whenever the button is clicked a new activity will start according to the position of the image in the array. How to do this?
2 Answers
Set a tag (relevant to the activity being launched) to each ImageView
while inflating, using setTag
method.
In the onClick handler retrive the tag using the getTag
method. Use this information to launch the required activity, using a simple switch case
.
The tag can be anything like activity name, array index etc.
More info: What is the main purpose of setTag() getTag() methods of View?
-
what parameter will I use for the switch case Switch(view .Param)? – Mar 17 '16 at 03:07
With each item in your list, you need a Class
reference on which Activity you want to start, then assign the click listener to pass that Class
to an Intent
and then startActivity
Assuming you have some ArrayList<Class> list
or an ArrayAdapter<SomeObject> adapter
, you could do
public void onClick(View v) {
Class activityClass = list.get(clickPosition);
// Class activityClass = adapter.getItem(clickPosition).getActivityToStart();
Intent intent = new Intent(this, activityClass);
startActivity(intent);
}
You could also use a String tag on the View with the name of a class, but you'll need to catch the ClassNotFoundException
.
public void onClick(View v) {
String className = (String) v.getTag();
Class activityClass = Class.forName(className);
Intent intent = new Intent(this, activityClass);
startActivity(intent);
}

- 179,855
- 19
- 132
- 245
-
How to set for private int []imgID ={R.drawable.img1,R.drawable.img2,R.drawable.img3}; – Mar 17 '16 at 03:03
-
Either make a custom class with a constructor like `MyObject(R.drawable.img1, Activity1.class)` and put those in an `ArrayList
` or have a `private Class[] classes = {Activity1.class, ...}` of the same length – OneCricketeer Mar 17 '16 at 03:07