How to return the id of selected item of listview

浪尽此生 提交于 2019-12-14 04:10:35

问题


Hello friends i am new to android and i am learning about android programming. I am working with my friends. I have web service from which i am showing list of cities in listview now my friend give me task that is when i will click on city then id of that city return me so i don't how to do so please anybody can help me to do so.

public class CityNameActivity extends ListActivity{
private TextView displayText;
ListView list;



private ProgressDialog pDialog;
// URL to get Cities JSON
private static String url = "http://14.140.200.186/Hospital/get_city.php";
// JSON Node names
private static final String TAG_CITIES = "Cities";
private static final String TAG_ID = "city_id";
private static final String TAG_NAME = "city_name";
// Cities JSONArray
JSONArray Cities = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> citylist;

//ArrayList<String> citylist;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.cityname_activity_main);

    ListView listView=getListView();

    citylist = new ArrayList<HashMap<String, String>>();

          new GetCities().execute();
}



/**
 * Async task class to get json by making HTTP call
 * */
private class GetCities extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Showing progress dialog
        pDialog = new ProgressDialog(CityNameActivity.this);
        pDialog.setMessage("Please wait...");
        pDialog.setCancelable(false);
        pDialog.show();

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Creating service handler class instance
        ServiceHandler sh = new ServiceHandler();

        // Making a request to url and getting response
        String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

        Log.d("Response: ", "> " + jsonStr);

        if (jsonStr != null) {
            try {
                JSONObject jsonObj = new JSONObject(jsonStr);

                // Getting JSON Array node
                Cities = jsonObj.getJSONArray(TAG_CITIES);

                // looping through All Cities
                for (int i = 0; i < Cities.length(); i++) {
                    JSONObject c = Cities.getJSONObject(i);

                    String id = c.getString(TAG_ID);
                    String name = c.getString(TAG_NAME);
                    HashMap<String, String> Cities = new HashMap<String, String>();

                    Cities.put(TAG_ID, id);

                    Cities.put(TAG_NAME, name);



                    // adding contact to Cities list
                    citylist.add(Cities);


                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Log.e("ServiceHandler", "Couldn't get any data from the url");
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result)
    {
        super.onPostExecute(result);
        // Dismiss the progress dialog
        if (pDialog.isShowing())
            pDialog.dismiss();
        /**`enter code here`
         * Updating parsed JSON data into ListView
         * */
        final ListAdapter adapter = new SimpleAdapter(CityNameActivity.this, citylist, R.layout.city_list_item, new String[] { TAG_NAME}, new int[] { R.id.name});
        setListAdapter(adapter);





    }
}}

cityname_mai_activity.xml

    <ListView
    android:id="@android:id/list"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView4" />
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Select City"
    android:id="@+id/textView4"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:textSize="25dp"/>

city_list_item:

<TextView
    android:id="@+id/name"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="2dip"
    android:paddingTop="6dip"
    android:textSize="16sp"
    android:textStyle="bold" />


回答1:


You have to use the Spinner like these below:

    Spinner spin = (Spinner) findViewById(R.id.spinner);  


    spin.setOnItemSelectedListener(this);

    ArrayAdapter aa = new ArrayAdapter(this,R.layout.spinner_item,ARRAYLIST_DATA_HERE);  
    aa.setDropDownViewResource(R.layout.spinner_item); 

    //Setting the ArrayAdapter data on the Spinner  
    spin.setAdapter(aa); 

    spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {

               String items=spinner.getSelectedItem().toString();
               Log.i("Selected item : ",items);
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }

    });
    return true;

Use the spinner_item xml

xmlns:android="http://schemas.android.com/apk/res/android"
    style="?android:attr/spinnerDropDownItemStyle"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#BAB7BA"
    android:ellipsize="start"
    android:gravity="left"
    android:padding="10dip"
    android:textColor="@color/white" />



回答2:


Did you check On Click Listener for your ListView ?? I think that will solve your problem.. Use onClikcListener's on ItemClick event which will give you position and based on that position you can get item from your Arraylist which will give you id from that..



来源:https://stackoverflow.com/questions/35721219/how-to-return-the-id-of-selected-item-of-listview

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!