将数据从recycleView传递到另一个

时间:2017-10-25 18:16:38

标签: java android android-fragments interface android-recyclerview

我是Android开发的初学者,我试图制作一个简单的应用程序,使用cardViews在片段内部有一个recycleView,当你点击列表中任何项目内的like按钮时,应用程序应该将此项发送到另一个名为FavoriteFragment的片段(也包含recycleView)并在此处显示。

我尝试使用接口来执行此操作,但每当我单击其中一个类似的按钮时,我的活动都没有收到信息(我尝试在方法内部使用Log.da消息并且未显示)

以下是每个代码:

我的界面,我想用来传递来自国家/地区的数据 - >适配器 - > viewholder - >活动 - >最喜欢的片段

public interface InterfaceListItemClickListener {
void listItemClickAction(ArrayList properties);
}

my CountriesFragment,它是保存第一个RecycleView的片段:

public class CountriesFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

ArrayList<RecycleViewItem> listCountries = new ArrayList<>();
String names[] = {"Thailand", "Venezuela", "Sweden"};
int images[] = {R.drawable.thailand, R.drawable.venezuela, R.drawable.sweden};
RecyclerView myRecyclerView;

InterfaceListItemClickListener sender;

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

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    sender = (InterfaceListItemClickListener) getActivity();
}

public static CountriesFragment newInstance(String param1, String param2) {
    CountriesFragment fragment = new CountriesFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
    initializeList();
}

public void initializeList(){
    listCountries.clear();
    for(int i = 0; i < names.length; i++){
        RecycleViewItem item = new RecycleViewItem();
        item.setCardName(names[i]);
        item.setImageResourceID(images[i]);
        item.setIsFav(0);
        item.setIsTurned(0);
        listCountries.add(item);
    }
}





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

    myRecyclerView = (RecyclerView) view.findViewById(R.id.recycleView);
    myRecyclerView.setHasFixedSize(true);
    LinearLayoutManager myLayoutManager = new LinearLayoutManager(getActivity());
    myLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    ListsForFragments.populateCountriesList();
    if (ListsForFragments.countriesList.size() > 0 & myRecyclerView != null) {
        myRecyclerView.setAdapter(new MyAdapter(ListsForFragments.countriesList, sender));
    }
    myRecyclerView.setLayoutManager(myLayoutManager);
    return view;
}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

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

}

我的适配器类:

public class MyAdapter extends RecyclerView.Adapter<MyViewHolder>{
private ArrayList<RecycleViewItem> list = new ArrayList<RecycleViewItem>();

InterfaceListItemClickListener sender = null;

public MyAdapter(ArrayList<RecycleViewItem> list, InterfaceListItemClickListener sender) {
    this.list = list;
    this.sender = sender;
}

public MyAdapter(ArrayList<RecycleViewItem> list) {
    this.list = list;
}




@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    // create a new view
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycle_items, parent, false);
    MyViewHolder holder = new MyViewHolder(view, sender);
    return holder;
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    holder.titleTextView.setText(list.get(position).getCardName());
    holder.coverImageView.setImageResource(list.get(position).getImageResourceID());
    holder.coverImageView.setTag(list.get(position).getImageResourceID());

}

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

我的viewHolder类:

public class MyViewHolder extends RecyclerView.ViewHolder{

public TextView titleTextView;
public ImageView coverImageView;
public ImageView likeImageView;
public ImageView shareImageView;


public ImageView favoriteImageView;
public TextView favoriteTextView;

private ArrayList goesToFavourites = new ArrayList();
public MyViewHolder(View itemView, final InterfaceListItemClickListener sender) {
    super(itemView);
    titleTextView = (TextView) itemView.findViewById(R.id.titleTextView);
    coverImageView = (ImageView) itemView.findViewById(R.id.coverImageView);
    likeImageView = (ImageView) itemView.findViewById(R.id.likeImageView);
    shareImageView = (ImageView) itemView.findViewById(R.id.shareImageView);

    favoriteImageView = (ImageView) itemView.findViewById(R.id.imageView_favorite);
    favoriteTextView = (TextView) itemView.findViewById(R.id.textView_name_favorite);
    if (likeImageView != null) {
        likeImageView.setTag(R.drawable.ic_like);
        likeImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int id = (int) likeImageView.getTag();
                if (id == R.drawable.ic_like) {
                    likeImageView.setTag(R.drawable.ic_liked);
                    likeImageView.setImageResource(R.drawable.ic_liked);
                    if(sender != null) {
                        getGoesToFavourites().add(coverImageView);
                        getGoesToFavourites().add(likeImageView);
                        sender.listItemClickAction(getGoesToFavourites());
                    }
                } else {
                    likeImageView.setTag(R.drawable.ic_like);
                    likeImageView.setImageResource(R.drawable.ic_like);
                }
            }
        });
    }
}

public ArrayList getGoesToFavourites() {
    return goesToFavourites;
}

public void setGoesToFavourites(ArrayList goesToFavourites) {
    this.goesToFavourites = goesToFavourites;
}
}

我最喜欢的片段类,接收信息的那个:

