将RecyclerView从活动迁移到片段-无法使用findViewById

时间:2018-11-19 13:55:07

标签: android

我将以下代码从MainActivity复制到一个单独的片段中,但是无法运行findViewById: 我得到“无法解析方法findViewById(int)” 这些是相关文件:

**还是初学者,您能否让我知道我的代码是否存在需要修复的一般问题?

MyFragment.java:

public class MyFragment extends Fragment {


    public myFragment() {
        // Required empty public constructor
    }
    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_my, container, false);
        mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);

        // use this setting to improve performance if you know that changes
        // in content do not change the layout size of the RecyclerView
        mRecyclerView.setHasFixedSize(true);

        // use a linear layout manager
        mLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);

        //placeholder data
        String[] myDataset = new String[16];
        myDataset[0] = "Data0";
        myDataset[1] = "Data1";
        myDataset[2] = "Data2";
        myDataset[3] = "Data3";
        myDataset[4] = "Data4";
        myDataset[5] = "Data5";
        myDataset[6] = "Data6";
        myDataset[7] = "Data7";
        myDataset[8] = "Data8";
        myDataset[9] = "Data9";
        myDataset[10] = "Data10";
        myDataset[11] = "Data11";
        myDataset[12] = "Data12";
        myDataset[13] = "Data13";
        myDataset[14] = "Data14";
        myDataset[15] = "Data15";

        // specify an adapter (see also next example)
        mAdapter = new MyAdapter(myDataset);
        mRecyclerView.setAdapter(mAdapter);


    }

}

MyAdapter.java:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    private String[] mDataset;

    // Provide a reference to the views for each data item
    // Complex data items may need more than one view per item, and
    // you provide access to all the views for a data item in a view holder
    public static class MyViewHolder extends RecyclerView.ViewHolder {
        // each data item is just a string in this case
        public TextView upTv;
        public TextView downTv;
        public View layout;
        public MyViewHolder(View v) {
            super(v);
            layout = v;
            upTv = (TextView)v.findViewById(R.id.upTv);
            downTv = (TextView)v.findViewById(R.id.downTv);
        }
    }

    // Provide a suitable constructor (depends on the kind of dataset)
    public MyAdapter(String[] myDataset) {
        mDataset = myDataset;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
                                                     int viewType) {


        View v =  LayoutInflater.from(parent.getContext())
                .inflate(R.layout.my_text_view, parent, false);

        MyViewHolder vh = new MyViewHolder(v);
        return vh;
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        // - get element from your dataset at this position
        // - replace the contents of the view with that element
        holder.upTv.setText(mDataset[position]);
        holder.downTv.setText(mDataset[position]);
    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return mDataset.length;
    }
}

fragment_my.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
   >

    <android.support.v7.widget.RecyclerView
        android:id="@+id/my_recycler_view"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="4dp"
        android:scrollbars="vertical"/>


</android.support.constraint.ConstraintLayout>

my_text_view.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    android:padding="6dip" >

    <ImageView
        android:id="@+id/icon"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_alignParentBottom="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="6dip"
        android:contentDescription="TODO"
        android:src="@drawable/ic_launcher_background" />

    <TextView
        android:id="@+id/downTv"
        android:layout_width="fill_parent"
        android:layout_height="26dip"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_toRightOf="@id/icon"

        android:text="downTv"
        android:textSize="12sp" />

    <TextView
        android:id="@+id/upTv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_alignWithParentIfMissing="true"
        android:layout_toRightOf="@id/icon"
        android:gravity="center_vertical"
        android:text="upTv"
        android:textSize="16sp" />

</RelativeLayout>

3 个答案:

答案 0 :(得分:1)

这是您的问题:

return inflater.inflate(R.layout.fragment_my, container, false);

您不能在return语句后添加更多代码。您将需要获取膨胀视图的引用,并使用它来找到子视图的引用。

View rootView = inflater.inflate(R.layout.fragment_my, container, false);

mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);

// other code

return rootView;

答案 1 :(得分:0)

使用片段的一种非常好的方法是在切换到片段时初始化与父活动关联的某些变量(例如,活动,上下文,根视图等)。 例如,您可以做某事,

private Context context;
        private MainActivity activity; //Let MainActivity is your parent activity
        private View view; //fields kept inside the fragment class,now we need to keep them initialized

    //initialize activity/context from onAttach
        @Override
        public void onAttach(Context c) {
        super.onAttach(c);

                Activity a;

                context=c;
                if (c instanceof Activity){
                    a=(Activity) c;
                    if(a instanceof MainActivity)
                        activity=(MainActivity) a;
                }

            }
//initialize view from onViewCreated
     @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
           this.view=view;
        }

现在您可以在片段类中的任何位置使用它们,而无需触发任何nullptrs和其他内容

例如-您可以走

this.view.findViewById(your_resId); 
this.activity.getSupportFragmentManager();

等以及您需要时使用的其他许多内容,请使用您初始化的这些字段

在使用recyclerView的情况下也要特别注意,不要忘记调用, adapter.notifyDataSetChanged()每当您认为要在recyclerView中显示的列表进行某些更改时。

答案 2 :(得分:0)

我没有足够的声誉来发表评论,所以我正在写这篇文章作为对您评论的回答。 您需要使用以下代码通知适配器。

mAdapter.notifyDataSetChanged();