CustomAdapter中的OnClickListener上的错误getItem()

时间:2017-06-24 05:04:26

标签: android listview onclicklistener

我制作了一个CustomAdapter扩展ArrayAdapter。我尝试在其中使用setOnClickListener,因为setItemOnClickListener对我不起作用。这是我的定制适配器代码:

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();
        }
    };

当我点击第一个项目时,它返回第二个Item对象。可能是什么问题?感谢。

1 个答案:

答案 0 :(得分:1)

看起来分离Click Listener就是问题所在。尝试将onClick()移到getView()的内部,这样您就不会获得成员变量的旧值:

@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 ...
}