Search code examples
androidlistviewviewviewgroup

Managing a list item of ListView


I created a custom ListView. Each item in the list have one imageView and two TextView.

The code is:

public class PersonalList extends ListActivity{

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String[] name= new String[] { "Mary", "Frank",
            "John" };
    String[] surname = new String[] { "Ballak", "Doe",
            "Strip"" };
    setContentView(R.layout.member_list);

    MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this, name, surname);
    setListAdapter(adapter);
}

 protected void onListItemClick(ListView l, View v, int position, long id) {
    String name = (String) getListAdapter().getItem(position);
    Toast.makeText(this, "selected item: "+name, Toast.LENGTH_LONG).show();     
  }

 }

where MySimpleArrayAdapter is:

public class MySimpleArrayAdapter extends ArrayAdapter<String> {
      private final Context context;
      private final String[] name;
      private final String[] surname;

      public MySimpleArrayAdapter(Context context, String[] name, String[] surname)
      {
          super(context, R.layout.list_row, name);
          this.context = context;
          this.name= name;
          this.surname = surname;
      }

      @Override
      public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView = inflater.inflate(R.layout.rowlayout, parent, false);
        TextView nameView= (TextView) rowView.findViewById(R.id.label);
        TextView surnameView= (TextView) rowView.findViewById(R.id.label1);
        ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
        nameView.setText(name[position]);
        surnameView.setText(surname[position]);

        return rowView;
      }
  } 

Calling the following code from onListItemClick:

  Toast.makeText(this, "selected item: "+name, Toast.LENGTH_LONG).show();

I obtain for the first item a message in toast like this:

  "selected item: Mary"

What can I do in order to obtain the following result?

  "selected item: Mary Ballak"

Solution

  • This will get you first & last names:

     protected void onListItemClick(ListView l, View v, int position, long id) {
        String name = (String) getListAdapter().getItem(position);
        Toast.makeText(this, "selected item: " + ((TextView) v.findViewById(R.id.label)).getText().toString() + " " + ((TextView) v.findViewById(R.id.label1)).getText().toString(), Toast.LENGTH_LONG).show();     
      }
    

    In addition - you can get the index from the onItemClick and get the String from the arrays (name/surname) - if you'll save the array as members of your Activity

    Something like: String text = mName[position] + " " + msurName[position];