Android: เปลี่ยนรูปภาพใน GridView โดยทางโปรแกรม [ซ้ำกัน]

ฉันได้ตั้งค่า GridView ตามแนวทางที่นี่ ตอนนี้ฉันต้องการเปลี่ยนรูปภาพใดรูปภาพหนึ่งโดยทางโปรแกรม (ผู้ใช้ ไม่ คลิกรูปภาพเพื่อเปลี่ยน) ฉันจะทำอย่างไรหากฉันรู้ตำแหน่งของภาพในตาราง?


person Jeff    schedule 14.08.2015    source แหล่งที่มา


คำตอบ (1)


คุณสามารถสร้างวัตถุที่อะแดปเตอร์ของคุณแสดงได้ด้วย ให้เมธอด getView() ของคุณตั้งค่าการอ้างอิง ImageView ภายในวัตถุนั้น

เมื่อคุณทำเสร็จแล้ว คุณสามารถใช้เมธอด getItem() เพื่อส่งคืนออบเจ็กต์นั้น รับการอ้างอิงของคุณไปที่ ImageView จากนั้นตั้งค่ารูปภาพโดยทางโปรแกรม

หากคุณใช้การดำเนินการตรงตามนั้นจากคำแนะนำดังกล่าว คุณสามารถใช้ ArrayList ได้

public class ImageAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<ImageView> mImageViewArrayList = new ArrayList<>(mThumbIds.length);

public ImageAdapter(Context c) {
    mContext = c;
} 

public int getCount() { 
    return mThumbIds.length;
} 

public ImageView getItem(int position) {
    return mImageViewArrayList.get(position); 
} 

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;
    } 

    mImageViewArrayList.set(position,imageView);

    imageView.setImageResource(mThumbIds[position]);
    return imageView;
} 

// references to our images 
private Integer[] mThumbIds = {
        R.drawable.sample_2, R.drawable.sample_3,
        R.drawable.sample_4, R.drawable.sample_5,
        R.drawable.sample_6, R.drawable.sample_7,
        R.drawable.sample_0, R.drawable.sample_1,
        R.drawable.sample_2, R.drawable.sample_3,
        R.drawable.sample_4, R.drawable.sample_5,
        R.drawable.sample_6, R.drawable.sample_7,
        R.drawable.sample_0, R.drawable.sample_1,
        R.drawable.sample_2, R.drawable.sample_3,
        R.drawable.sample_4, R.drawable.sample_5,
        R.drawable.sample_6, R.drawable.sample_7
}; 
} 

จากนั้นในชั้นเรียนของคุณที่คุณต้องการเปลี่ยนแปลงโดยทางโปรแกรมให้ทำเช่นนี้

private void setImage(int position, int image){
    mAdapter.getItem(position).setImageResource(image);
}
person hitch.united    schedule 14.08.2015