以下代码是GalleryView
在 Android 中使用的典型方式。但是,我不明白哪一行代码实际显示所有图像 1-8。
我知道所有图像 1-8 都存储在数组中ImageIds
。getView{...}
然而,下面的代码@Override
只显示一个特定的图像 ( ImageIds[position]
),其中position
是您选择的图像。
i.setImageResource(ImageIds[position]);
因此,哪一行代码告诉 Android 显示所有 ImageIds 图像?
主要的.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Gallery
android:id="@+id/gallery1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/imageView1"
android:layout_marginTop="100dp"
android:layout_width="250dp"
android:layout_gravity="center_horizontal"
android:layout_height="250dp"
android:src="@drawable/image1" />
</LinearLayout>
主要活动
public class MainActivity extends Activity
{
ImageView selectedImage;
private Integer[] ImageIds = {
R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4,
R.drawable.image5,
R.drawable.image6,
R.drawable.image7,
R.drawable.image8
};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
selectedImage=(ImageView)findViewById(R.id.imageView1);
gallery.setSpacing(1);
gallery.setAdapter(new GalleryImageAdapter(this));
// clicklistener for Gallery
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(MainActivity.this, "Your selected position = " + position, Toast.LENGTH_SHORT).show();
// show the selected Image
selectedImage.setImageResource(ImageIds[position]);
}
});
}
}
GalleryImageAdapter
public class GalleryImageAdapter extends BaseAdapter
{
private Context mContext;
private Integer[] ImageIds = {
R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4,
R.drawable.image5,
R.drawable.image6,
R.drawable.image7,
R.drawable.image8
};
public GalleryImageAdapter(Context context)
{
mContext = context;
}
public int getCount() {
return ImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// Override this method according to your need
public View getView(int position, View view, ViewGroup viewGroup)
{
// TODO Auto-generated method stub
ImageView i = new ImageView(mContext);
i.setImageResource(ImageIds[position]);
i.setLayoutParams(new Gallery.LayoutParams(200, 200));
i.setScaleType(ImageView.ScaleType.FIT_XY);
return i;
}
}