如何从列表视图中的选定项目中获取值?

时间:2015-04-01 16:25:26

标签: android android-listview

到目前为止,这是我的代码。这是有效的,但它只显示我在listView中的第一个值,而不是用户选择的项目。请用这个来打扰我。这非常重要。

        unitListView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);

          unitListView.setOnItemClickListener(new   AdapterView.OnItemClickListener() {
              public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {

                  // selected item
                 TextView t1 = (TextView) findViewById(R.id.lblLUnitName);

                 String name=t1.getText().toString();

          //    String a= (String) unitListView.getItemAtPosition(position);

                       // touchpressed=position;
                    Toast.makeText(getApplicationContext(), "Selected Item :" +name, Toast.LENGTH_SHORT).show();

        }
    });

3 个答案:

答案 0 :(得分:0)

View只是为了在UI上显示一些值。如果您想获得真实值,请使用positionListAdapter获取值。

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    YourItemClass item = (YourItemClass)listAdapter.getItem(position);
    //[...]
}

其他方式是直接从ListAdapter获取unitListView

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Object item = unitListView.getAdapter().getItem(position);
    //[...]
}

答案 1 :(得分:0)

按如下方式更新您的代码并尝试;

      unitListView.setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
      unitListView.setOnItemClickListener(new   AdapterView.OnItemClickListener() {
          public void onItemClick(AdapterView<?> parent, View view,int position, long id) {

             TextView t1 = (TextView) findViewById(R.id.lblLUnitName);
             String name=String.valuesOf(position);
             Toast.makeText(getApplicationContext(), "Selected Item :" +name, Toast.LENGTH_SHORT).show();

    }
});

答案 2 :(得分:0)

替换
TextView t1 = (TextView) findViewById(R.id.lblLUnitName);

TextView t1 = (TextView) view.findViewById(R.id.lblLUnitName);