Spinner小记

来源:互联网 发布:免费人才测评软件 编辑:程序博客网 时间:2024/05/29 08:04
 

一、Activity部份代码

// Generate spinner entries using XML arrays

intvisiblelimitValuesId= R.array.account_settings_down_count_values;

intvisiblelimitEntriesId= R.array.account_settings_down_count_entries;

CharSequence[] visiblelimitValues = getResources().getTextArray(visiblelimitValuesId);

CharSequence[] visiblelimitEntries = getResources().getTextArray(visiblelimitEntriesId);

// Now create the array used by the Spinner

SpinnerOption[] checkVisiblelimits =newSpinnerOption[visiblelimitEntries.length];

for(inti = 0; i < visiblelimitEntries.length; i++) {

checkVisiblelimits[i] =newSpinnerOption(

Integer.valueOf(visiblelimitValues[i].toString()), visiblelimitEntries[i].toString());

}

ArrayAdapter<SpinnerOption> checkVisiblelimitsAdapter =newArrayAdapter<SpinnerOption>(this,android.R.layout.simple_spinner_item, checkVisiblelimits);

checkVisiblelimitsAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

downloadCount.setAdapter(checkVisiblelimitsAdapter);

SpinnerOption.setSpinnerOptionValue(downloadCount,VISIBLE_LIMIT_DEFAULT);

二、SpinnerOption代码

