从适配器RecyclerView打开片段

时间:2017-07-15 21:24:30

标签: android onclick android-recyclerview fragment

我的应用程序遇到了一些麻烦。我有使用CardView的recyclerView。我想打开一个包含信息描述的新片段......但这并不重要。

这是我的适配器

public class RVAdapter extends RecyclerView.Adapter<RVAdapter.DataViewHolder>{

//here
private OnRecyclerViewItemClickListener mClickListener;

public static class DataViewHolder extends RecyclerView.ViewHolder{
    CardView cardView;
    TextView textViewName;
    TextView textViewRegion;

    public DataViewHolder(View itemView) {
        super(itemView);
        cardView = (CardView) itemView.findViewById(R.id.cardView);
        textViewName = (TextView) itemView.findViewById(R.id.textViewName);
        textViewRegion = (TextView) itemView.findViewById(R.id.textViewRegion);
    }
}

private List<DataJSON> dataList;

RVAdapter(List<DataJSON> dataList){
    this.dataList = dataList;
}

@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
    super.onAttachedToRecyclerView(recyclerView);
}

@Override
public DataViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
    DataViewHolder dvh = new DataViewHolder(v);
    return dvh;
}

private DataJSON getItem(int position){
    return dataList.get(position);
}

@Override
public void onBindViewHolder(DataViewHolder holder, final int position) {
    holder.textViewName.setText(dataList.get(position).getPierName());
    holder.textViewRegion.setText(dataList.get(position).getRegion());

    holder.cardView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.d("myLog", "Click-clack position " + position);
            if (mClickListener != null){
                Log.d("myLog", "mClickListener != null");
                mClickListener.onClick(position);
            } else {Log.d("myLog", "mClickListener = null");}
        }
    });
}

//here
public interface OnRecyclerViewItemClickListener {
    void onClick(int parameter);
}

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

}

在onBindViewHolder中我有onClick,我在MainActivity中调用OnRecyclerViewItemClickListener onClick。

这是MainActivity。

public class MainActivity extends AppCompatActivity implements RVAdapter.OnRecyclerViewItemClickListener{
private CardViewFragment cardViewFragment;
private DetailFragment detailFragment;

private FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.d("MyTag", "onCreate");

    //Create FragmentManager
    fragmentManager = getSupportFragmentManager();

    //Initialization fragments
    cardViewFragment = new CardViewFragment();
    detailFragment = new DetailFragment();


    fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.container, cardViewFragment, CardViewFragment.TAG);
    fragmentTransaction.commit();
}

@Override
public void onClick(int parameter) {
    Log.d("myLog", "Hi, from MainActivity");
    fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.container, detailFragment, DetailFragment.TAG);
    fragmentTransaction.commit();
}

}

我有一个错误,mClickListener是null对象,并了解它, 但我真的不知道如何解决它。

这是CardViewFragment

public class CardViewFragment extends Fragment implements RVAdapter.OnRecyclerViewItemClickListener {

public static final String TAG = "CardViewFragment";

private List<DataJSON> dataJSONList;
private RecyclerView recyclerView;
RVAdapter rvAdapter;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState){
    View rootView = inflater.inflate(R.layout.activity_card_view_fragment, container, false);

    dataJSONList = new ArrayList<>();
    recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);

    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(linearLayoutManager);
    recyclerView.setHasFixedSize(true);

    loadDataFromServer();
    //testData();

    rvAdapter = new RVAdapter(this, dataJSONList);
    recyclerView.setAdapter(rvAdapter);

    getActivity();
    return rootView;
}

private void testData(){
    //dataJSONList.add(new DataJSON(0, "RiverIsland", "Moscow", "Moscow is the capital of Russia"));
    //dataJSONList.add(new DataJSON(1, "kek", "Lol", "Scream"));
    DataJSON data2 = new DataJSON(0, "RiverIsland", "Moscow", "Moscow is the capital of Russia");
    dataJSONList.add(data2);
}

String strJson;
private void loadDataFromServer()  {

    AsyncTask<Void, Void, String> task = new AsyncTask<Void, Void, String>(){
        @Override
        protected String doInBackground(Void... voids) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url("https://gesmetrics.ru/testpiers.php").build();
            Response response;

            try {
                response = client.newCall(request).execute();
                strJson = response.body().string();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return strJson;
        }

        @Override
        protected void onPostExecute(String strJson) {
            super.onPostExecute(strJson);
            Log.d("myLog", strJson);

            //DataJSON data2 = new DataJSON(0, "RiverIsland", "Moscow", "Moscow is the capital of Russia");
            //dataJSONList.add(data2);

            try {
                JSONArray jsonArray = new JSONArray(strJson);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject object = jsonArray.getJSONObject(i);

                    int id = object.getInt("pierId");
                    String name = object.getString("pierName");
                    String region = object.getString("region");
                    String description = object.getString("description");
                    DataJSON data = new DataJSON(i, name, region, description);
                    //nothing happens here
                    dataJSONList.add(data);
                }
            } catch (JSONException e) {
                System.out.println("Issue");
            }
            rvAdapter.notifyDataSetChanged();
        }

    };
    task.execute();
}

@Override
public void onClick(int parameter) {

}

}

MainActivity

public class MainActivity extends AppCompatActivity implements RVAdapter.OnRecyclerViewItemClickListener{
private CardViewFragment cardViewFragment;
private DetailFragment detailFragment;

private FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.d("MyTag", "onCreate");

    //Create FragmentManager
    fragmentManager = getSupportFragmentManager();

    //Initialization fragments
    cardViewFragment = new CardViewFragment();
    detailFragment = new DetailFragment();


    fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.container, cardViewFragment, CardViewFragment.TAG);
    fragmentTransaction.commit();
}

@Override
public void onClick(int parameter) {
    Log.d("myLog", "Hi, from MainActivity");
    fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.container, detailFragment, DetailFragment.TAG);
    fragmentTransaction.commit();
}

}

非常感谢!

1 个答案:

答案 0 :(得分:1)

  1. 通过适配器的构造函数传递click侦听器。

    RVAdapter(OnRecyclerViewItemClickListener listener,List<DataJSON> dataList){
        mClickListener = listener;
        this.dataList = dataList;
    }
    
  2. CardViewFragment

    中进行片段交易
    public class CardViewFragment extends Fragment implements RVAdapter.OnRecyclerViewItemClickListener {
    
    @Override
    public void onClick(int parameter) {
        //either add fragment
        //getChildFragmentManager().beginTransaction()
        //        .add(new DetailFragment(), null)
        //        .commit();
        //or if you defined any container for DetailFragment(like frame layout) in your fragment layout file which is activity_card_view_fragment.xml just use replace
        getChildFragmentManager().beginTransaction()
                .replace(R.id.container, new DetailFragment())
                .commit();
    
        }
    }