管理ListView的列表项

时间:2012-10-21 16:05:46

标签: android listview view viewgroup

我创建了一个自定义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"

1 个答案:

答案 0 :(得分:3)

这会让你第一个&amp;姓氏:

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