How to extract the text from the selected item on the listView

后端 未结 14 2546
轻奢々
轻奢々 2020-11-28 07:55

I have a listview with some items. I would like to get the text from the selected item.

Here is my list adapter and the onItemClickListener:

ListView         


        
14条回答
  •  借酒劲吻你
    2020-11-28 08:37

    Here's for future reference for anyone that stumbles on this. In my case I had a custom adapter class, with type as a POJO class I had. Also the items I wanted to pass to the adapter and display in my ListView where of the util.List class.

    I successfully passed the data to the ListView, but also wanted to get the text of the currently selected.

    Eg: the data I passed was a list of schools that a lecturer taught at, so he had to select the particular school he wanted to work with at that time, and on logging in I wanted to pass an intent to a new Activity with the current school the lecturer had selected.

    Thus my ListView onClick():

    private void loginSuccess() {
        progressDialog.dismiss();
        if (mySchoolsList.size() > 1) {
            schoolsListView = new ListView(MainActivity.this);
            schoolsArrayAdapter = new SchoolListAdapter(MainActivity.this, android.R.layout.simple_list_item_1, mySchoolsList);
            schoolsListView.setAdapter(schoolsArrayAdapter);
    
            dialog = new Dialog(MainActivity.this);
            dialog.setContentView(schoolsListView);
            dialog.setTitle("Welcome " + staff.getFullName());
            dialog.show();
    
    
            schoolsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView parent, View view, int position, long id) {
                    //the .getName() is accessed from the School POJO class.
                    String schoolName = schoolsArrayAdapter.getItem(position).getName();
                    intent = new Intent(MainActivity.this, NavMainActivity.class);
                    intent.putExtra("sentIntent", schoolName);
                    startActivity(intent);
                }
            });
    
        } else {
            intent = new Intent(MainActivity.this, NavMainActivity.class);
            intent.putExtra("sentIntent", recieveName);
            startActivity(intent);
        }
    }
    

    Hope this saves someone someday, because all the solutions here didn't work for me. Cheers!

提交回复
热议问题