Fragment中使用listview的解决方案

本文详细介绍在Android项目中,如何在Fragment中使用ListView显示数据。通过定义XML布局、创建适配器及实现点击事件,实现了一个可运行的示例。文章分享了从多次失败到成功的心得,适合初学者及遇到相似问题的开发者。
摘要由CSDN通过智能技术生成

Fragment中使用listview的用法


背景:

在android项目中,经常用到关于listview的,经过很多博客博主的文章,我尝试很多测试都失败了,终于通过不断的总结调试终于有了可靠的解决方案,这里分享给小伙伴们;

先上效果图:

在这里插入图片描述

1、定义xml

xml 主要有两个;第一个位listview,还有一个为item;

1.1 fragment_my.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#dee9f7">


    <ListView
        android:id="@+id/my_list"
      
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>




1.2 my_menu.xml
<?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="match_parent">

    <ImageView
        android:id="@+id/myMenu_image"
        android:layout_margin="10dp"
        android:layout_width="80px"
        android:layout_height="80px" />

    <TextView
        android:id="@+id/myMenu_name"
        android:textSize="23dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        />


</LinearLayout>
1.3 Fragment核心代码
package com.liu.znybq.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;


import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import androidx.fragment.app.Fragment;


import com.liu.znybq.R;
import com.liu.znybq.utils.L;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 *  项目名:  android_znybq
 *  包名:     com.liu.znybq.fragment
 *  文件名:    FragmentHome
 *  创建者:    shi860715@126.com liubj
 *  创建时间:   2020/4/16  12:50
 *  描述:    TODO
 */
public class FragmentMy extends Fragment implements AdapterView.OnItemClickListener {
     ListView listView;
     SimpleAdapter simpleAdapter;

    /**
     *   布局文件和framagement 关联
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

       View view =inflater.inflate(R.layout.fragment_my,container,false);
        listView =view.findViewById(R.id.my_list);

        simpleAdapter = new SimpleAdapter(getActivity(),getData(),R.layout.my_menu,new String[]{"title","image"},new int[]{R.id.myMenu_name,R.id.myMenu_image});
       listView.setAdapter(simpleAdapter);

        listView.setOnItemClickListener(this);
        return view;
    }

    private List<Map<String,Object>> getData() {
        String [] titles={"水果1","水果2","水果3","水果4","水果5","水果6","水果7"};
        int [] images={R.drawable.shuiguo_0,R.drawable.shuiguo_1,R.drawable.shuiguo_2,
                R.drawable.shuiguo_3,R.drawable.shuiguo_4,
                R.drawable.shuiguo_5,R.drawable.shuiguo_6};
        List<Map<String,Object>> list= new ArrayList<>();
           for(int i=0;i<7;i++){
               Map  map = new HashMap();
               map.put("title",titles[i]);
               map.put("image",images[i]);
               list.add(map);
           }
        return list;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }



    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        L.i("position:"+position);
        String text = listView.getAdapter().getItem(position).toString();
        L.i("position:"+position+"text"+text );
    }
}

1.4 测试

通过点击事件可用得到,里面的json格式的输出

2020-04-16 12:43:31.393 7455-7455/com.liu.znybq I/ZNYBQ: position:6text{image=2131230868, title=水果7}
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设计一个商品展示页面了。
评论 33
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值