spinner並不是直接讀取資料,而是經由一個適配器(Adapter)做為資料的橋接
適配器(Adapter)我們在另外的章節再做介紹,今天先拿最簡單的ArrayAdapter做示範
廢話不多說,下面就開始為您實作:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/blood_group"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Spinner
android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, ReadtxtActivity!</string>
<string name="app_name">Readtxt</string>
<string name="blood_group">血型</string>
</resources>
ReadtxtActivity
package jim.readtxt;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class ReadtxtActivity extends Activity {
private Spinner spinner;
private ArrayAdapter<String> adapter;
private static final String[] Blood_group={"A型","B型","O型","AB型","其他"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
spinner = (Spinner) findViewById(R.id.spinner1);
//將可選内容與ArrayAdapter連接起來
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,Blood_group);
//設置下拉列表的風格
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//将adapter 添加到spinner中
spinner.setAdapter(adapter);
}catch(Exception e){
e.printStackTrace();
}
}
}
執行後畫面
後記:
此為最基礎的spinner下拉式選單應用,下個章節為您介紹spinner的其他應用。


這個程式不需要像c++依樣做宣告嗎
回覆刪除我造打完還是有錯誤
你好:
刪除你指的是哪方面的宣告?
Android是用Java開發的,所以如果對Java不了解請找Java相關書籍了解一下和c++差異
基本上Java不像C++那麼的嚴謹
程式都是有經過測試的,所以才會有畫面
請用Debug模式+中斷點找看看是在哪一行出錯了或是連Build都無法。
TextView T01;
回覆刪除CheckBox CB1,CB2,CB3;
/* (非 Javadoc)
* @see android.app.Activity#onCreate(android.os.Bundle)
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
T01=(TextView) this. findViewById(R.id.t01);
CB1=(CheckBox) this. findViewById(R.id.cb1);
CB2=(CheckBox) this.findViewById(R.id.cb2);
CB3=(CheckBox) this. findViewById(R.id.cb3);
CB1.setOnCheckedChangeListener(mylistener);
像這樣的宣告
我想做地址的下拉,需要怎麼用
回覆刪除縣市可以很多選項
再點完縣市,有可以分許須多區