Reputation: 331
I made a CustomAdapter extending ArrayAdapter. I tried to use a setOnClickListener inside it because setItemOnClickListener doesn't work for me. Here is my get Custom adapter code :
public class ChatRoomAdapter extends ArrayAdapter<ChatRoom> {
Context context;
ChatRoom chatRoom;
public ChatRoomAdapter(Context context, ArrayList<ChatRoom> chatRoomArrayList){
super(context,0,chatRoomArrayList);
this.context = context;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView= LayoutInflater.from(context).inflate(R.layout.chat_room_model,parent,false);
chatRoom = getItem(position);
System.out.println(chatRoom.chatRoomId);
final TextView chatroomName = (TextView)convertView.findViewById(R.id.chatroom_name);
final TextView chatroomMessage = (TextView)convertView.findViewById(R.id.chatroom_message);
chatroomMessage.setText(Splash_Screen.localDatabase.getLatestChatMessage(chatRoom.chatRoomId).message);
LinearLayout chatroomLayout = (LinearLayout)convertView.findViewById(R.id.chatroom);
chatroomLayout.setOnClickListener(openChat);
chatroomName.setText(chatRoom.chatRoomName);
return convertView;
}
private View.OnClickListener openChat = new View.OnClickListener() {
@Override
public void onClick(View v) {
Bundle bundle = new Bundle();
bundle.putString("chatroom_id",chatRoom.chatRoomId);
FragmentTransaction fragmentTransaction = ((FragmentActivity)getContext()).getSupportFragmentManager().beginTransaction();
ChatFragment chatFragment = new ChatFragment();
chatFragment.setArguments(bundle);
fragmentTransaction.replace(R.id.view_container,chatFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
};
when I clicked on the first item, it returns me the second Item object. What might be the problem? thanks.
Upvotes: 0
Views: 74
Reputation: 1924
It looks like separating your Click Listener is the problem. Try moving your onClick()
to the inside of your getView()
so that you're not getting old values of your member variables:
@Override
public View getView(int position, View convertView, ViewGroup parent){
final ChatRoom chatRoom = getItem(position);
chatroomLayout.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
// You should have the accurate position here now
// so you can perform actions on the correct chatroom
}
});
// The rest of your code ...
}
Upvotes: 1