Spinner with list view

2019-09-01 08:32发布

问题:

I would like to ask, I'm working with spinner. I've a list view and a spinner. in my spinner I declare "month", "june","july","august","sept","oct","nov","dec"

In the list view, originally, it is empty. When I click on "August" , it will show that data of August(august.java) in the list view, May I know is there any way to do it?

Because right now , I'm doing via class.. Meaning, when I onclick Aug, it will open up new intent. But I wanted to merge it into one class, so that when I click "August", it will change in the list view and not open up new intent. Is there a way to do it?

This is my code

String [] months = {
                "June",
                "July",
                "August",
                "Septemeber",
                "November",
                "December",

part of my date.java

//SpinnerView
            s1 = (Spinner) findViewById(R.id.spinner1);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, months);
        s1.setAdapter(adapter);
        s1.setOnItemSelectedListener(new OnItemSelectedListener()
        {
            public void onItemSelected(AdapterView<?> arg0,View arg1, int arg2, long arg3) {
                int index = s1.getSelectedItemPosition();
                //Toast.makeText(getBaseContext(), "You have seleted item :" + months[index] , Toast.LENGTH_SHORT).show();
            }
            public void onNothingSelected(AdapterView<?>arg0) {}
            });


    if ( s1.equals("August")) {

        startActivity(new Intent(date.this,MainActivity.class));
    }
    else{
        startActivity(new Intent(date.this,august
                .class));

    } 

data code that I'm getting. august.java

public class august extends ListActivity {

    String URL = "http://api.eventful.com/rest/events/search?app_key=42t54cX7RbrDFczc&location=singapore&page_size=20&date=august";

    // XML node keys
    static final String KEY_EVENT = "event"; // parent node
    static final String KEY_TITLE = "title";
    static final String KEY_URL = "url";
    static final String KEY_DESC = "description";
    static final String KEY_START_TIME = "start_time";
    static final String KEY_STOP_TIME = "stop_time";
    static final String KEY_TIME = "combine_time";
    static final String KEY_VENUE_NAME = "venue_name";
    static final String KEY_COUNTRY_NAME = "country_name";
    static final String KEY_VENUE_ADDRESS = "venue_address";
    static final String KEY_VENUE = "venue";
    static final String KEY_LATITUDE = "latitude";
    static final String KEY_LONGITUDE = "longitude";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.date);

        final ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

        XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl(URL); // getting XML
        Document doc = parser.getDomElement(xml); // getting DOM element

        NodeList nl = doc.getElementsByTagName(KEY_EVENT);
        // looping through all item nodes <item>
        for (int i = 0; i < nl.getLength(); i++) {
            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();
            Element e = (Element) nl.item(i);
            // adding each child node to HashMap key => value
            map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
            map.put(KEY_URL, parser.getValue(e, KEY_URL));

            map.put(KEY_DESC, "Description: " + parser.getValue(e, KEY_DESC));
            map.put(KEY_START_TIME, parser.getValue(e, KEY_START_TIME));
            map.put(KEY_STOP_TIME, parser.getValue(e, KEY_STOP_TIME));
            if (parser.getValue(e, KEY_STOP_TIME) != "") {
                map.put(KEY_TIME, parser.getValue(e, KEY_START_TIME) + "-"
                        + parser.getValue(e, KEY_STOP_TIME));
            } else {
                map.put(KEY_TIME, parser.getValue(e, KEY_START_TIME));
            }
            map.put(KEY_VENUE_NAME, parser.getValue(e, KEY_VENUE_NAME));
            map.put(KEY_COUNTRY_NAME, parser.getValue(e, KEY_COUNTRY_NAME));
            map.put(KEY_VENUE_ADDRESS, parser.getValue(e, KEY_VENUE_ADDRESS));
            map.put(KEY_LATITUDE, parser.getValue(e, KEY_LATITUDE));
            map.put(KEY_LONGITUDE, parser.getValue(e, KEY_LONGITUDE));
            map.put(KEY_VENUE, parser.getValue(e, KEY_VENUE_NAME) + ", "
                    + parser.getValue(e, KEY_VENUE_ADDRESS));

            // adding HashList to ArrayList

            menuItems.add(map);

        }

        // Adding menuItems to ListView

        ListAdapter adapter = new SimpleAdapter(this, menuItems,
                R.layout.list_item, new String[] { KEY_TITLE, KEY_DESC,
                        KEY_COUNTRY_NAME, KEY_VENUE, KEY_LATITUDE,
                        KEY_LONGITUDE, KEY_TIME, }, new int[] { R.id.title,
                        R.id.description, R.id.countryName, R.id.venueName,
                        R.id.lat, R.id.lng, R.id.startTime });

        setListAdapter(adapter);

        // selecting single ListView item
        ListView lv = getListView();

        lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
                String title = ((TextView) view.findViewById(R.id.title))
                        .getText().toString();
                String description = ((TextView) view
                        .findViewById(R.id.description)).getText().toString();

                String venue = ((TextView) view.findViewById(R.id.venueName))
                        .getText().toString();
                String lat = ((TextView) view.findViewById(R.id.lat)).getText()
                        .toString();

                String lng = ((TextView) view.findViewById(R.id.lng)).getText()
                        .toString();

                // Starting new intent
                Intent in = new Intent(getApplicationContext(),
                        SingleMenuItemActivity.class);
                in.putExtra(KEY_TITLE, title);
                in.putExtra(KEY_DESC, description);
                in.putExtra(KEY_VENUE, venue);
                in.putExtra(KEY_LATITUDE, lat);
                in.putExtra(KEY_LONGITUDE, lng);
                startActivity(in);

            }
        });


    }

}

