为什么在Fragment中使用CardView的Recyclerview无法显示任何内容?

时间:2017-03-19 10:51:03

标签: android android-fragments android-recyclerview android-cardview

我是Android的初学者。当我在带有TabLayout的片段中使用ListView时,一切都很好。 enter image description here 现在我想用TabLayout在Fragment中实现带有CardView行的RecyclerView。 但是,当使用带有CardView的RecyclerView时,片段中没有显示任何内容。为什么? enter image description here

请帮忙!提前谢谢!

这是我的代码:

MainActivity.java:

make -j n

activity_main.xml中:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 关联ViewPager和SampleFragmentPagerAdapter,配置tabs用以下两个步骤:

        // ① Get the ViewPager and set it's PagerAdapter so that it can display items
        ViewPager viewPager=(ViewPager) findViewById(R.id.viewpager);
        viewPager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager(),MainActivity.this));

        // ② 为了关联pager和tabs,在TabLayout中设置ViewPager
        TabLayout tabLayout=(TabLayout) findViewById(R.id.sliding_tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    public class SampleFragmentPagerAdapter extends FragmentPagerAdapter{
        final int PAGE_COUNT=3;
        private String[] tabTitles={"知乎日报","果壳精选","豆瓣一刻"};
        private Context context;

        public SampleFragmentPagerAdapter(FragmentManager fm, Context context) {
            super(fm);
            this.context = context;
        }

        @Override
        public int getCount() {
            return PAGE_COUNT;
        }

        @Override
        public Fragment getItem(int position) {
            return PageFragment.newInstance(position+1);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return tabTitles[position];
        }
    }
}

PageFragment.java:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.sherrywong.stonedaily.MainActivity">

    <android.support.design.widget.TabLayout
        android:id="@+id/sliding_tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabMode="fixed"
        app:tabGravity="fill">
    </android.support.design.widget.TabLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="1"
        android:background="@android:color/white">
    </android.support.v4.view.ViewPager>

</LinearLayout>

MyAdapter.java:

public class PageFragment extends Fragment{
    private String TAG=PageFragment.class.getName();    // 打印log时使用
    private static final String ARG_PAGE = "ARG_PAGE";
    private int mPage;
    private RecyclerView recyclerView;
    private MyAdapter myAdapter;

    private OnFragmentInteractionListener mListener;

    public PageFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     * @param page
     * @return A new instance of fragment PageFragment.
     */
    public static PageFragment newInstance(int page) {
        Bundle args=new Bundle();
        args.putInt(ARG_PAGE,page);
        PageFragment fragment=new PageFragment();
        fragment.setArguments(args);
        return fragment;
    }

    //Store instance variables based on arguments passed
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG,"---------onCreate");
        if (getArguments() != null) {
            mPage=getArguments().getInt(ARG_PAGE);
        }


    }

    /**
     * Define fragment layout
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return View
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_page,container,false);
        // 获取RecyclerView
        recyclerView=(RecyclerView) view.findViewById(R.id.recycler_list);
        // 设置布局管理器
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        // 设置ItemAnimator
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        // 设置固定大小
        recyclerView.setHasFixedSize(true);
        // 初始化自定义适配器
        String[] list={"class 1","class 2","class 3","class 4","class 5","class 6","class 7","class 8"};
        myAdapter=new MyAdapter(getActivity(),getData(list));
        // 为recyclerView设置适配器
        recyclerView.setAdapter(myAdapter);

        Log.i(TAG,"---------onCreateView");
        return view;
    }

    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);
    }
/*

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);

        System.out.println(l.getChildAt(position));
        HashMap<String,String> view=(HashMap<String, String>) l.getItemAtPosition(position);
        System.out.println(view.get("title").toString()+"+++++++++title");

        Toast.makeText(getActivity(),TAG+l.getItemIdAtPosition(position),Toast.LENGTH_SHORT).show();
        System.out.println(v);
        System.out.println(position);

    }
*/

    private List<HashMap<String,String>> getData(String[] args){
        List<HashMap<String,String>> list=new ArrayList<>();
        for (int i=0;i<args.length;i++){
            HashMap<String,String> map=new HashMap<>();
            map.put("title",args[i]);
            map.put("image","http://img3.hao123.com/data/1_8583424a3f55c06ebeafce438a637c0d_0");
            list.add(map);
        }
        return list;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.i(TAG,"-----------onActivityCreated");
    }

}

fragment_page.xml:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

    private Context context;
    private List<HashMap<String,String>> dataSet;

    public MyAdapter(Context context,List<HashMap<String,String>> dataSet){
        this.context=context;
        this.dataSet=dataSet;
    }

    // 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 textView;
        public ImageView imageView;
        public MyViewHolder(View view){
            super(view);
            textView=(TextView) view.findViewById(R.id.itemTitle);
            imageView=(ImageView) view.findViewById(R.id.itemImage);
        }
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // 给ViewHolder设置布局文件
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item,parent,false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        // 给ViewHolder设置元素
        Picasso.with(context).load(dataSet.get(position).get("image")).into(holder.imageView);
        holder.textView.setText(dataSet.get(position).get("title"));
    }

    @Override
    public int getItemCount() {
        // 返回数据总数
        return dataSet==null?0:dataSet.size();
    }


}

card_item.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.sherrywong.stonedaily.PageFragment">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v7.widget.RecyclerView>

</RelativeLayout>

1 个答案:

答案 0 :(得分:0)

Picasso.with(context).load(dataSet.get(position).get("image")).into(holder.imageView);

//将上面的代码行改为

Picasso.with(holder.imageView.getContext()).load(dataSet.get(position).get("image")).into(holder.imageView);