Getting an image to link to a web page in a GridView on Android?
I have an app with the GridView layout have a single image for testing purposes until I figure out this next step. I have everything set up, but I don't know how implement a design where image A, B, C, D, etc. are clicked result in the user (me) landing on a webpage that I specify. I need each image to link to different locations and I would really appreciate the help to implement this into my code:
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 new ImageView for each item
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(150, 150));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(5, 5, 5, 5);
}
else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to images
private Integer[] mThumbIds = {
R.drawable.A, R.drawable.B,
R.drawable.C, R.drawable.D,
R.drawable.E, R.drawable.F,
R.drawable.G, R.drawable.H,
};
}
Use the getItemId() in your adapter (just return the position) to select the URL you want to go to. Just like you have mThumbIds, just have a parallel array that holds the matching URLs, so when an image is clicked, its corresponding URL can be accessed easily at the same index.
The "zero-work" method of doing this would be to simply launch an Intent that would open the URL in the device's browser from an OnItemClickListener. Something like:
//Obtain a reference to the view in your layout somehow...I chose findViewById()
GridView grid = (GridView)findViewById(R.id.peters_grid);
grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//"position" is the location of the image clicked
String url = arrayOfUrls[position];
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
Where you are grabbing the correct URL for each position from an array of Strings. This is just one idea for getting the right URL...you could construct the proper URL a million different ways, but the key is to pass it to the Intent
and then fire it.
The "little work" version of this would be to create a WebView
in this or another Activity
so you can load the web page and stay within your application code. If the WebView
is in a second Activity
, it would still be best to use an Intent to pass the URL string from the first Activity
to the second.
Hope that Helps!
精彩评论