最近通过视频把基础ListView部分过了一遍,把一些简单有用的点记录了下来,方便每天温习和查看
1. 首先添加一个ImageView方面的
ImageView后端加载图片:
后端设置ImageResource
int imageResourceIndex = getResource().getIdentifier("@drawable/desert", null, this.getPackageName());
imageView.setImageResource(imageResourceIndex); // 注意传入的是Int类型
2. ListView应用
main_layout新建ListView组件, list_item_layout新建TextView组件用于自定义Adatper中Text的属性
后端代码:
ListView list = findViewById(R.id.list_view);
ArrayList<String> names = new ArrayList<String>();
names.add("Wang");
names.add("Li");
names.add("Zhang");
ArrayAdapter adapter = new ArrayAdapter(this, R.layout.list_item_layout, names);
list.setAdatper(adatper);
3. 自定义多列显示的ListView
自定义Adapter的布局,通过属性weightSum设置每行左边一个TextView,右边两个垂直显示的TextView
<linearLayout ...
android: orientation: "horizontal"
android:weightSum="100">
<TextView ...
android:layout_weight="60" />
<LinearLayout ...
android:orientation="vertical"
android:weightSum="40" >
<Textview .../>
<TextView ... />
</LinearLayout>
</LinearLayout>
定义Class:左边TextView显示汽车品牌,右边两个垂直TextView为型号和价格
public class Car {
private String brand;
private String model;
private String price;
// Getter和Setter
}
MainActivity.java类:
ListView listView = findViewById(R.layout.list_view);
ArrayList<Car> carList = new ArrayList<Car>();
Car tesla1 = new Car("Tesla", "model3","30w");
Car tesla2 = new Car("Tesla", "models","80w");
Car tesla3 = new Car("Tesla", "modelx", "80w");
carList.add(tesla1);
carList.add(tesla2);
carList.add(tesla3);
...更多Car可以添加
// 自定义Adapter
CarListAdapter adapter = new CarListAdapter(this, R.layout.list_view_adapter, carList);
listView.setAdapter(adapter);
CarListAdapter.java:
public class CarListAdapter extends ArrayAdapter<Car> {
private Context context;
// Constructor
public CarListAdapter(Context context, int resource, ArrayList<Car> objects) {
super(context, resource, objects;
mContext = context;
mResource = resource;
}
public View getView(int position, View convertView, ViewGroup parent) {
String brand= getItem(position).getBrand();
String model= getItem(position).getModel()
String price = getItem(position).getPrice();
Car car = new Car(brand, model, price);
LayoutInflater infalter = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
TextView textBrand = convertView.findViewById(R.id.text_view_1);
... model
... price
textBrand.setText(brand);
... model
...price
return convertView;
}
}