您好我的片段中有recycleView
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list_petrole, container, false);
recyclerView = (RecyclerView)view.findViewById(R.id.recycle_view);
allPetroles = getArguments().getParcelableArrayList("petroles");
mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
mAdapter = new RecyclerAdapter(allPetroles, getActivity());
recyclerView.setAdapter(mAdapter);
return view;
}
在RecycleView适配器中,我在onBindViewHolder中设置了OnClickListener,所以我需要在点击一些raw后发送回Fragment一些信息(位置),然后进行一些更改(将此信息重新发送给Activity并在Gmaps上添加一些新视图) 这个onBindViewHolder:
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.linearClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
positionClick = position;
notifyDataSetChanged();
--------------I NEED CODE HERE----------------------
}
});
if (positionClick == position) {
holder.linearClick.setSelected(true);
}
else {
holder.linearClick.setSelected(false);
}
我不明白我该怎么做
答案 0 :(得分:0)
在RecyclerAdapter中:
1-添加内部接口:
/**********
*
* Inner interface
*
*/
public interface OnClickListener {
void onItemClicked(Item item);
}
2-在构造函数中添加一个参数:
public RecyclerAdapter(Context context, List<Item> data, OnClickListener onClickListener) {
mContext = context;
mData = data;
mListener = onClickListener
}
3-呼叫听众:
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
holder.linearClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//positionClick = position;
//you don't need this here : notifyDataSetChanged();
mListener.onItemClicked(mData.get(position));
}
});
if (positionClick == position) {
holder.linearClick.setSelected(true);
}
else {
holder.linearClick.setSelected(false);
}
你的片段应该实现RecyclerAdapter.OnClickListener
public class YourFragment extends Fragment implements RecyclerAdapter.OnClickListener {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_list_petrole, container, false);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
recyclerView = (RecyclerView)view.findViewById(R.id.recycle_view);
allPetroles = getArguments().getParcelableArrayList("petroles");
mLayoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(mLayoutManager);
mAdapter = new RecyclerAdapter(getActivity(), allPetroles, this);
recyclerView.setAdapter(mAdapter);
}
@Override
void onItemClicked(Item item) {
// TODO put your code here
}
}