首页 > 代码库 > listView优化
listView优化
图片资源
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优化
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。