화면을 중심으로 보지 마시고 채팅방 관리라는 데이터를 기준으로 보시면 문제해결이 명확해 집니다.
채팅방 목록을 관리하는 것이므로 채팅방을 리스트로 관리하도록 데이터를 설계하시면 됩니다.
public class ChatRoom {
private int roomId;
private String name;
private int numberOfPeople;
// 필요한 정보 추가,
// 생성자, Getter 추가
}
이제 List<ChatRoom> 형태의 데이터를 만드신 다음, 채팅방이 추가/변경/삭제 될 때 List<ChatRoom>을 업데이터 하신다음 어댑터에 제공하시면 됩니다. 어댑터에서는 클릭이벤트를 연결하시면 어떤 채팅방을 클릭했는지 알 수 있겠죠.
제가 리스트뷰는 써본지가 몇년이 넘어서 (리사이클러뷰만 사용 중) 대략적인 코드만 적습니다. 리스트뷰 사용 관련 문의가 있으시면 다른 분들한테 하시기 바랍니다.
public class MainActivity extends Activity {
private ListView listView;
private List<ChatRoom> chatRooms;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
// Create chat room objects
chatRooms = new ArrayList<>();
chatRooms.add(new ChatRoom(1, "Chat Room 1", 5));
chatRooms.add(new ChatRoom(2, "Chat Room 2", 3));
chatRooms.add(new ChatRoom(3, "Chat Room 3", 7));
// Add more chat rooms as needed
// Create the custom ArrayAdapter for ChatRoom objects
ArrayAdapter<ChatRoom> adapter = new ArrayAdapter<ChatRoom>(this,
R.layout.list_item_chat_room, R.id.textViewName, chatRooms) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.list_item_chat_room, parent, false);
}
ChatRoom chatRoom = getItem(position);
TextView textViewRoomId = convertView.findViewById(R.id.textViewRoomId);
TextView textViewName = convertView.findViewById(R.id.textViewName);
TextView textViewNumberOfPeople = convertView.findViewById(R.id.textViewNumberOfPeople);
textViewRoomId.setText("Room ID: " + chatRoom.getRoomId());
textViewName.setText("Name: " + chatRoom.getName());
textViewNumberOfPeople.setText("Number of People: " + chatRoom.getNumberOfPeople());
return convertView;
}
};
// Set the adapter on the ListView
listView.setAdapter(adapter);
// Set the item click listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ChatRoom selectedChatRoom = (ChatRoom) parent.getItemAtPosition(position);
Toast.makeText(MainActivity.this, "Clicked: " + selectedChatRoom.getName(), Toast.LENGTH_SHORT).show();
}
});
}
}