1. 程式人生 > >Fragment靜態傳值(RecyclerView,介面回撥)

Fragment靜態傳值(RecyclerView,介面回撥)

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(); } }); } }