Pass Integer to BaseAdapter
-
08-01-2021 - |
Domanda
I am trying to pass an integer array to a baseadapter, such that A.class will pass an array of integers to the BaseAdapter in B.class. Here is how I am passing the integer array in A.Class (sender):
int [] mThumb = {
R.drawable.image1_thumb, R.drawable.image2_thumb, R.drawable.image3_thumb,
R.drawable.image4_thumb, R.drawable.image5_thumb, R.drawable.image6_thumb,
R.drawable.image7_thumb, R.drawable.image8_thumb, R.drawable.image9_thumb,
R.drawable.image10_thumb};
Bundle b=new Bundle();
b.putIntArray("mThumbSent", mThumb);
Intent startSwitcher = new Intent(A.this, B.class);
startSwitcher.putExtras(b);
And in my BaseAdapter in activity B:
public class ImageSwitch1 extends Activity Extends ...{
onCreate....
[redacted]
}
private ImageSwitcher mSwitcher;
public class ImageAdapter extends BaseAdapter {
Bundle b=this.getIntent().getExtras();
int[] mThumb = b.getIntArray("mThumbSent");
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumb.length; //this used to say return mThumbIds
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView im = new ImageView(mContext);
im.setImageResource(mThumb[position]);
im.setAdjustViewBounds(true);
im.setLayoutParams(new Gallery.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
im.setBackgroundResource(R.drawable.picture_frame);
return im;
}
private Context mContext;
}
}
now obviously the code above is incorrect, I cannot use getintent in the imageadapter. But this is an illustrative example of what I am trying to accomplish, and would like to know how to pass a variable or array via intent to a BaseAdapter, if possible.
Soluzione
Update the constructor of your ImageAdapter to accept an integer array like so:
int[] mResources;
public ImageAdapter(Context c, int[] resources) {
mResources = resources;
mContext = c;
}
Then when initializing your Adapter in your Activity, just pass it the extra int array:
ImageAdapter adapter = new ImageAdapter(context, intArray);
Altri suggerimenti
getIntent() will be available in your class B.
You could put the Bundle or the integer array into the constructor of your ImageAdapter
public class ImageAdapter extends BaseAdapter {
public ImageAdapter(Context c, Bundle b) {
int[] mThumb = b.getIntArray("mThumbSent");
mContext = c;
}
.....
}
In your Activity B construct your Adapter this way:
ImageAdapter adapter = new ImageAdapter(yourcontext,getIntent().getExtras());
Where do you want to use your adapter? In a ListView? Then it would be enough to subclass ListAdapter instead of BaseAdapter.