Is it possible to have a spinner and a list view on the same page?

前端 未结 2 549
醉酒成梦
醉酒成梦 2021-01-25 10:18

I want to have a spinner at the top of page, and then generate a list view below the spinner according to what the user has selected from the spinner, does anyone know a good tu

相关标签:
2条回答
  • 2021-01-25 10:35

    Yes it is possible. Create a layout containing spinner and listview. In the listactivtiy, use setContentView to create a view based on the layout. Get a handle on the spinner (findViewById) and do whatever you need to do with it. Based on the spinner selection - set the array or cursor for your listview adapter. That should be enough.

    0 讨论(0)
  • 2021-01-25 10:47

    A simple example using an ArrayAdapter over a string array for populating the spinner:

    // Create string array adapter to populate spinner
    ArrayAdapter<CharSequence> adapter = 
        ArrayAdapter.createFromResource(this, R.array.spinner_string_array,
            android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    
    // Set the spinners content adapter and add onSelect listener
    Spinner spinnerExample = (Spinner)findViewById(R.id.id_to_spinner);
    spinnerExample.setAdapter(adapter);
    spinnerExample.setOnItemSelectedListener(listerner);
    
    // Get a reference to the ListView that will be used in the listener
    listViewToPopulate = (ListView)findViewById(R.id.id_to_listview);
    

    And the associated OnClickListener to handle list population:

    OnItemSelectedListener listerner = new OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> paramAdapterView,
                View paramView, int paramInt, long paramLong) {
            String selection = (String)paramAdapterView.getItemAtPosition(paramInt);
            // Populate list based on selection
        }
    
        @Override
        public void onNothingSelected(AdapterView<?> paramAdapterView) {
            // do nothing
        }
    };
    
    0 讨论(0)
提交回复
热议问题