listView優化
阿新 • • 發佈:2017-05-21
nds .text term res rri als 芒果 his convert
圖片資源
public class Fruit {
private static Object[][] listFruit={
{"蘋果",R.drawable.apple_pic},
{"香蕉",R.drawable.banana_pic},
{"櫻桃",R.drawable.cherry_pic},
{"葡萄",R.drawable.grape_pic},
{"芒果",R.drawable.mango_pic},
{"橘子",R.drawable.orange_pic},
{"梨子",R.drawable.pear_pic},
{"菠蘿",R.drawable.pineapple_pic},
{"草莓",R.drawable.strawberry_pic},
{"西瓜",R.drawable.watermelon_pic}
};
public static Object[][] getListFruit() {
return listFruit;
}
}
對象
public class FruitClass {
private String name;
private int imgId;
public FruitClass(String name, int imgId) {
this.name = name;
this.imgId = imgId;
}
public String getName() {
return name;
}
public int getImgId() {
return imgId;
}
}
適配器
public class FruitAdapter extends ArrayAdapter<FruitClass> {
private int resource;
public FruitAdapter(@NonNull Context context, @LayoutRes int resource, @NonNull List objects) {
super(context, resource, objects);
this.resource=resource;
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
FruitClass fruit=getItem(position);
View view;
ViewHolder viewHolder;
if (convertView==null){
view = LayoutInflater.from(getContext()).inflate(resource,parent,false);
viewHolder=new ViewHolder();
viewHolder.imageView=(ImageView) view.findViewById(R.id.listViewItem_img);
viewHolder.textView=(TextView) view.findViewById(R.id.listViewItem_name);
view.setTag(viewHolder);
}else{
view=convertView;
viewHolder= (ViewHolder) view.getTag();
}
viewHolder.imageView.setImageResource(fruit.getImgId());
viewHolder.textView.setText(fruit.getName());
return view;
}
class ViewHolder{
ImageView imageView;
TextView textView;
}
}
MainActivity
public class MainActivity extends ActivityDisplayName {
private List<FruitClass> fruit=new ArrayList<FruitClass>();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
inisFruit();
FruitAdapter fa=new FruitAdapter(this,R.layout.item_listview,fruit);
ListView lv= (ListView) findViewById(R.id.main_listView);
lv.setAdapter(fa);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FruitClass fc=fruit.get(position);
switch (fc.getImgId()){
case R.drawable.apple_pic:
Intent i=new Intent(MainActivity.this,AppleActivity.class);
startActivity(i);
break;
case R.drawable.watermelon_pic:
Toast.makeText(MainActivity.this,"西瓜",Toast.LENGTH_SHORT).show();
break;
}
}
});
}
private void inisFruit() {
Object[][] f=Fruit.getListFruit();
for (int j = 0; j < 5; j++) {
for (int i = 0; i <10 ; i++) {
Log.d("forSlyune", f[i][0].toString()+"----------"+f[i][1].toString());
FruitClass fc=new FruitClass(f[i][0].toString()+"."+(j+1),Integer.parseInt(f[i][1].toString()));
fruit.add(fc);
}
}
}
}
listView優化