[英]Get item position and string of a List (Android)
I need to get in a toast the position and the string of a item in a ListView when is clicked. 单击时,我需要举个例子,祝酒在ListView中的位置和项目的字符串。 Until now it only gives me the position, but not the string.
到现在为止,它只给我职位,而不给我字符串。 I need help getting the string of the same position
我需要帮助以获取相同位置的字符串
This is my code 这是我的代码
public void mandaOnClick(View v){
try {
View parentRow = (View) v.getParent();
lista = (ListView) parentRow.getParent();
final int position = lista.getPositionForView(parentRow);
//this is not working
final String item = (String) lista.getItemAtPosition(position);
//this is not working
String string = (String) lista.get(position);
Toast.makeText(getBaseContext(),"Your " + position + string + item, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getBaseContext(),"Nothing", Toast.LENGTH_SHORT).show();
}
}
This is how i set my adapter in my list 这是我在列表中设置适配器的方式
public class JsonTask extends AsyncTask<URL, Void, List<Animal>> {
@Override
protected List<Animal> doInBackground(URL... urls) {
List<Animal> contactos = null;
HttpURLConnection con = null;
try {
// Establecer la conexión
con = (HttpURLConnection) urls[0].openConnection();
con.setConnectTimeout(15000);
con.setReadTimeout(10000);
// Obtener el estado del recurso
int statusCode = con.getResponseCode();
if (statusCode != 200) {
contactos = new ArrayList<>();
contactos.add(new Animal(null, null, null, null));
} else {
// Parsear el flujo con formato JSON
InputStream in = new BufferedInputStream(con.getInputStream());
// JsonAnimalParser parser = new JsonAnimalParser();
GsonAnimalParser parser = new GsonAnimalParser();
contactos = parser.leerFlujoJson(in);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
con.disconnect();
}
return contactos;
}
@Override
protected void onPostExecute(final List<Animal> contactos) {
/*
Asignar los objetos de Json parseados al adaptador
*/
if (contactos != null) {
adaptador = new AdaptadorDeAnimales(getBaseContext(), contactos);
lista.setAdapter(adaptador);
} else {
Toast.makeText(
getBaseContext(),
"Error",
Toast.LENGTH_SHORT)
.show();
}
}
}
} }
You're doing it wrong by trying to call onClick method from your ListView's layout declaration. 您尝试从ListView的布局声明中调用onClick方法来做错了。 You should attach a onItemClickListener to your ListView in your Activity/Fragment class.
您应该将onItemClickListener附加到Activity / Fragment类中的ListView上。
First, implement the OnItemClickListener interface in your Activity/Fragment class. 首先,在Activity / Fragment类中实现OnItemClickListener接口。 Then set the listener:
然后设置监听器:
lista.setOnItemClickListener(this);
And in the onItemClick method: 并在onItemClick方法中:
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
String str = (String) adaptador.getItem(position);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.