如何在微调器上设置字符串?

时间:2016-07-12 09:38:40

标签: android

String str = countries.get(country);

mSpinnerCountry.setSelection(的Integer.parseInt(STR));

mSpinnerCountry有项目,但我想在微调器上设置一个特定项目以供更新。

1 个答案:

答案 0 :(得分:1)

通过从微调器列表中获取项目索引来做到这一点。

spinner.setSelection(countries.indexOf(str));

完成示例:

public class SpinnerModel {

        private  String CompanyName="";
        private  String Image=""; 
        private  String Url="";

        /*********** Set Methods ******************/
        public void setCompanyName(String CompanyName)
        {
            this.CompanyName = CompanyName;
        }

        public void setImage(String Image)
        {
            this.Image = Image;
        }

        public void setUrl(String Url)
        {
            this.Url = Url;
        }

        /*********** Get Methods ****************/
        public String getCompanyName()
        {
            return this.CompanyName;
        }

        public String getImage()
        {
            return this.Image;
        }

        public String getUrl()
        {
            return this.Url;
        }   
  }

<强> activity_custom_spinner:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:orientation="vertical"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent">

      <TextView
          android:paddingTop="20dip"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"/>

      <Spinner
          android:id="@+id/spinner"
          android:drawSelectorOnTop="true"
          android:prompt="@string/defaultText"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"

          />

      <TextView
          android:paddingTop="20dip"
          android:paddingLeft="20dip"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:id="@+id/output"
          />

  </LinearLayout>

完整代码:

public class CustomSpinner extends Activity {

    /**************  Intialize Variables *************/
    public  ArrayList<SpinnerModel> CustomListViewValuesArr = new ArrayList<SpinnerModel>();
    TextView output = null;
    CustomAdapter adapter;
    CustomSpinner activity = null;

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

        activity  = this;

        Spinner  SpinnerExample = (Spinner)findViewById(R.id.spinner);
        output                  = (TextView)findViewById(R.id.output);

        // Set data in arraylist
        setListData();

        // Resources passed to adapter to get image
        Resources res = getResources(); 

        // Create custom adapter object ( see below CustomAdapter.java )
        adapter = new CustomAdapter(activity, R.layout.spinner_rows, CustomListViewValuesArr,res);

        // Set adapter to spinner
        SpinnerExample.setAdapter(adapter);

        // Listener called when spinner item selected
        SpinnerExample.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View v, int position, long id) {
                // your code here

                // Get selected row data to show on screen
                String Company    = ((TextView) v.findViewById(R.id.company)).getText().toString();
                String CompanyUrl = ((TextView) v.findViewById(R.id.sub)).getText().toString();

                String OutputMsg = "Selected Company : \n\n"+Company+"\n"+CompanyUrl;
                output.setText(OutputMsg);

                Toast.makeText(
                        getApplicationContext(),OutputMsg, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // your code here
            }

        });
    }

    /****** Function to set data in ArrayList *************/
    public void setListData()
    {

        // Now i have taken static values by loop.
        // For further inhancement we can take data by webservice / json / xml;

        for (int i = 0; i < 11; i++) {

            final SpinnerModel sched = new SpinnerModel();

              /******* Firstly take data in model object ******/
               sched.setCompanyName("Company "+i);
               sched.setImage("image"+i);
               sched.setUrl("http:\\www."+i+".com");

            /******** Take Model Object in ArrayList **********/
            CustomListViewValuesArr.add(sched);
        }

    }

  }

<强> CustomAdapter:

/***** Adapter class extends with ArrayAdapter ******/
public class CustomAdapter extends ArrayAdapter<String>{
     
    private Activity activity;
    private ArrayList data;
    public Resources res;
    SpinnerModel tempValues=null;
    LayoutInflater inflater;
     
    /*************  CustomAdapter Constructor *****************/
    public CustomAdapter(
                          CustomSpinner activitySpinner, 
                          int textViewResourceId,   
                          ArrayList objects,
                          Resources resLocal
                         ) 
     {
        super(activitySpinner, textViewResourceId, objects);
         
        /********** Take passed values **********/
        activity = activitySpinner;
        data     = objects;
        res      = resLocal;
    
        /***********  Layout inflator to call external xml layout () **********************/
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
         
      }
 
    @Override
    public View getDropDownView(int position, View convertView,ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }
 
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }
 
    // This funtion called for each row ( Called data.size() times )
    public View getCustomView(int position, View convertView, ViewGroup parent) {
 
        /********** Inflate spinner_rows.xml file for each row ( Defined below ) ************/
        View row = inflater.inflate(R.layout.spinner_rows, parent, false);
         
        /***** Get each Model object from Arraylist ********/
        tempValues = null;
        tempValues = (SpinnerModel) data.get(position);
         
        TextView label        = (TextView)row.findViewById(R.id.company);
        TextView sub          = (TextView)row.findViewById(R.id.sub);
        ImageView companyLogo = (ImageView)row.findViewById(R.id.image);
         
        if(position==0){
             
            // Default selected Spinner item 
            label.setText("Please select company");
            sub.setText("");
        }
        else
        {
            // Set values for spinner each row 
            label.setText(tempValues.getCompanyName());
            sub.setText(tempValues.getUrl());
            companyLogo.setImageResource(res.getIdentifier
                                         ("com.androidexample.customspinner:drawable/"
                                          + tempValues.getImage(),null,null));
             
        }   
 
        return row;
      }
 }

<强> spinner_rows.XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:orientation="vertical"
 android:padding="3dip"
>
    <ImageView
         android:id="@+id/image"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         />
    <TextView
         android:layout_toRightOf="@+id/image"
         android:padding="3dip"
         android:layout_marginTop="2dip"
         android:textColor="@drawable/red"
         android:textStyle="bold"
         android:id="@+id/company"
         android:layout_marginLeft="5dip"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"/>
     <TextView
         android:layout_toRightOf="@+id/image"
         android:padding="2dip"
         android:textColor="@drawable/darkgrey"
         android:layout_marginLeft="5dip"
         android:id="@+id/sub"
         android:layout_below="@+id/company"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"/>
</RelativeLayout>

Explanation demo