2012年7月10日 星期二

Android:Spinner(下拉式選單)以及Adapter(接口)

XML layout:

<Spinner
        android:id="@+id/spinner1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="75dp"
        android:layout_marginTop="63dp" />


XML file (values)利用圖形化介面產生

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="webname">
        <item /><item >Google</item>
        <item >Yahoo</item>
        <item >Mobile01</item>
       
    </string-array>
    <string-array name="website">
        <item />
        <item >http://www.google.com</item>
        <item >http://www.yahoo.com</item>
        <item >http://www.mobile01.com</item>
    </string-array>
   
</resources>


Code



package com.spinner2;


import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;


public class MainActivity extends Activity {
Spinner spi;
String[] webname, website;


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spi = (Spinner) findViewById(R.id.spinner1);
//從XML中將預先設定好之string array叫進JAVA程式
webname = getResources().getStringArray(R.array.webname);
website = getResources().getStringArray(R.array.website);
//ArrayAdapter建構子需要三個參數,目的activity,,spinner樣式,以及顯示內容之字串陣列
ArrayAdapter ada = new ArrayAdapter(this,
android.R.layout.simple_spinner_item, webname);
//將Spinner與Adapter接上
spi.setAdapter(ada);
//設定監聽物件
spi.setOnItemSelectedListener(new OnItemSelectedListener() {
            /* arg0 The AdapterView where the selection happened
               arg1 The view within the AdapterView that was clicked
               arg2 The position of the view in the adapter
               arg3 The row id of the item that is selected
               使用arg2可以知道使用者選擇Spinner中item的位置  
               */
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
                           
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(website[arg2]));
startActivity(intent);
}


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


}


});
}


}





沒有留言:

張貼留言