我有一个名为level0 ... level20的20个ImageView的Activity。我想要改变前10个ImageViews的图像源。我试过这个,但没有好结果。请帮助我。
private ImageView [] lvlImgs;
private int unlocked=10;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.levels);
for(int i=0;i<unlocked;i++)
{
int id = getResources().getIdentifier("level"+i, "id", this.getPackageName());
lvlImgs[i]=(ImageView)findViewById(id);
lvlImgs[i].setImageResource(R.drawable.new_image_to_show);
}
}
答案 0 :(得分:0)
您应该发布Exception
或错误。
考虑到您发布的代码,我能理解的原因是
您没有按原样初始化lvlImgs
数组:
lvlImgs = new ImageView [unlocked];
这可能是应用程序崩溃的原因。
发布您的Exception
log-cat可能有助于我们了解问题。
答案 1 :(得分:0)
谢谢你的回答。我找到了其他方法:使用GridView和ImageAdapter类。对于那些感兴趣的人:
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private int unlocked=10;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return 20;
}
public Object getItem(int position) {
return null;
}
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(90, 50));
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
} else {
imageView = (ImageView) convertView;
}
if(position<unlocked){
imageView.setImageResource(R.drawable.gheta_med);
}else{
imageView.setImageResource(R.drawable.gheta_med_lock);
}
return imageView;
}
和我的活动
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
Log.i("item", ""+arg2);