回答1:

Use following code i have tried it is working fine

 import java.util.ArrayList;
    import java.util.List;

    import android.app.Activity;
    import android.os.Bundle;
    import android.view.Menu;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.Spinner;
    import android.widget.Toast;
    import android.widget.AdapterView.OnItemSelectedListener;

    public class MainActivity extends Activity implements OnItemSelectedListener {
        private Spinner sp;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            uI();
            spElements();

        }

        public void uI() {
            sp = (Spinner) findViewById(R.id.mydsp);
            sp.setOnItemSelectedListener(this);
        }

        public void spElements() {
            List<String> months = new ArrayList<String>();
            months.add("June");
            months.add("July");
            months.add("August");
            months.add("September");
            months.add("October");
            months.add("November");
            months.add("December");

            // Creating adapter for spinner
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, months);

            // Drop down layout style - list view with radio button
            dataAdapter
                    .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

            // attaching data adapter to spinner
            sp.setAdapter(dataAdapter);
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {

            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }

        @Override
        public void onItemSelected(AdapterView<?> main, View view, int position,
                long Id) {

            String item = main.getItemAtPosition(position).toString();

  int index = item.getSelectedItemPosition();
            Toast.makeText(main.getContext(), "You selected Month is: " + item,
                    Toast.LENGTH_LONG).show();

        }

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

        }

    }


回答2:

Showing custom data in your ListView is actually not very complicated. There are several steps involved.

What to show This is quite easy. When a user selects an item from your spinner, you know what to show; the month he selected. Now, as your months are actual classes, I would recommend you implement a variable that lets you know what is selected. That variable will be used by other classes to actually show the content.

How to show Here is where it gets more tricky. Your ListView will show a list. The items contained in the list need to be set by you. You need to define what data from your month class you will actually want to show. And here is where your design falls a bit short. The items you would want to show would ideally need to be homogeneous. So it would be easier to visualise a list of month objects then of several different items from one month. What I propose is that you switch your implementation from ListView to a simple TextView inside a ScrollView.

Show the data With the above modification, every time a selection is made, visualise it. Now here is where you can apply a little trick. Simply implement a toString() method in your object that will return, as a String what you want to show to the user. That way you can control what a user sees and leave the responsibility of what to show with the month object which is generally a good design choice.

I hope you will consider this new design. I believe you erred in trying to use ListView, ArrayAdapter, and the ViewHolder pattern when it wasn't necessary. Also, you will need to pre-load all month objects or use, as David says, an AsyncTask to retrieve the data. Never block your UI thread with network operations. Not only is it a bad practice, newer versions of Android will throw an exception.



回答3:

Try this:

When any Month is selected then try to set adapter for Listview. like this:

