我已经制作了MainActivity类,我想在列表视图中设置图标
代码在这里
public class MainActivity extends ListActivity {
static String classes[]={"StartingPoint","Example1","Example2","Example3","Example4","Example5","Example6","Example7"};
static final Integer[] imgid = {R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, classes));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String cheese=classes[position];
try {
Class myclass=Class.forName("com.example.listmenu."+cheese);
Intent i=new Intent(MainActivity.this,myclass);
startActivity(i);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
我想在列表视图项目中设置图标....请帮我解决这个问题?
答案 0 :(得分:1)
制作自定义适配器并传递文本和图像数组
public class AboutAdapter extends BaseAdapter {
private LayoutInflater inflater;
private Context mcontext;
private Strig[] arrayList;
public AboutAdapter(Context context, Strig[] arrayList) {
this.mcontext = context;
this.arrayList= arrayList;
inflater = LayoutInflater.from(mcontext);
}
@Override
public int getCount() {
return arrayList.length;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
public class Holder {
TextView txtname;
ImageView imag;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
Holder holder;
if (vi == null) {
vi = inflater.inflate(R.layout.raw_aboutlist, null);
holder = new Holder();
holder.txtname = (TextView) vi
.findViewById(R.id.raw_about_txt_name);
holder.imag = (ImageView) vi
.findViewById(R.id.raw_about_img);
vi.setTag(holder);
} else {
holder = (Holder) vi.getTag();
}
holder.txtname.setText(arrayList[position]);
// same as for image pass array of image and set
holder.imag.setBackgroundResource(R.drawable.explr_img_selector);
return vi;
}
}
然后在listview中设置适配器,如下所示
AboutAdapter aboutAdapter = new AboutAdapter(AboutActivity.this, arrayList);
listView.setAdapter(aboutAdapter);