RecyclerView中的数据未从片段传递到适配器

时间:2018-11-06 22:57:21

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

创建#include <stdio.h> int main(void) { char *strVar = "testfordifferentlength"; int i,timesCalled=0; printf("\nLength = %d\n\n",strlen(strVar)); for(i=0;i <= strlen(strVar);i++){ printf("%c",*strVar); strVar++; timesCalled++; } printf("\n\nFor loop run %d times!\n",timesCalled); return 0; } 后,我注意到在RecyclerView中声明的字符串没有从Bundle传递到Fragment,并且连接的文本视图显示为空白。有谁知道出了什么问题?在这种情况下或其他情况下,我需要使用意图吗?

用于片段:

AlertDialog

用于适配器:

Bundle bundle = new Bundle();
bundle.putString("goalreached",  getResources().getString(R.string.goal_reached));
bundle.putString("day",  getResources().getString(R.string.today));
bundle.putString("distance",  getResources().getString(R.string._3_2_km));
bundle.putString("calories",  getResources().getString(R.string._213_kcal));

enter image description here

预期结果

enter image description here

当前结果

enter image description here

片段类

Bundle bundle = new Bundle();
String goalreached = bundle.getString("goalreached");   
String day = bundle.getString("day");
String distance = bundle.getString("distance");                        
String calories = bundle.getString("calories");

适配器类

public class TabFragmentRV extends android.support.v4.app.Fragment {
    RecyclerView mRecyclerView;

    public TabFragmentRV() {}

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_rv, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        View v = getView();
        assert v != null;

        mRecyclerView = v.findViewById(R.id.my_recyclerview);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));

        Bundle bundle = new Bundle();
        bundle.putString("goalreached",  getResources().getString(R.string.goal_reached));
        bundle.putString("day",  getResources().getString(R.string.today));
        bundle.putString("distance",  getResources().getString(R.string._3_2_km));
        bundle.putString("calories",  getResources().getString(R.string._213_kcal));

        super.onActivityCreated(savedInstanceState);

        initRVAdapter();
    }

    private void initRVAdapter(){
        List<Object> itemsList = new ArrayList<>();

        itemsList.add(new RVLineSeparator());
        itemsList.add(new RVTable("Stats", "Today", "Yesterday", "This week", "This month"));

        RVItemsAapter itemsListAdapter = new RVItemsAapter(getContext());
        mRecyclerView.setAdapter(itemsListAdapter);

        itemsListAdapter.setCallSMSFeed(itemsList);
        itemsListAdapter.notifyDataSetChanged();
    }
}

2 个答案:

答案 0 :(得分:2)

您需要将第一个创建的捆绑软件传递到适配器中(可能是在创建适配器时)

这里是需要更改的班级

