android recyclerView Adapter错误。单击RecyclerView项时,应用程序将停止工作。我想在单击任何项目时进行其他活动,当我使用Toast时,它工作正常,但是如果添加Intent,则它将停止工作。
这是我的界面:
public interface OnItemClickListener {
void onClick(View view, int position);
}
这是我的回收站适配器校准:
public class RecAdapter extends RecyclerView.Adapter<RecAdapter.MyViewHolder> {
private List<Items> items;
private Context context;
public RecAdapter(List<Items> items, Context context )
{
this.items = items;
this.context = context;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item,parent,false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.countryname.setText(items.get(position).getCountryname());
holder.rank.setText(items.get(position).getRank());
Picasso.with(context)
.load(items.get(position).getFlag())
.into(holder.flag);
holder.setClickListener(new OnItemClickListener() {
@Override
public void onClick(View view, int position) {
Intent intent = new Intent(context , Main2Activity.class);
context.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return items.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView countryname, rank;
ImageView flag;
private OnItemClickListener clickListener;
public MyViewHolder(View itemView) {
super(itemView);
countryname = (TextView) itemView.findViewById(R.id.capital);
rank = (TextView) itemView.findViewById(R.id.rank);
flag = (ImageView) itemView.findViewById(R.id.flag);
itemView.setTag(itemView);
itemView.setOnClickListener(this);
}
public void setClickListener(OnItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
@Override
public void onClick(View view) {
if (clickListener != null) clickListener.onClick(view, getAdapterPosition());
}
}
}
答案 0 :(得分:0)
您不能直接单击一个持有人.....为视图提供一个ID,然后重新编写如下代码:
holder.(someitem).setClickListener(new OnItemClickListener() {//you need a view to execute the onclicklistener
@Override
public void onClick(View view, int position) {
Intent intent = new Intent(context , Main2Activity.class);
context.startActivity(intent);
}
});
答案 1 :(得分:0)
从另一个问题中复制我的答案:
您已经知道RecyclerView
类中不再提供此方法。
我在onClick
中实现RecyclerView
事件的方法是这样的:
class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
interface OnClickListener {
void onClick(Item item);
}
private final List<Item> dataset;
private final OnClickListener l;
public MyAdapter(List<Item> data, OnClickListener listener) {
this.dataset = data;
this.l = listener;
}
@Override MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = //inflate layout
MyClick click = new MyClick() {
onClick(int position) {
if (l != null) {
l.onClick(dataset.get(position));
}
}
};
return new MyViewHolder(click, v);
}
static class MyViewHolder {
final MyClick l;
public MyViewHolder(MyClick listener, View view) {
super(view);
l = listener;
// inflate views
view.setOnClickListener(new OnClickListener() {
if (l != null) {
l.onClick(getAdapterPosition());
}
});
}
interface MyClick {
void onClick(int position);
}
}
}
class MyActivity extends AppCompatActivity {
@Override void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set layout
MyAdapter adapter = new MyAdapter(getData(), new OnClickListener() {
@Override onClick(Item item) {
// do stuff with item
}
});
}
}
答案 2 :(得分:0)
添加点击侦听器,如下所示:-
View itemView;
Context context;
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_view, parent, false);
this.context=parent.getContext();
return new ViewHolder(itemView);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context , Main2Activity.class);
context.startActivity(intent);
}
});
}
答案 3 :(得分:0)
以下是我为回收站项目点击
创建的点击监听器的代码使用此方法,您将获得两种点击类型
这是RecyclerItemClickListener.java文件
public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
public interface OnItemClickListener
{
void onItemClick(View view, int position);
void onItemLongClick(View view, int position);
}
private OnItemClickListener mListener;
private GestureDetector mGestureDetector;
public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, OnItemClickListener listener)
{
mListener = listener;
mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener()
{
@Override
public boolean onSingleTapUp(MotionEvent e)
{
return true;
}
@Override
public void onLongPress(MotionEvent e)
{
View childView = recyclerView.findChildViewUnder(e.getX(), e.getY());
if(childView != null && mListener != null)
{
mListener.onItemLongClick(childView, recyclerView.getChildPosition(childView));
}
}
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e)
{
View childView = view.findChildViewUnder(e.getX(), e.getY());
if(childView != null && mListener != null && mGestureDetector.onTouchEvent(e))
{
mListener.onItemClick(childView, view.getChildPosition(childView));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView view, MotionEvent motionEvent){}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
如何在“活动和片段”中使用
rvcyclerView.addOnItemTouchListener(new RecyclerItemClickListener(context, rvcyclerView,
new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
//do you what you want tot do simple click
}
@Override
public void onItemLongClick(View view, int position) {
//do you what you want tot do on long click
}
}));
答案 4 :(得分:0)
class SessionManager: NSObject, MCSessionDelegate, MCBrowserViewControllerDelegate, MCNearbyServiceAdvertiserDelegate, MCNearbyServiceBrowserDelegate {
func browser(_ browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String: String] ? ) {
browser.invitePeer(peerID, to: mcSession, withContext: nil, timeout: 10)
}
func browser(_ browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) {
print("Lost Peer")
}
static
let shared = SessionManager()
var peerID = MCPeerID(displayName: UIDevice.current.name)
var mcSession: MCSession!
var mcAdvertiserAssistant: MCAdvertiserAssistant!
var delegate: SessionDelegate!
var serviceBrowser: MCNearbyServiceBrowser
var serviceAdvertiser: MCNearbyServiceAdvertiser
override init() {
serviceBrowser = MCNearbyServiceBrowser(peer: peerID, serviceType: "demo")
serviceAdvertiser = MCNearbyServiceAdvertiser(peer: peerID, discoveryInfo: nil, serviceType: "demo")
super.init()
peerID = MCPeerID(displayName: UIDevice.current.name)
mcSession = MCSession(peer: peerID, securityIdentity: nil, encryptionPreference: .required)
mcSession.delegate = self
serviceBrowser.delegate = self
serviceBrowser.startBrowsingForPeers()
serviceAdvertiser.delegate = self
serviceAdvertiser.startAdvertisingPeer()
}
//MARK: Start Hosting
func startHosting() {
mcAdvertiserAssistant = MCAdvertiserAssistant(serviceType: "demo", discoveryInfo: nil, session: mcSession)
mcAdvertiserAssistant.start()
}
//MARK: Join Session
func joinSession() {
let mcBrowser = MCBrowserViewController(serviceType: "demo", session: mcSession)
mcBrowser.delegate = self
mcBrowser.navigationController ? .navigationBar.backgroundColor = .black
UINavigationBar.appearance().tintColor = .black
UIApplication.visibleViewController.present(mcBrowser, animated: true)
}
//MARK: Delegate Methods
func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) {}
func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) {}
func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL ? , withError error : Error ? ) {}
func browserViewControllerDidFinish(_ browserViewController: MCBrowserViewController) {
UIApplication.visibleViewController.dismiss(animated: true, completion: nil)
}
func browserViewControllerWasCancelled(_ browserViewController: MCBrowserViewController) {
UIApplication.visibleViewController.dismiss(animated: true, completion: nil)
}
func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {
switch state {
case MCSessionState.connected:
print("Connected:SessionManager \(peerID.displayName)")
case MCSessionState.connecting:
print("Connecting:SessionManager \(peerID.displayName)")
case MCSessionState.notConnected:
print("Not Connected:SessionManager \(peerID.displayName)")
}
}
func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
let sessionData = SessionModel.init(session, peerID, data)
delegate.didRecieveSessionData(sessionData)
}
func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: Data ? , invitationHandler : @escaping(Bool, MCSession ? ) - > Void) {
print("Receive Invitation")
invitationHandler(true, self.mcSession)
}
func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didNotStartAdvertisingPeer error: Error) {
print("Ddn't Start")
}
}
在您的活动/片段上实现OnItemClickListener
public class RecAdapter extends RecyclerView.Adapter<RecAdapter.MyViewHolder> implements View.OnClickListener {
private List<Items> items;
private Context context;
private OnItemClickListener clickListener;
public RecAdapter(List<Items> items, Context context )
{
this.items = items;
this.context = context;
}
public void setClickListener(OnItemClickListener itemClickListener) {
this.clickListener = itemClickListener;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_item,parent,false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
holder.countryname.setText(items.get(position).getCountryname());
holder.rank.setText(items.get(position).getRank());
Picasso.with(context)
.load(items.get(position).getFlag())
.into(holder.flag);
holder.flag.setOnClickListener(this);
}
@Override
public int getItemCount() {
return items.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView countryname, rank;
ImageView flag;
public MyViewHolder(View itemView) {
super(itemView);
countryname = (TextView) itemView.findViewById(R.id.capital);
rank = (TextView) itemView.findViewById(R.id.rank);
flag = (ImageView) itemView.findViewById(R.id.flag);
}
@Override
public void onClick(View view) {
if (clickListener != null) clickListener.onClick(view, getAdapterPosition());
}
}
}
}