publicclassSpinnerOption {

publicfinalObjectvalue;

publicfinalStringlabel;

publicstaticvoidsetSpinnerOptionValue(

Spinner spinner, Object value) {

for(inti = 0, count = spinner.getCount(); i < count; i++) {

SpinnerOption so = (SpinnerOption)spinner.getItemAtPosition(i);

if(so.value.equals(value)) {

spinner.setSelection(i,true);

return;

}

}

}

publicSpinnerOption(Object value, String label) {

this.value= value;

this.label= label;

}

@Override

publicString toString() {

returnlabel;

}

三、如何获取Spinner选中项值

intvisibelLimit = (Integer)((SpinnerOption)downloadCount.getSelectedItem()).value;

四、

<PreferenceCategory android:title="@string/account_settings_download_title">

<ListPreference

android:layout="?android:attr/preferenceLayoutChild"

android:dependency="account_down"

android:key="account_settings_down"

android:defaultValue="never"

android:title="@string/account_settings_download_title"

android:entries="@array/account_settings_down_entries"

android:entryValues="@array/account_settings_down_values"

android:dialogTitle="@string/account_settings_download_title"

/>

</PreferenceCategory>

--------------------------------------------------------------------------

实例: 主要目的假如在values.xml文件中已定义6个StringArrays的Item的项目,在Spinner中属性已定义Entries绑定了数据,不修改这2个文件下修改代码,只显示4个Item。

意思是重新绑定下即可。

java代码

package luokan.commonui;import android.app.Activity;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.widget.AdapterView;import android.widget.AdapterView.OnItemSelectedListener;import android.widget.ArrayAdapter;import android.widget.Spinner;import android.widget.Toast;public class MainActivity extends Activity {private Spinner spinner;/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);spinner = (Spinner) findViewById(R.id.spinner);/* * ArrayAdapter arrayadp = ArrayAdapter.createFromResource(this, * R.array.spinner_arrays,android.R.layout.simple_spinner_item); */int arraysValueID = R.array.spinner_arrays;String[] entriesValue = getResources().getStringArray(arraysValueID);/*new arrays */SpinnerOption[] optionsValue = new SpinnerOption[entriesValue.length-2];for (int i = 0; i < optionsValue.length; i++) {optionsValue[i] = new SpinnerOption(entriesValue[i].toString());}ArrayAdapter<SpinnerOption> arrayadp = new ArrayAdapter<SpinnerOption>(this, android.R.layout.simple_spinner_item, optionsValue);arrayadp.setDropDownViewResource(android.R.layout. simple_spinner_dropdown_item);spinner.setAdapter(arrayadp);spinner.setPrompt("信息:");//SpinnerOption.setSpinnerOptionValue(spinner,"");/*spinner.setOnItemSelectedListener(new OnItemSelectedListener() {public void onItemSelected(AdapterView<?> parent, View view,int position, long id) {Toast.makeText(getApplicationContext(), position + "", 0).show();}public void onNothingSelected(AdapterView<?> parent) {Toast.makeText(getApplicationContext(), "ʲôҲûѡ", 0).show();}});*/}}

一个放新数组的类:

package luokan.commonui;import android.widget.Spinner;public class SpinnerOption {public String value;public SpinnerOption(String value) {this.value = value;}public static void setSpinnerOptionValue(Spinner spinner, Object value) {for (int i = 0, count = spinner.getCount(); i < count; i++) {SpinnerOption so = (SpinnerOption) spinner.getItemAtPosition(i);//if (so.value.equals(value)) {spinner.setSelection(i, true);return;//}}}@Overridepublic String toString() {return value;}}



    <Spinner
    android:id="@+id/spinner"
     android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:entries="@array/spinner_arrays"
    >
    </Spinner>

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <string name="hello">Hello World, MainActivity!</string>
 <string name="app_name">常用Ui</string>
 <string-array name="spinner_arrays">
  <item>abc</item>
  <item>edf</item>
  <item>sss</item>
  <item>eeee</item>
  <item>fffffff</item>
 <item>tttt</item>
</string-array>
</resources>

 

 

 --------------------------------------------------------------spinner在dialog对话框内的使用,,,-----------在Activity消亡之前把dialog。dismiss掉;否则发生窗口泄漏异常。

import android.app.Activity;import android.app.AlertDialog;import android.app.Dialog;import android.content.DialogInterface;import android.os.Bundle;import android.util.Log;import android.view.KeyEvent;import android.view.View;import android.view.View.OnClickListener;import android.widget.AdapterView;import android.widget.Spinner;import android.widget.TextView;public class Activity03 extends Activity implements AdapterView.OnItemSelectedListener{ private final static int DIALOG_PAUSED_ID = 1; private TextView text,myTextView2; private View mView; AlertDialog alert; @Override protected void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.three);  mView = getLayoutInflater().inflate(R.layout.spinner, null);        Spinner spinner = ((Spinner) mView.findViewById(R.id.spinner));              //  spinner.setSelection(1);        spinner.setOnItemSelectedListener(this);  findViewById(R.id.myButton03).setOnClickListener(new OnClickListener(){   public void onClick(View v) {   // showDialog(DIALOG_PAUSED_ID);    createDialog();   }     });  text = (TextView) findViewById(R.id.myTextView03);  myTextView2 = (TextView)mView.findViewById(R.id.myTextView2); }      @Override    protected Dialog onCreateDialog(int id) {        if (id == DIALOG_PAUSED_ID) {         //   return createDialog();        }        return null;    }        public void createDialog(){     Log.i("other", "come on");        AlertDialog.Builder builder = new AlertDialog.Builder(this);          builder.setMessage("Are you sure you want to exit?")                 .setCancelable(false)                .setView(mView)                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {                     public void onClick(DialogInterface dialog, int id) {                        //  MyActivity.this.finish();                      dialog.cancel();                    }                 })                 .setNegativeButton("No", new DialogInterface.OnClickListener() {                     public void onClick(DialogInterface dialog, int id) {                          dialog.cancel();                     }                 });          alert = builder.create();          alert.show();    } public void onItemSelected(AdapterView<?> parent, View view, int position,   long id) { // myTextView2.setText(position); } public void onNothingSelected(AdapterView<?> parent) {  // TODO Auto-generated method stub   }/* @Override public boolean onKeyDown(int keyCode, KeyEvent event) {  if(keyCode == KeyEvent.KEYCODE_HOME){   Log.i("other", "alert dismiss..come on");      finish();  }  return super.onKeyDown(keyCode, event); }*/ @Override protected void onPause() {  Log.i("other", "alert dismiss..come on");       if (alert != null) {        alert.dismiss();        alert = null;         }  super.onPause(); }}


mainifest.xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"      package="mars.activity"      android:versionCode="1"      android:versionName="1.0">    <application android:icon="@drawable/icon" android:label="@string/app_name">        <activity android:name=".Activity01"                  android:label="@string/app_name"                    android:taskAffinity="mars.activity.Activity01"                android:clearTaskOnLaunch="true"                android:launchMode="singleTop">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />                <category android:name="android.intent.category.DEFAULT" />            </intent-filter>        </activity>        <activity android:name=".Activity02" android:clearTaskOnLaunch="true"                  android:label="@string/app_name" >              </activity>   <activity android:name=".Activity03"                  android:label="@string/app_name"                    android:configChanges="orientation|keyboardHidden"               >        </activity>    </application>    <uses-sdk android:minSdkVersion="5" /></manifest> 


 

 

 

 

 

原创粉丝点击