【问题标题】:Adding items from xml String array into recycler view within a fragment将 xml 字符串数组中的项目添加到片段内的回收器视图中
【发布时间】:2020-05-12 12:24:54
【问题描述】:

我在尝试将一组城市添加到我的片段列表中的每个项目位置时遇到了一些麻烦。我已经为我的片段创建了虚拟列表模板,但在网上找不到任何关于如何将 Strings.xml 文件中数组上的值存储到回收器视图中的值的任何内容。我想用我的数组中的城市名称替换虚拟项目(例如 1:项目 1、2:项目 2 等)。请帮忙!!!

xml 文件:

<resources>

    <string-array name="Cities">
        <item>Vancouver</item>
        <item>Kamloops</item>
        <item>Edmonton</item>
        <item>Calgary</item>
        <item>Winnipeg</item>
        <item>Toronto</item>
        <item>Montreal</item>
    </string-array>
</resources>

片段文件:

package com.example.fragments;

import android.content.Context;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

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

import com.example.fragments.dummy.DummyContent;
import com.example.fragments.dummy.DummyContent.DummyItem;

import java.util.List;

/**
 * A fragment representing a list of Items.
 * <p/>
 * Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener}
 * interface.
 */
public class citiesFragment extends Fragment {

    // TODO: Customize parameter argument names
    private static final String ARG_COLUMN_COUNT = "column-count";
    // TODO: Customize parameters
    private int mColumnCount = 1;
    private OnListFragmentInteractionListener mListener;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public citiesFragment() {
    }

    // TODO: Customize parameter initialization
    @SuppressWarnings("unused")
    public static citiesFragment newInstance(int columnCount) {
        citiesFragment fragment = new citiesFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_COLUMN_COUNT, columnCount);
        fragment.setArguments(args);
        return fragment;
    }

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

        if (getArguments() != null) {
            mColumnCount = getArguments().getInt(ARG_COLUMN_COUNT);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_cities_list, container, false);

        // Set the adapter
        if (view instanceof RecyclerView) {
            Context context = view.getContext();
            RecyclerView recyclerView = (RecyclerView) view;
            if (mColumnCount <= 1) {
                recyclerView.setLayoutManager(new LinearLayoutManager(context));
            } else {
                recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
            }
            recyclerView.setAdapter(new MycitiesRecyclerViewAdapter(DummyContent.ITEMS, mListener));
        }
        return view;
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnListFragmentInteractionListener) {
            mListener = (OnListFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                + " must implement OnListFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnListFragmentInteractionListener {
        // TODO: Update argument type and name
        void onListFragmentInteraction(DummyItem item);
    }
}

布局:

<androidx.recyclerview.widget.RecyclerView 
    xmlns:android="schemas.android.com/apk/res/android" 
    xmlns:app="schemas.android.com/apk/res-auto" 
    xmlns:tools="schemas.android.com/tools" 
    android:id="@+id/list" 
    android:name="com.example.fragments.citiesFragment" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:layout_marginLeft="16dp" 
    android:layout_marginRight="16dp"
    app:layoutManager="LinearLayoutManager" 
    tools:context=".citiesFragment" 
    tools:listitem="@layout/fragment_cities" />

适配器文件:

/**
 * {@link RecyclerView.Adapter} that can display a {@link DummyItem} and makes a call to the
 * specified {@link OnListFragmentInteractionListener}.
 * TODO: Replace the implementation with code for your data type.
 */
public class MycitiesRecyclerViewAdapter extends RecyclerView.Adapter<MycitiesRecyclerViewAdapter.ViewHolder> {

    private final List<DummyItem> mValues;
    private final OnListFragmentInteractionListener mListener;

