如何将RecyclerView扩展到Fragment.java类?

时间:2017-04-30 04:08:00

标签: android android-fragments

我对Android很新,目前正在开发聊天应用。我打算将RecyclerView实现到多个TabLayout中,并且我仍然坚持将回收器视图的片段扩展到Fragment类中。以下是所涉及的源代码。

fragment_one.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:emojicon="http://schemas.android.com/apk/res-auto"
    android:id="@+id/contentRoot"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/background">



    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">

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

        <View
            android:layout_width="match_parent"
            android:layout_height="4dp"
            android:layout_gravity="bottom"
            android:background="@drawable/shadow_top" />
    </FrameLayout>


    <RelativeLayout
        android:background="#fff"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="2dp">
        <ImageView
            android:id="@+id/buttonEmoji"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:padding="4dp"
            android:src="@drawable/smiley"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignBottom="@+id/editTextMessage"
            />
        <hani.momanii.supernova_emoji_library.Helper.EmojiconEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/editTextMessage"
            android:layout_toStartOf="@+id/buttonMessage"
            android:layout_toRightOf="@+id/buttonEmoji"
            android:layout_toEndOf="@+id/buttonEmoji"
            emojicon:emojiconSize="28sp"/>
        <ImageView
            android:id="@+id/buttonMessage"
            android:src="@android:drawable/ic_menu_send"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:padding="4dp"
            android:layout_alignBottom="@+id/editTextMessage"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            />
    </RelativeLayout>

</LinearLayout>

Adapter.java

package example.asuspc.prospect;

/**
 * Created by asus pc on 12/2/2016.
 */
import android.content.Context;
import android.media.Image;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.Collections;
import java.util.List;

/**
 * Created by asus pc on 11/3/2016.
 */
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {

    private static final int TYPE_HEADER = 0;  // Declaring Variable to Understand which View is being worked on
    // IF the view under inflation and population is header or Item
    private static final int TYPE_ITEM = 1;

    private String mNavTitles[]; // String Array to store the passed titles Value from MainActivity.java
    private int mIcons[];       // Int Array to store the passed icons resource value from MainActivity.java

    private String name;        //String Resource for header View Name
    private int profile;        //int Resource for header view profile picture
    private String email;       //String Resource for header view email


    // Creating a ViewHolder which extends the RecyclerView View Holder
    // ViewHolder are used to to store the inflated views in order to recycle them

    public static class ViewHolder extends RecyclerView.ViewHolder {
        int Holderid;

        TextView textView;
        ImageView imageView;
        ImageView profile;
        TextView Name;
        TextView email;


        public ViewHolder(View itemView,int ViewType) {                 // Creating ViewHolder Constructor with View and viewType As a parameter
            super(itemView);


            // Here we set the appropriate view in accordance with the the view type as passed when the holder object is created

            if(ViewType == TYPE_ITEM) {
                textView = (TextView) itemView.findViewById(R.id.rowText); // Creating TextView object with the id of textView from item_row.xml
                imageView = (ImageView) itemView.findViewById(R.id.rowIcon);// Creating ImageView object with the id of ImageView from item_row.xml
                Holderid = 1;                                               // setting holder id as 1 as the object being populated are of type item row
            }
            else{


                Name = (TextView) itemView.findViewById(R.id.name);         // Creating Text View object from header.xml for name
                email = (TextView) itemView.findViewById(R.id.email);       // Creating Text View object from header.xml for email
                profile = (ImageView) itemView.findViewById(R.id.circleView);// Creating Image view object from header.xml for profile pic
                Holderid = 0;                                                // Setting holder id = 0 as the object being populated are of type header view
            }
        }


    }



    Adapter(String Titles[],int Icons[],String Name,String Email, int Profile){ // MyAdapter Constructor with titles and icons parameter
        // titles, icons, name, email, profile pic are passed from the main activity as we
        mNavTitles = Titles;                //have seen earlier
        mIcons = Icons;
        name = Name;
        email = Email;
        profile = Profile;                     //here we assign those passed values to the values we declared here
        //in adapter



    }



    //Below first we ovverride the method onCreateViewHolder which is called when the ViewHolder is
    //Created, In this method we inflate the item_row.xml layout if the viewType is Type_ITEM or else we inflate header.xml
    // if the viewType is TYPE_HEADER
    // and pass it to the view holder

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

        if (viewType == TYPE_ITEM) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_row,parent,false); //Inflating the layout

            ViewHolder vhItem = new ViewHolder(v,viewType); //Creating ViewHolder and passing the object of type view

            return vhItem; // Returning the created object

            //inflate your layout and pass it to view holder

        } else if (viewType == TYPE_HEADER) {

            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.header,parent,false); //Inflating the layout

            ViewHolder vhHeader = new ViewHolder(v,viewType); //Creating ViewHolder and passing the object of type view

            return vhHeader; //returning the object created


        }
        return null;

    }

    //Next we override a method which is called when the item in a row is needed to be displayed, here the int position
    // Tells us item at which position is being constructed to be displayed and the holder id of the holder object tell us
    // which view type is being created 1 for item row
    @Override
    public void onBindViewHolder(Adapter.ViewHolder holder, int position) {
        if(holder.Holderid ==1) {                              // as the list view is going to be called after the header view so we decrement the
            // position by 1 and pass it to the holder while setting the text and image
            holder.textView.setText(mNavTitles[position - 1]); // Setting the Text with the array of our Titles
            holder.imageView.setImageResource(mIcons[position -1]);// Settimg the image with array of our icons
        }
        else{

            holder.profile.setImageResource(profile);           // Similarly we set the resources for header view
            holder.Name.setText(name);
            holder.email.setText(email);
        }
    }

    // This method returns the number of items present in the list
    @Override
    public int getItemCount() {
        return mNavTitles.length+1; // the number of items in the list will be +1 the titles including the header view.
    }


    // Witht the following method we check what type of view is being passed
    @Override
    public int getItemViewType(int position) {
        if (isPositionHeader(position))
            return TYPE_HEADER;

        return TYPE_ITEM;
    }

    private boolean isPositionHeader(int position) {
        return position == 0;
    }

}

