How can we get the value of the selected row in listview?

To retrieve the value of the selected row in a ListView, you can use the OnItemClickListener listener to handle this. The specific steps are as follows:

  1. First, set an OnItemClickListener listener for the ListView.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // 处理选中行的操作
    }
});
  1. Get the value of the selected row in the onItemClick method.
String selectedValue = (String) parent.getItemAtPosition(position);

Assuming the data in the ListView is of type String. If the data is of a different type, it will need to be converted accordingly.

The complete example code is as follows:

ListView listView = findViewById(R.id.listView);
String[] data = {"Item 1", "Item 2", "Item 3"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, data);
listView.setAdapter(adapter);

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String selectedValue = (String) parent.getItemAtPosition(position);
        Toast.makeText(MainActivity.this, selectedValue, Toast.LENGTH_SHORT).show();
    }
});

In the code above, the value corresponding to the selected row’s position is obtained and displayed using Toast. You can further process the value of the selected row based on your actual needs.

bannerAds