s1.setOnItemSelectedListener(new OnItemSelectedListener()
        {
            public void onItemSelected(AdapterView<?> arg0,View arg1, int arg2, long arg3) {
                int index = s1.getSelectedItemPosition();
                if(index>0)
                {
                             String Month = MonthArray[index];

                         // get data as per your month here.
                        //set your adapter for listview here according to your month data.


                }
            }
            public void onNothingSelected(AdapterView<?>arg0) {}
        });

If you want to load data from server and then want to change the adapter then i would suggest that you use AsyncTask for loading data. and on completion of data load set adapter of Listview.

Hope it Helps!!



回答4:

Here is one example for you

 spinner.setOnItemSelectedListener(new OnItemSelectedListener() 
                {
                    @Override
                    public void onItemSelected(AdapterView<?> arg0, View arg1,
                            int arg2, long arg3) 
                    {
                        String A = arg0.getSelectedItem().toString();
                        new abc(Context, A).excute();


                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> arg0) 
                    {
                    }
                });

    private class abc extends AsyncTask<Void, Void, HashMap<String, String>> 
    {
        ProgressDialog pd;
        HashMap<String, String> map;
        String Month;

        abc(Context context, String a)
                {
            pd = new ProgressDialog(context);
            map = new HashMap<String, String>();
Month = a;
                } 
        protected void onPreExecute() 
        {
            pd.setTitle("Please Wait...");
            pd.setMessage("Saving...");
            pd.setCancelable(false);
            pd.show();
        } 
        protected void onPostExecute(HashMap<String, String> result)
        {
            // Get value from map and sent it to your adapter class where you can set value to textview in your listview

            String title = result.get(KEY_TITLE);

             ListAdapter adapter = new SimpleAdapter(this, menuItems,
                        R.layout.list_item, new String[] { KEY_TITLE, KEY_DESC,
                                KEY_COUNTRY_NAME, KEY_VENUE, KEY_LATITUDE,
                                KEY_LONGITUDE, KEY_TIME, }, new int[] { R.id.title,
                                R.id.description, R.id.countryName, R.id.venueName,
                                R.id.lat, R.id.lng, R.id.startTime });

                setListAdapter(adapter);

                // selecting single ListView item
                ListView lv = getListView();
            if(pd.isShowing()) pd.dismiss();
        } 

        @Override
        protected HashMap<String , String> doInBackground(Void... params) 
        {
             XMLParser parser = new XMLParser();
                String xml = parser.getXmlFromUrl(URL); // getting XML
                Document doc = parser.getDomElement(xml); // getting DOM element

                NodeList nl = doc.getElementsByTagName(KEY_EVENT);
                // looping through all item nodes <item>
                for (int i = 0; i < nl.getLength(); i++) {
                    // creating new HashMap
                    Element e = (Element) nl.item(i);
                    // adding each child node to HashMap key => value
                    map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
                    map.put(KEY_URL, parser.getValue(e, KEY_URL));

                    map.put(KEY_DESC, "Description: " + parser.getValue(e, KEY_DESC));
                    map.put(KEY_START_TIME, parser.getValue(e, KEY_START_TIME));
                    map.put(KEY_STOP_TIME, parser.getValue(e, KEY_STOP_TIME));
                    if (parser.getValue(e, KEY_STOP_TIME) != "") {
                        map.put(KEY_TIME, parser.getValue(e, KEY_START_TIME) + "-"
                                + parser.getValue(e, KEY_STOP_TIME));
                    } else {
                        map.put(KEY_TIME, parser.getValue(e, KEY_START_TIME));
                    }
                    map.put(KEY_VENUE_NAME, parser.getValue(e, KEY_VENUE_NAME));
                    map.put(KEY_COUNTRY_NAME, parser.getValue(e, KEY_COUNTRY_NAME));
                    map.put(KEY_VENUE_ADDRESS, parser.getValue(e, KEY_VENUE_ADDRESS));
                    map.put(KEY_LATITUDE, parser.getValue(e, KEY_LATITUDE));
                    map.put(KEY_LONGITUDE, parser.getValue(e, KEY_LONGITUDE));
                    map.put(KEY_VENUE, parser.getValue(e, KEY_VENUE_NAME) + ", "
                            + parser.getValue(e, KEY_VENUE_ADDRESS));

                    // adding HashList to ArrayList

                    menuItems.add(map); 
                    }
                return map;
        }
    }

Hope it helps you.