我正在尝试从ArrayAdapter的单击行中获取文本视图的值。我有两个问题:1.如何检测单击行?2.如何获得该行的vaule?
我正在使用此代码显示列表:
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity {
// List view
private ListView lv;
// Listview Adapter
ArrayAdapter<String> adapter;
// Search EditText
E ditText inputSearch;
// ArrayList for Listview
ArrayList<HashMap<String, String>> productList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Listview Data
String products[] = {"Dell Inspiron", "HTC One X", "HTC Wildfire S", "HTC Sense", "HTC Sensation XE",
"iPhone 4S", "Samsung Galaxy Note 800",
"Samsung Galaxy S3", "MacBook Air", "Mac Mini", "MacBook Pro"};
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
lv.setAdapter(adapter);
}
}
1-列表对象上的侦听器
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
}
});
2位置将为您提供单击的项目位置
在列表中使用itemClickListener。如果您在代码中提到的那样将字符串传递到阵列Adadapter,则将是。
mListView.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
String item=arg0.getItemAtPosition(arg2).toString();
}
});
如果您在数组中传递数组列表,例如
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
然后,您可以在该特定位置上获得该项目,如以下内容:
mListView.setOnItemClickListener(new OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
// TODO Auto-generated method stub
String item=arg0.getItemAtPosition(arg2).toString();
}
});
使用setOnitemSelectedListener()for listView
lv.setOnItemSelectedListener(new MyOnItemSelectedListener());
public class MyOnItemSelectedListener implements OnItemSelectedListener
{
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id)
{
//toast message
Toast.makeText(parent.getContext(), "Selected item: " + parent.getItemAtPosition(pos).toString(), Toast.LENGTH_SHORT).show();
String selected_item = parent.getItemAtPosition(pos).toString();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
}