public class FavoriteFragment extends Fragment {
private OnFragmentInteractionListener mListener;

RecyclerView myRecyclerView;
ArrayList receiver = new ArrayList();

public FavoriteFragment() {

}

public void receiveData(ArrayList receiver){
    this.receiver = receiver;
}


public static FavoriteFragment newInstance() {
    FavoriteFragment fragment = new FavoriteFragment();
    Bundle args = new Bundle();
    fragment.setArguments(args);
    return fragment;
}

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

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

    myRecyclerView = (RecyclerView) view.findViewById(R.id.recycleView);
    myRecyclerView.setHasFixedSize(true);
    LinearLayoutManager myLayoutManager = new LinearLayoutManager(getActivity());
    myLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    if (receiver != null & myRecyclerView != null) {
        myRecyclerView.setAdapter(new MyAdapter(receiver));
    }
    myRecyclerView.setLayoutManager(myLayoutManager);
    return view;    }

public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

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

最后,我的MainActivity,桥梁:

public class MainActivity extends AppCompatActivity implements
        HostFragment.OnFragmentInteractionListener,
        CountriesFragment.OnFragmentInteractionListener,
        CitiesFragment.OnFragmentInteractionListener,
        PlacesFragment.OnFragmentInteractionListener,
        FavoriteFragment.OnFragmentInteractionListener,
        ViewPagerFragment.OnFragmentInteractionListener,
        InterfaceListItemClickListener{

FragmentManager fm;

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


    fm = getSupportFragmentManager();

    //if this is the first time we are running the app
    if(savedInstanceState ==  null){
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.replace(R.id.content, new ViewPagerFragment());
        transaction.commit();
    }
}

@Override
public void onFragmentInteraction(Uri uri) {

}

@Override
public void listItemClickAction(ArrayList list) {
    FavoriteFragment favorite = (FavoriteFragment) 
fm.findFragmentById(R.id.favorite);
    favorite.receiveData(list);
    Log.d("INTERFACE", "Data received!" + list);
}
}

如果需要任何额外信息,请告诉我,我会提供。

编辑:所以试图调试,我发现MyViewHolder的InterfaceListItemClickListener为null,但不确定原因......

编辑2:所以我改变了一些事情,在My CountriesFragment中:

  • 我删除了OnActivityCreated方法,并在onCreate内部初始化了界面,如下所示:

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    initializeList();
    sender = (InterfaceListItemClickListener) getActivity();
    }
    

现在有了这个改变,我能够知道我的MainActivity中的findFragmentById返回null。现在,我显示这个片段的方式是使用一个包含两个片段的ViewPager片段。这看起来像这样:

public class ViewPagerFragment extends Fragment {


private OnFragmentInteractionListener mListener;

public static ViewPager viewPager;

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

public static ViewPagerFragment newInstance() {
    ViewPagerFragment fragment = new ViewPagerFragment();
    return fragment;
}

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_view_pager, container, false);
    CustomAdapter adapter = new CustomAdapter(getChildFragmentManager()); //getChildFragmentManager
    viewPager = (ViewPager) view.findViewById(R.id.viewpager);
    viewPager.setAdapter(adapter);
    return view;
}


public class CustomAdapter extends FragmentPagerAdapter {


    public CustomAdapter(FragmentManager fm){
        super(fm);

    }

    //position tells the program what fragment we are currently on/displaying
    public Fragment getItem(int position){
        switch (position){ //notice we don't use breaks on each case, due to the return statement on each.
            case 0:return CountriesFragment.newInstance();
            case 1: return FavoriteFragment.newInstance();
            default: return FavoriteFragment.newInstance();
        }
    }

    public  int getCount(){
        return 2;
    }

}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}
}

在这种情况下,如何完成传递信息?

1 个答案:

答案 0 :(得分:0)

OnCreateView()之前调用

OnActivityCreate(),这就是您的发件人为空的原因。此外,您必须避免在OnCreateView()中设置或创建任何对象。你的片段应该是这样的

public class CountriesFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

ArrayList<RecycleViewItem> listCountries = new ArrayList<>();
String names[] = {"Thailand", "Venezuela", "Sweden"};
int images[] = {R.drawable.thailand, R.drawable.venezuela, R.drawable.sweden};
RecyclerView myRecyclerView;

InterfaceListItemClickListener sender;

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

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    sender = (InterfaceListItemClickListener) getActivity();
 myRecyclerView.setHasFixedSize(true);
    LinearLayoutManager myLayoutManager = new LinearLayoutManager(getActivity());
    myLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    ListsForFragments.populateCountriesList();
    if (ListsForFragments.countriesList.size() > 0 & myRecyclerView != null) {
        myRecyclerView.setAdapter(new MyAdapter(ListsForFragments.countriesList, sender));
    }
    myRecyclerView.setLayoutManager(myLayoutManager);
}

public static CountriesFragment newInstance(String param1, String param2) {
    CountriesFragment fragment = new CountriesFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
    initializeList();
}

public void initializeList(){
    listCountries.clear();
    for(int i = 0; i < names.length; i++){
        RecycleViewItem item = new RecycleViewItem();
        item.setCardName(names[i]);
        item.setImageResourceID(images[i]);
        item.setIsFav(0);
        item.setIsTurned(0);
        listCountries.add(item);
    }
}





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

    myRecyclerView = (RecyclerView) view.findViewById(R.id.recycleView);

    return view;
}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

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