0

我创建了一个自定义 ListView。列表中的每一项都有一个 imageView 和两个 TextView。

代码是:

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

 }

其中 MySimpleArrayAdapter 是:

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

从以下代码调用onListItemClick

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

我为第一项获得了这样的敬酒消息:

  "selected item: Mary"

我该怎么做才能获得以下结果?

  "selected item: Mary Ballak"
4

1 回答 1

3

这将为您提供名字和姓氏:

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

此外-您可以从数组中获取索引onItemClick并从数组(姓名/姓氏)中获取字符串-如果您将数组保存为您的成员Activity

就像是:String text = mName[position] + " " + msurName[position];

于 2012-10-21T16:10:15.927 回答