我是Android编程的初学者,需要一些帮助。 我有一个应该在listview中显示的对象数组。这是一个类的代码:
public class Car {
public String img;
public String thumbnail;
public String manufacturer;
public String model;
public int price;
public String description;
}
缩略图是一个字符串变量,包含要显示的缩略图的URL。 我还有几个Car对象的数组,称为" cars"在我的DataStorage类中声明。
我只希望在我的自定义列表视图中显示每个对象的两件事:缩略图(来自互联网)和模型。
我创建了layout item.xml,它应代表listview的一项:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="100dp"
android:background="@android:color/holo_blue_dark">
<ImageView
android:layout_width="100dp"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:text="left"
android:id="@+id/image_tmb"
android:layout_gravity="left|center_vertical"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:background="@android:color/holo_blue_dark">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@android:color/white"
android:paddingBottom="10dp"
android:id="@+id/name"
android:layout_weight="1"
android:textSize="23dp"/>
</LinearLayout>
</LinearLayout>
TextView应填充模型,Imageview应填充缩略图。
我还创建了类MyAdapter,它应该填充listview:
public class MyAdapter extends BaseAdapter {
private Context myContext;
public MyAdapter(Context context) {
this.myContext = context;
}
@Override
public int getCount() {
return DataStorage.cars.length;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
//Here I should customize my view but don't know how.
}
我在activity_main.xml中创建了listview元素,并在MainActivity中对其进行了delcared:
ListView lv=(ListView) findViewById(R.id.lv);
那么,我该如何完成任务呢?
答案 0 :(得分:2)
一个简单的模式看起来像这样
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
// Inflate the view if it doesn't already exist
if (view == null) {
LayoutInflater.from(getContext()).inflate(R.layout.item, parent, false);
}
// Get your current Car object
Car c = getItem(i);
// Initialize the views
ImageView image = (ImageView) view.findViewById(R.id.image_tmb);
TextView name = (TextView) view.findViewById(R.id.name);
// Fill the views according to the car's properties
/* NOTE: I'm not going to go in depth to explain how to set
an ImageView image from a URL, as it is an entirely different question,
so I'll put a link to this library below */
Picasso.with(myContext).load(c.thumbnail).into(image);
name.setText(c.model);
}
您需要修改getItem
以实际获取该项目,而不是返回null ..
@Override
public Object getItem(int position) {
return DataStorage.cars[position];
}
然后,在Activity / Fragment / Whatever中设置你的适配器,就像这样
MyAdapter mAdapter = new MyAdapter(this);
lv.setAdapter(mAdapter);
如果您要使用图片做很多事情并且不想编写自己的实现,Picasso是一个非常容易使用的库。