获取列表的项目位置和字符串(Android)

时间:2016-05-18 19:02:49

标签: java android string listview onclick

单击时,我需要在ListView中获取项目的位置和字符串。到现在为止,它只给我一个位置,但不是字符串。我需要帮助获取相同位置的字符串

这是我的代码

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();
    }
}

这就是我在我的列表中设置我的适配器的方法

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();
        }

    }
}

}

1 个答案:

答案 0 :(得分:0)

编辑:

通过尝试从ListView的布局声明中调用onClick方法,你做错了。您应该将onItemClickListener附加到Activity / Fragment类中的ListView。

首先,在Activity / Fragment类中实现OnItemClickListener接口。然后设置监听器:

lista.setOnItemClickListener(this);

在onItemClick方法中:

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
    String str = (String) adaptador.getItem(position);
}