android onClickListener有一个bug

时间:2014-10-21 20:12:47

标签: android android-listview onitemclicklistener

我尝试实现onItemClickListener,附加的是我的代码和xml文件。根据我的理解,当我点击任何textview时,我应该给我一个唯一的ID;但这里只返回0。不确定为什么,提前感谢解决方案。

我的主要活动:

public class MainActivity extends ListActivity implements OnItemClickListener   {
public static final String number = "number" ;
public static final String email ="email" ;
public static final String name ="name";
ArrayList<HashMap<String, String>> userList = new ArrayList<HashMap<String,String>>();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
for (int i=0 ;i <=5;i++){
    HashMap<String, String> map = new HashMap<String, String>();
    map.put(number, i+"");
    map.put(email, i+"email");
    map.put(name,i+"name");

    userList.add(map);  
}
settextView(userList);
final ListView lv = getListView();
lv.setTextFilterEnabled(false);
lv.setOnItemClickListener(this);
}

public void settextView(ArrayList<HashMap<String, String>> userList) 
{
 ListAdapter adapter = new SimpleAdapter(
            MainActivity.this, userList,
            R.layout.list_item, new String[] {number , email ,name  },
            new int[] { R.id.userName, R.id.ventDesc ,R.id.ventUserName});
    // updating listview
    setListAdapter(adapter);
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub

String numberPressed = ((TextView)findViewById(R.id.userName)).getText().toString();
Toast.makeText(MainActivity.this, "CLICK: " + numberPressed, Toast.LENGTH_SHORT).show();
Log.d("selected is ",numberPressed);

}
}

main xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="20sp" >
</TextView>

列出xml:

   <?xml version="1.0" encoding="utf-8"?>
   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical" >

    <TextView
    android:id="@+id/userName"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"

     />
<!-- Name Label -->

    <TextView
    android:id="@+id/ventUserName"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

 <TextView
    android:id="@+id/ventDesc"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="6dip"
    android:paddingTop="6dip"
    android:textSize="17dip"
    android:textStyle="bold" />

    </LinearLayout>

PS:我确实尝试调试代码,老实说似乎没有什么能帮助我

1 个答案:

答案 0 :(得分:0)

更改字符串numberPressed =((TextView)findViewById(R.id.userName))。getText()。toString(); to String numberPressed =((TextView)view.findViewById(R.id.userName))。getText()。toString();