public class RVItemsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private final static int TYPE_TABLE = 1, TYPE_SEPARATOR = 2;
    private ArrayList myArrayList = new ArrayList();
    private Context context;
    //Added Global bundle
    Private Bundle mBundle;

    public RVItemsAdapter(Context context){
        this. context=context;
    }

    //Added Constructor
    public RVItemsAdapter(Context context, Bundle bundle){
        this.context=context;
        this.mBundle = bundle;
    } 

    public void setCallSMSFeed(List<Object> myArrayList){
        this.myArrayList = (ArrayList) myArrayList;
    }

    @Override
    public int getItemViewType(int position) {
        if (myArrayList.get(position) instanceof TableRV) {
            return TYPE_TABLE;
        } else if (myArrayList.get(position) instanceof RVLineSeparator) {
            return TYPE_SEPARATOR;
        }
        throw new IllegalArgumentException("Item at position " + position + " is not an instance of either Phonecall or SMSmessage");
    }

    //Update Bundle
    public void updateView(Bundle bundle){
        mBundle = bundle;
        this.notifyDataSetChanged();
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        int viewType=holder.getItemViewType();
        switch (viewType){
            case TYPE_TABLE:
                TableRV tblRV = (TableRV) myArrayList.get(position);
                ((TblViewHolder)holder).bind(tblRV);
                break;
            case TYPE_SEPARATOR:
                ((SeparatorViewHolder)holder).showSeparatorDetails();
                break;
            default:
                throw new IllegalArgumentException("unexpected viewType: " + viewType);
        }
    }

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

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        int layout;
        RecyclerView.ViewHolder viewHolder;
        switch (viewType){
            case TYPE_TABLE:
                layout = R.layout.cardview_tableview_withexpandability;
                View tblView = LayoutInflater
                        .from(parent.getContext())
                        .inflate(layout, parent, false);
                viewHolder = new TblViewHolder(tblView);
                break;
            case TYPE_SEPARATOR:
                layout = R.layout.lineseparatorforrecyclerview;
                View separatorView = LayoutInflater
                        .from(parent.getContext())
                        .inflate(layout, parent, false);
                viewHolder = new SeparatorViewHolder(separatorView);
                break;
            default:
                throw new IllegalArgumentException("unexpected viewType: " + viewType);
        }
        return viewHolder;
    }

    public class TblViewHolder extends RecyclerView.ViewHolder {
        final Typeface iconFont = FontManager.getTypeface(context, FontManager.FONTAWESOME);

        private Button btnToday, btnYesterday, btnThisWeek, btnThisMonth;
        private TextView arrowexpandcollapseTextView, sectionNameTextView;

        TblViewHolder(View itemView) {
            super(itemView);

            btnMale.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    AlertDialog alertDialog = new AlertDialog.Builder(v.getContext()).create();

                    alertDialog.setButton(Dialog.BUTTON_NEUTRAL,"OK",new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });


                    LayoutInflater inflater = LayoutInflater.from(context);
                    @SuppressLint("InflateParams") View content = inflater.inflate(R.layout.dialog_stats, null);
                    alertDialog.setView(content);

                    //Pulling String out of bundle
                    String goalreached = mBundle.getString("goalreached");   
                    String day = mBundle.getString("day");
                    String distance = mBundle.getString("distance");                        
                    String calories = mBundle.getString("calories");


                    ImageView imgdialogMain = content.findViewById(R.id.imgView_genderA);
                    ivGenderA.setImageResource(R.drawable.ic_male);

                    TextView tvGoalReached = content.findViewById(R.id.txtView_dialog_goalreached);
                    tvGoalReached.setText(goalreached);


                    TextView tvDay = content.findViewById(R.id.txtView_day);
                    tvDay.setText(day);

                    TextView tvImgviewWalking = content.findViewById(R.id.imgView_walking);


                    TextView tvDistance = content.findViewById(R.id.txtView_distance);
                    tvDistance.setText(distance);

                    TextView tvImgviewFire = content.findViewById(R.id.imgView_fire);

                    TextView tvCaloriesBurned = content.findViewById(R.id.txtView_location);
                    tvCaloriesBurned.setText(calories);

                    alertDialog.show();
                }
            });
        }
    }
}

当前,您只是在片段中创建一个新包,然后向其中添加字符串,然后对其不执行任何操作,然后在适配器中创建另一个新包,并尝试提取不存在的字符串。

要更新数据,您可以在需要更新数据时尝试在适配器中调用类似的方法(虽然不确定notifyDataSetChanged()是否可以从适配器内部运行):

//Update Bundle
public void updateView(Bundle bundle){
    mBundle = bundle;
    this.notifyDataSetChanged();
}

答案 1 :(得分:1)

您正在尝试从此处的新捆绑包中获取额外优惠:

Bundle bundle = new Bundle();
String goalreached = bundle.getString("goalreached");
...

您需要获取用于存储该信息的捆绑软件。捆绑包只是信息的“容器”,因此您需要先存储然后再检索。

您永远不会将捆绑软件保存在任何地方,因此以后将无法阅读。

我不确定您要在这里做什么,所以我无法举个例子,只需要检查一下即可:

Bundle bundle = new Bundle();
bundle.putString("goalreached",  getResources().getString(R.string.goal_reached));
bundle.putString("day",  getResources().getString(R.string.today));
bundle.putString("distance",  getResources().getString(R.string._3_2_km));
bundle.putString("calories",  getResources().getString(R.string._213_kcal));

您正在创建该捆绑包,然后存储信息,仅此而已。您永远不会将其存储在任何地方。

捆绑软件的基本用法是将其存储在一个Intent上,然后检索该Intent并获取捆绑软件。