【问题标题】:how to create custom adapter to use cardview for list view inside fragment如何创建自定义适配器以将 cardview 用于片段内的列表视图
【发布时间】:2019-12-09 20:16:01
【问题描述】:

我想在片段内的列表视图中使用卡片视图来显示 2 个变量,我已经可以连接到数据库并将 json 中的一个变量“nama_matkul”显示到我的列表视图中,但我需要显示“ nama_matkul" 和 "sks" 所以我正在创建一个卡片视图,但我很困惑为它制作 costum 适配器

这是我的 json 响应

{
"error": false,
"matkul_mhs": [{
"nama_matkul": "matkul_3",
"sks": 3
}]}

这是我在片段中初始化列表视图的方法

 public void initListView1(){
        Call<MatkulMhs> getMatkulMhs = mApiService.getMatkulMhs(
                mPrefs.getUserID());
        getMatkulMhs.enqueue(new Callback<MatkulMhs>() {
            @Override
            public void onResponse(Call<MatkulMhs> call, Response<MatkulMhs> response) {
                boolean iserror_ = response.body().getError();
                if (iserror_ == false) {
                    List<Matkul_Mhs> list = new ArrayList<>();
                    list = response.body().getMatkulMhs();
                    nama_matkul = new String[list.size()];
                    for (int i =0;i<list.size();i++) {
                        nama_matkul[i] = list.get(i).getNamaMatkul();
                    }
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, nama_matkul);
                    listview1.setAdapter(adapter);

                }
            }

这是我的卡片视图 (form_mhs_02_cardview.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <androidx.cardview.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="fill_parent"
        android:layout_height="100dp"
        android:layout_margin="5dp"
        card_view:cardCornerRadius="2dp"
        card_view:contentPadding="10dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:background="@drawable/rounded_sqrwht"
            android:padding="10dp"
            >

            <TextView
                android:id="@+id/tv_matkul"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Mata Kuliah 1 "
                android:textSize="25dp"
                android:textColor="@color/colorPrimaryDark"
                android:textStyle=""
                android:singleLine="true"
                />
            <TextView
                android:id="@+id/tv_sks"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="3 sks"
                android:textSize="20dp"
                android:textColor="@color/black"
                android:singleLine="true"
                />
        </LinearLayout>

    </androidx.cardview.widget.CardView>

</LinearLayout>

我从另一篇文章中找到了这个答案,但仍然困惑于改变我的需求 ,帖子可以在custom adapter for listview in fragment Android找到

public class CustomAdapter extends ArrayAdapter<HashMap<String,String>>
{
    private ArrayList<HashMap<String,String>> callLogData;
    private Context context;
    private int resource;
    private View view;
    private Holder holder;
    private HashMap<String,String> hashMap;
    public CustomAdapter(Context context, int resource,ArrayList<HashMap<String, String>> objects)
    {
        super(context, resource, objects);
        this.context=context;
        this.resource=resource;
        this.callLogData=objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {

        LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view=inflater.inflate(resource, parent,false);

        holder=new Holder();
        holder.text_matkul=(TextView)view.findViewById(R.id.tv_matkul);
        holder.text_sks=(TextView)view.findViewById(R.id.tv_sks);

        hashMap=callLogData.get(position);

        Date date=new Date(Long.parseLong(hashMap.get(CallLog.Calls.DATE)));
        java.text.DateFormat dateFormat=DateFormat.getDateFormat(context);
        java.text.DateFormat timeformat=DateFormat.getTimeFormat(context);


        holder.text_matkul.setText(hashMap.get(CallLog.Calls.NUMBER));
        holder.text_sks.setText(timeformat.format(date));

        return view;
    }

    public class Holder
    {
        TextView text_matkul;
        TextView text_sks;
    }

}

【问题讨论】:

    标签: java android android-fragments retrofit2


    【解决方案1】:

    @togan-j-r 请在此链接https://medium.com/@Pang_Yao/android-fragment-use-recyclerview-cardview-4bc10beac446 上查看此示例,并尝试按照演示示例实现。

    【讨论】:

      【解决方案2】:

      在 SetAdapter 之前使用您的自定义适配器类文件。

      CustomAdapter 适配器 = new CustomAdapter(getActivity(), android.R.layout.simple_list_item_1, nama_matkul);

       public void initListView1(){
          Call<MatkulMhs> getMatkulMhs = mApiService.getMatkulMhs(
                  mPrefs.getUserID());
          getMatkulMhs.enqueue(new Callback<MatkulMhs>() {
              @Override
              public void onResponse(Call<MatkulMhs> call, Response<MatkulMhs> response) {
                  boolean iserror_ = response.body().getError();
                  if (iserror_ == false) {
                      List<Matkul_Mhs> list = new ArrayList<>();
                      list = response.body().getMatkulMhs();
                      nama_matkul = new String[list.size()];
                      for (int i =0;i<list.size();i++) {
                          nama_matkul[i] = list.get(i).getNamaMatkul();
                      }
                      CustomAdapter <String> adapter = new CustomAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, nama_matkul);
                      listview1.setAdapter(adapter);
      
                  }
              }
      

      【讨论】:

      【解决方案3】:
      public class CustomAdapter extends ArrayAdapter<HashMap<String, String>> {
          private final ArrayList<HashMap<String, String>> callLogData;
          private final Context context;
          private final int resource;
      
          /*
          This TODO code won't cause any issue even if not done.
          */
          //TODO : Check below comment
          private View view;
      
          //TODO :: NEED TO REMOVE as adapter handle multiple items therefore no meaning in having single field of holder object
          private Holder holder;
          //TODO :: NEED TO REMOVE same as above. you should get item from based on position provided in getView method no need to keep reference to it
          private HashMap<String, String> hashMap;
      
          public CustomAdapter(Context context, int resource, ArrayList<HashMap<String, String>> objects) {
              super(context, resource, objects);
              this.context = context;
              this.resource = resource;
              callLogData = objects;
          }
      
          @Override
          public View getView(int position, View convertView, ViewGroup parent) {
      
              LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
              //Added local instance of holder
              View view = inflater.inflate(resource, parent, false);
              //Added local instance of holder
              Holder holder = new Holder();
              holder.text_matkul = (TextView) view.findViewById(R.id.tv_matkul);
              holder.text_sks = (TextView) view.findViewById(R.id.tv_sks);
              //Added local instance of holder
              HashMap<String, String> hashMap = callLogData.get(position);
      
              //Commenting below code
              /*
                      Date date=new Date(Long.parseLong(hashMap.get(CallLog.Calls.DATE)));
                      java.text.DateFormat dateFormat=DateFormat.getDateFormat(context);
                      java.text.DateFormat timeformat=DateFormat.getTimeFormat(context);
              */
      
      
              holder.text_matkul.setText(hashMap.get("nama_matkul"));
              holder.text_sks.setText("sks");
      
              return view;
          }
      
          public class Holder {
              TextView text_matkul;
              TextView text_sks;
          }
      
      }
      
      
      public void initListView1() {
          Call<MatkulMhs> getMatkulMhs = mApiService.getMatkulMhs(
                  mPrefs.getUserID());
          getMatkulMhs.enqueue(new Callback<MatkulMhs>() {
              @Override
              public void onResponse(Call<MatkulMhs> call, Response<MatkulMhs> response) {
                  boolean iserror_ = response.body().getError();
                  if (iserror_ == false) {
                      List<Matkul_Mhs> list = new ArrayList<>();
                      list = response.body().getMatkulMhs();
                      ArrayList<HashMap<String, String>> nama_matkul = new ArrayList<>();
                      for (int i = 0; i < list.size(); i++) {
                          HashMap<String, String> item = new HashMap<String, String>();
                          item.put("nama_matkul", list.get(i).getNamaMatkul());
                          item.put("sks", list.get(i).getSKS());
                          nama_matkul.add(item);
                      }
                      //Note: layout resource changed to your card view and ArrayAdapter  to CustomAdapter
                      CustomAdapter adapter = new CustomAdapter(getActivity(), R.layout.form_mhs_02_cardview, nama_matkul);
                      listview1.setAdapter(adapter);
      
                  }
              }
          }
      }
      

      【讨论】:

      • CustomAdapter 适配器错误 = new CustomAdapter(getActivity(), R.layout.form_mhs_02_cardview, nama_matkul);所需对象 java...java.lang.String>> 找到 java...java.lang.String>[]
      • 修改 HashMap 对象为 HashMap 对象的 ArrayList,像这样 nama_matkul[i] = new ArrayList>(); .这应该可以解决上面的错误。正如我从代码中看到的那样,在适配器构造函数中,您应该传递一个 ArrayList 而不是 Object。
      • 此代码只是对您原始代码的修改。如果您对性能改进感兴趣,则可能需要寻找 recyclerView 和 RecyclerView.Adapter 或 ListAdapter(diffUtil.ItemCallback)
      • 它没有显示任何内容,当我尝试在方法 public View getView 中使用 log.d 时它没有运行
      猜你喜欢
      • 1970-01-01
      • 2020-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-15
      • 1970-01-01
      • 2015-06-27
      相关资源
      最近更新 更多