    public MycitiesRecyclerViewAdapter(List<DummyItem> items, OnListFragmentInteractionListener listener) {
        mValues = items;
        mListener = listener;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.fragment_cities, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder holder, int position) {
        holder.mItem = mValues.get(position);
        holder.mIdView.setText(mValues.get(position).id);
        holder.mContentView.setText(mValues.get(position).content);

        holder.mView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null != mListener) {
                    // Notify the active callbacks interface (the activity, if the
                    // fragment is attached to one) that an item has been selected.
                    mListener.onListFragmentInteraction(holder.mItem);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return mValues.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        public final View mView;
        public final TextView mIdView;
        public final TextView mContentView;
        public DummyItem mItem;

        public ViewHolder(View view) {
            super(view);
            mView = view;
            mIdView = (TextView) view.findViewById(R.id.item_number);
            mContentView = (TextView) view.findViewById(R.id.content);
        }

        @Override
        public String toString() {
            return super.toString() + " '" + mContentView.getText() + "'";
        }
    }
}

虚拟内容文件:

    /**

* Helper 类,用于为由创建的用户界面提供示例内容 * Android 模板向导。 *

* TODO:在发布您的应用程序之前替换该类的所有用途。 */ 公共类 DummyContent {

/**
 * An array of sample (dummy) items.
 */
public static final List<DummyItem> ITEMS = new ArrayList<DummyItem>();

/**
 * A map of sample (dummy) items, by ID.
 */
public static final Map<String, DummyItem> ITEM_MAP = new HashMap<String, DummyItem>();

private static final int COUNT = 25;

static {
    // Add some sample items.
    for (int i = 1; i <= COUNT; i++) {
        addItem(createDummyItem(i));
    }
}

private static void addItem(DummyItem item) {
    ITEMS.add(item);
    ITEM_MAP.put(item.id, item);
}

private static DummyItem createDummyItem(int position) {
    return new DummyItem(String.valueOf(position), "Item " + position, makeDetails(position));
}

private static String makeDetails(int position) {
    StringBuilder builder = new StringBuilder();
    builder.append("Details about Item: ").append(position);
    for (int i = 0; i < position; i++) {
        builder.append("\nMore details information here.");
    }
    return builder.toString();
}

/**
 * A dummy item representing a piece of content.
 */
public static class DummyItem {
    public final String id;
    public final String content;
    public final String details;

    public DummyItem(String id, String content, String details) {
        this.id = id;
        this.content = content;
        this.details = details;
    }

    @Override
    public String toString() {
        return content;
    }
}

}

【问题讨论】:

  • 你必须从资源数组Cities创建DummyItem
  • 什么意思?我是移动开发新手
  • 在您的“fragment_cities_list.xml”文件中,父视图是什么?你能分享你的xml文件吗?
  • 是的一秒钟
  • 对不起,我必须在 cmets 中发布它,它不允许我编辑我的帖子

标签: java android xml android-fragments android-recyclerview


【解决方案1】:

您必须从资源数组Cities 创建DummyItem 并将其传递给您的adapter。检查以下:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_cities_list, container, false);

    // Set the adapter
    if (view instanceof RecyclerView) {
        Context context = view.getContext();

        //Get cities array from resource
        String[] cities = context.getResources().getStringArray(R.array.Cities);
        List<DummyItem> mValues = new ArrayList<>();
        for(int i = 0; i < cities.length; i++) {
            mValues.add(new DummyItem(String.valueOf(i + 1), cities[i], ""));
        }

        RecyclerView recyclerView = (RecyclerView) view;
        if (mColumnCount <= 1) {
            recyclerView.setLayoutManager(new LinearLayoutManager(context));
        } else {
            recyclerView.setLayoutManager(new GridLayoutManager(context, mColumnCount));
        }

        //Pass the mValues to adapter
        recyclerView.setAdapter(new MycitiesRecyclerViewAdapter(mValues, mListener));
    }

    return view;
}

【讨论】:

  • 那么,这会进入适配器文件吗?
  • 是的,我想弄清楚,它不起作用,因为还有一个我不知道的文件叫做虚拟内容,它把它搞砸了
  • 文件现在已经准备好了
  • new DummyItem(String.valueOf(i + 1), cities[i], "")一样将空传给你的DummyItem。检查我更新的答案。只需复制并替换您的代码
  • 它希望我将方法的第一个参数更改为 int 因为 i + 1
猜你喜欢
  • 1970-01-01
  • 2017-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-03
  • 2015-07-13
  • 1970-01-01
  • 2018-02-25
相关资源
最近更新 更多