OneFragment.java

    package example.asuspc.prospect;


    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ImageView;



    public class OneFragment extends Fragment{


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



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

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            View rootView = inflater.inflate(R.layout.fragment_one, container, false);


            return rootView;
        }

}

我正在尝试在OneFragment.java中对循环器视图进行充气,但我完全被困在这里。真的很感激,如果有人可以提供帮助

3 个答案:

答案 0 :(得分:2)

更新OneFragment,如下所示:

public class OneFragment extends Fragment {

    // Context
    Context mContext;

    // RecyclerView
    RecyclerView mRecyclerView;
    Adapter mAdapter;
    RecyclerView.LayoutManager mLayoutManager;

    // Values
    private String[] mNavTitles = {"Title One", "Title Two", "Title Three"};
    private int[] mIcons = {R.drawable.icon1, R.drawable.icon2, R.drawable.icon3};
    private String mName;
    private String mEmail;


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

        // Context
        mContext = getActivity();   

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

        // Views
        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.messageRecyclerView);

        // 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);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());    

        mName = "Android";
        mEmail = "android@google.com";

        // specify an adapter
        mAdapter = new Adapter(getActivity(), mNavTitles, mIcons, mName, mEmail, R.drawable.profile_icon);
        mRecyclerView.setAdapter(mAdapter);


        return rootview;
    }

    .................
    ...................... 
}

更新Adapter课程如下:

package example.asuspc.prospect;

/**
 * Created by asus pc on 12/2/2016.
 */
import android.content.Context;
import android.media.Image;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.Collections;
import java.util.List;

