Can anybody tell me how to embed a Gallery
into a ListVview
, so that I can do horizontal scrolling over images inside ListView
?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Check this post, it worked for me.
My setup is as follows:
- I have a
ListActivity
that uses anArrayAdapter
to populate it with data. - My XML resource
list_item
contains an ImageView, TextView and a Gallery. - I add an
OnClickListener
to the row (as you normally would to handle list item clicks.) - Then I set the adapter for the Gallery
- I add a
GestureListener
to the gallery that handles swiping - I add a
OnItemClickListener
to the gallery to handle clicking images in the gallery
In my ArrayAdapter
I do the following:
private static final int SWIPE_MAX_OFF_PATH = 250;
private GestureDetector gestureDetector;
private OnTouchListener gestureListener;
private Gallery picGallery;
...
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
/* Holder pattern here, commented out for clarity */
// We need to set the onClickListener here to make sure that
// the row can also be clicked, in addition to the gallery photos
row.setOnClickListener(new MyOnClickListener(context,position));
// Set the adapter for the gallery
picGallery = (Gallery) row.findViewById(R.id.gallery);
picGallery.setAdapter(
new MyGalleryAdapter(/* some input data here to populate the gallery */));
// GestureDetector to detect swipes on the gallery
gestureDetector = new GestureDetector(new MyGestureDetector());
gestureListener = new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
};
// Detect clicking an image
picGallery.setOnItemClickListener(new MyOnItemClickListener(context));
// Detect swipes
picGallery.setOnTouchListener(gestureListener);
return row;
}
...
private class MyGestureDetector extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
try {
if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
return false;
} catch (Exception e) {
// nothing
}
return false;
}
}
...
private class MyOnItemClickListener implements OnItemClickListener{
private Context context;
public MyOnItemClickListener(Context context){
this.context = context;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent intent = new Intent(context, PhotoDetailActivity.class);
intent.putExtra("id", id);
context.startActivity(intent);
}
}
回答2:
Do you require a Listview? Perhaps you could place a LinearLayout (vertical) inside a ScrollView?