我试图从ArrayAdapter的单击行中获取TextView的值。 我有两个问题: 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);
}
}
答案 0 :(得分:3)
1 - 在列表对象上使用监听器
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
}
});
2位将为您提供list_view中单击的项目位置
答案 1 :(得分:0)
在列表中使用itemclicklistener。 如果你在代码中提到的那样将字符串传递给arrayadapter那么它就是。
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();
}
});
如果您在arrayadapter中传递数组列表,如
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();
}
});
答案 2 :(得分:0)
对列表视图使用setOnItemSelectedListener()
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
}
}