/**
 * Created by asus pc on 11/3/2016.
 */
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {

    private static final int TYPE_HEADER = 0;  // Declaring Variable to Understand which View is being worked on
    // IF the view under inflation and population is header or Item
    private static final int TYPE_ITEM = 1;

    private String mNavTitles[]; // String Array to store the passed titles Value from MainActivity.java
    private int mIcons[];       // Int Array to store the passed icons resource value from MainActivity.java

    private String name;        //String Resource for header View Name
    private int profile;        //int Resource for header view profile picture
    private String email;       //String Resource for header view email

    private Context mContext;

    Adapter(Context context, String Titles[],int Icons[],String Name,String Email, int Profile) { 
        mNavTitles = Titles;               
        mIcons = Icons;
        name = Name;
        email = Email;
        profile = Profile;                   

        this.mContext = context;
    }

    // Creating a ViewHolder which extends the RecyclerView View Holder
    // ViewHolder are used to to store the inflated views in order to recycle them

    public static class ViewHolder extends RecyclerView.ViewHolder {
        int Holderid;

        TextView textView;
        ImageView imageView;
        ImageView profile;
        TextView Name;
        TextView email;

        public ViewHolder(View itemView,int ViewType) {                 // Creating ViewHolder Constructor with View and viewType As a parameter
            super(itemView);

            // Here we set the appropriate view in accordance with the the view type as passed when the holder object is created

            if(ViewType == TYPE_ITEM) {
                textView = (TextView) itemView.findViewById(R.id.rowText); // Creating TextView object with the id of textView from item_row.xml
                imageView = (ImageView) itemView.findViewById(R.id.rowIcon);// Creating ImageView object with the id of ImageView from item_row.xml
                Holderid = 1;                                               // setting holder id as 1 as the object being populated are of type item row
            }
            else{

                Name = (TextView) itemView.findViewById(R.id.name);         // Creating Text View object from header.xml for name
                email = (TextView) itemView.findViewById(R.id.email);       // Creating Text View object from header.xml for email
                profile = (ImageView) itemView.findViewById(R.id.circleView);// Creating Image view object from header.xml for profile pic
                Holderid = 0;                                                // Setting holder id = 0 as the object being populated are of type header view
            }
        }
    }

    //Below first we ovverride the method onCreateViewHolder which is called when the ViewHolder is
    //Created, In this method we inflate the item_row.xml layout if the viewType is Type_ITEM or else we inflate header.xml
    // if the viewType is TYPE_HEADER
    // and pass it to the view holder

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

        if (viewType == TYPE_ITEM) {
            View v = LayoutInflater.from(mContext).inflate(R.layout.custom_row,parent,false); //Inflating the layout

            ViewHolder vhItem = new ViewHolder(v,viewType); //Creating ViewHolder and passing the object of type view

            return vhItem; // Returning the created object

            //inflate your layout and pass it to view holder

        } else if (viewType == TYPE_HEADER) {

            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.header,parent,false); //Inflating the layout

            ViewHolder vhHeader = new ViewHolder(v,viewType); //Creating ViewHolder and passing the object of type view

            return vhHeader; //returning the object created


        }
        return null;

    }

    //Next we override a method which is called when the item in a row is needed to be displayed, here the int position
    // Tells us item at which position is being constructed to be displayed and the holder id of the holder object tell us
    // which view type is being created 1 for item row
    @Override
    public void onBindViewHolder(Adapter.ViewHolder holder, int position) {
        if(holder.Holderid ==1) {                              // as the list view is going to be called after the header view so we decrement the
            // position by 1 and pass it to the holder while setting the text and image
            holder.textView.setText(mNavTitles[position - 1]); // Setting the Text with the array of our Titles
            holder.imageView.setImageResource(mIcons[position -1]);// Settimg the image with array of our icons
        }
        else{

            holder.profile.setImageResource(profile);           // Similarly we set the resources for header view
            holder.Name.setText(name);
            holder.email.setText(email);
        }
    }

    // This method returns the number of items present in the list
    @Override
    public int getItemCount() {
        return mNavTitles.length+1; // the number of items in the list will be +1 the titles including the header view.
    }


    // Witht the following method we check what type of view is being passed
    @Override
    public int getItemViewType(int position) {
        if (isPositionHeader(position))
            return TYPE_HEADER;

        return TYPE_ITEM;
    }

    private boolean isPositionHeader(int position) {
        return position == 0;
    }

}

答案 1 :(得分:0)

初始化回收站视图,设置布局管理器,然后设置适配器。

答案 2 :(得分:0)

我希望这会对你有帮助 -

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

    RecyclerView recyclerView = (RecyclerView) rootView .findViewById(R.id.messageRecyclerView);
    Adapter mAdapter = new Adapter(dItem, getActivity());
    // GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2);
    LinearLayoutManager lnrLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setAdapter(mAdapter);
recyclerView.setLayoutManager(gridLayoutManager);
适配器中的

    List<modelClassItem> dItem;
    Context context;

public Adapter(List<modelClassItem> doItem, Context context) {
        this.doItem = doItem;
        this.context = context;
    }