Fragment静态传值(RecyclerView,接口回调)

效果图:


Fragment静态传值(RecyclerView,接口回调)


布局 :

activity:

<fragment
        android:layout_width="0dp"
        android:layout_weight="1"
        android:name="com.example.administrator.yn_demob.Fragmnet1"
        android:layout_height="match_parent"
        android:id="@+id/f1"></fragment>
    <fragment
        android:layout_width="0dp"
        android:layout_weight="2"
        android:name="com.example.administrator.yn_demob.Fragmnet2"
        android:layout_height="match_parent"
        android:id="@+id/f2"></fragment>
fragment1:

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

<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/f2_rec"></android.support.v7.widget.RecyclerView>
f1_list布局

<TextView

      android:textColor="@drawable/select"
android:textSize="18dp" android:text="大多数" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/f1_list_text"/>f2_list布局

<ImageView
    android:layout_width="100dp"
    android:src="@mipmap/ic_launcher"
    android:layout_height="100dp"
    android:id="@+id/f2_list__pic"/>
    <TextView
        android:text="的繁华都市跨界"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="15dp"
        android:id="@+id/f2_list_text"/>
//写一个selector字体变颜色

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:color="#ff0"/>
<item android:state_selected="false" android:color="#000"/>
</selector>


MainActivity类什么都不用写,因为我们用的静态注册的
Fragment1 类中

public class Fragmnet1 extends Fragment {
    private RecyclerView rec;
    public void setOnItem(OnItem onItem) {
        this.onItem = onItem;
    }

    private OnItem onItem;
    private Handler handler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==0){
                String str = (String) msg.obj;
                //Gson解析
                Gson gson =new Gson();
                Bean bean = gson.fromJson(str, Bean.class);
                final List<Bean.ResultBean.BrandsBean> brands = bean.getResult().getBrands();
                rec.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false));
                MyList my =new MyList(getActivity(),brands);
                rec.setAdapter(my);
               //适配器点击并接口回调传值
                my.setOnItemLiener(new MyList.OnItemLiener() {
                    @Override
                    public void ItemLiseren(View view, int position) {
                        
                        onItem.OnItems(position,brands);
                    }
                });
            }
        }
    };


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view =inflater.inflate(R.layout.f1_main,null);
       //找空件
        initView(view);
        return view;
    }

    private void initView(View view) {
        rec = (RecyclerView) view.findViewById(R.id.f1_rec);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getData();
    }
    //定义一个接口并提供set方法
    public  interface  OnItem{
        void OnItems(int posotion,List<Bean.ResultBean.BrandsBean> list);
    }
    // OkHttpClient进行解析
    private void getData() {
        OkHttpClient mOkHttp =new OkHttpClient();

        String url ="http://www.babybuy100.com/API/getShopOverview.ashx";
        Request request =new Request.Builder().url(url).build();
        Call call = mOkHttp.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(Response response) throws IOException {
                String string = response.body().string();
                Message message = handler.obtainMessage(0, string);
                message.sendToTarget();
            }
        });
    }
}
f1_适配器


public class MyList extends RecyclerView.Adapter<MyList.ViewHolder> {
   private Context context;
    private List<Bean.ResultBean.BrandsBean> brands;
    private OnItemLiener onItemLiener;
    private  int item =0;

    public void setOnItemLiener(OnItemLiener onItemLiener) {
        this.onItemLiener = onItemLiener;
    }

    public interface OnItemLiener{
        void ItemLiseren(View view,int position);
    }
    public MyList(Context context, List<Bean.ResultBean.BrandsBean> brands) {
        this.context=context;
        this.brands=brands;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view =View.inflate(context,R.layout.f1_list,null);
        final ViewHolder holder =new ViewHolder(view);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = holder.getLayoutPosition();
                item =position;
                if(onItemLiener!=null){
                    onItemLiener.ItemLiseren(v,position);
                }
                notifyDataSetChanged();
            }
        });
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
       holder.text.setText(brands.get(position).getTitle());
        //点击字体变颜色
        if(item==position){
            holder.text.setSelected(true);
        }else{
            holder.text.setSelected(false);
        }
    }

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

    class ViewHolder extends  RecyclerView.ViewHolder{

        private final TextView text;

        public ViewHolder(View itemView) {
            super(itemView);
            text = (TextView) itemView.findViewById(R.id.f1_list_text);

        }
    }
}

fragment2类中:

public class Fragmnet2 extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view =inflater.inflate(R.layout.f2_main,null);
        initView(view);
        return view;
    }

    private void initView(View view) {
        final RecyclerView rec = (RecyclerView) view.findViewById(R.id.f2_rec);
        rec.setLayoutManager(new GridLayoutManager(getActivity(),3,GridLayoutManager.VERTICAL,false));
       //使用接口回调传过来的值
        Fragmnet1 f1 = (Fragmnet1) getActivity().getSupportFragmentManager().findFragmentById(R.id.f1);
        f1.setOnItem(new Fragmnet1.OnItem() {
            @Override
            public void OnItems(int posotion, List<Bean.ResultBean.BrandsBean> list) {
                MyGrid my =new MyGrid(getActivity(),list.get(posotion).getProducts());
                rec.setAdapter(my);
              

            }
        });

    }

}
f2_适配器

public class MyGrid extends RecyclerView.Adapter<MyGrid.ViewHolder> {
    private  Context context;

    private List<Bean.ResultBean.BrandsBean.ProductsBean> products;

    public MyGrid(Context context, List<Bean.ResultBean.BrandsBean.ProductsBean> products) {
        this.context=context;

        this.products =products;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.f2_list,null);
        ViewHolder holder =new ViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {

           Glide.with(context).load(products.get(position).getPic()).into(holder.pic);
        holder.textx.setText(products.get(position).getName());
    }

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

    class ViewHolder extends  RecyclerView.ViewHolder{

        private final ImageView pic;
        private final TextView textx;

        public ViewHolder(View itemView) {
            super(itemView);
            pic = (ImageView) itemView.findViewById(R.id.f2_list__pic);
            textx = (TextView) itemView.findViewById(R.id.f2_list_text);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = getLayoutPosition();
                    Toast.makeText(context, "当前的条目" + position, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }
}