在fragment中使用listView设计一个商品展示页面
时间: 2024-05-01 08:17:12 浏览: 142
1.首先,在fragment的布局文件中添加一个ListView控件。例如:
```
<ListView
android:id="@+id/listview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
2.创建一个自定义的Adapter类,用于将商品数据显示在ListView上。例如:
```
public class ProductAdapter extends BaseAdapter {
private Context mContext;
private List<Product> mProductList;
public ProductAdapter(Context context, List<Product> productList) {
mContext = context;
mProductList = productList;
}
@Override
public int getCount() {
return mProductList.size();
}
@Override
public Object getItem(int position) {
return mProductList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.item_product, parent, false);
holder = new ViewHolder();
holder.imageView = convertView.findViewById(R.id.imageview);
holder.nameTextView = convertView.findViewById(R.id.name_textview);
holder.priceTextView = convertView.findViewById(R.id.price_textview);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Product product = mProductList.get(position);
holder.imageView.setImageResource(product.getImageResId());
holder.nameTextView.setText(product.getName());
holder.priceTextView.setText(product.getPrice());
return convertView;
}
private static class ViewHolder {
ImageView imageView;
TextView nameTextView;
TextView priceTextView;
}
}
```
3.在fragment的Java代码中,初始化ListView控件,并使用上一步创建的Adapter类将商品数据显示在ListView上。例如:
```
public class ProductFragment extends Fragment {
private ListView mListView;
private ProductAdapter mAdapter;
private List<Product> mProductList;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_product, container, false);
mListView = view.findViewById(R.id.listview);
mProductList = getProductList(); // 获取商品数据
mAdapter = new ProductAdapter(getActivity(), mProductList);
mListView.setAdapter(mAdapter);
return view;
}
private List<Product> getProductList() {
List<Product> productList = new ArrayList<>();
productList.add(new Product(R.drawable.product1, "商品1", "100元"));
productList.add(new Product(R.drawable.product2, "商品2", "200元"));
productList.add(new Product(R.drawable.product3, "商品3", "300元"));
return productList;
}
}
```
4.最后,创建一个商品类Product,用于存储商品数据。例如:
```
public class Product {
private int mImageResId;
private String mName;
private String mPrice;
public Product(int imageResId, String name, String price) {
mImageResId = imageResId;
mName = name;
mPrice = price;
}
public int getImageResId() {
return mImageResId;
}
public String getName() {
return mName;
}
public String getPrice() {
return mPrice;
}
}
```
这样,就可以在fragment中使用ListView设计一个商品展示页面了。
阅读全文