Android常用UI之Spinner

來源:互聯網
上載者:User

標籤:android應用   ui   控制項   

    在做應用時,經常要用到下拉式清單選擇操作,比如我們點擊下拉式清單選擇省市區,選擇性別等。我們可以用多種方法實現,比如可以用ListView顯示資料,再用onItemClickListner()事件來處理選擇操作。不過更好的選擇是用Android內建的下拉式清單控制項Spinner。

--------------------------超簡單布局--------------------------------------------------

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

    <TextView
        android:id="@+id/view_city"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Spinner
        android:id="@+id/my_pinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

-------------------------代碼實現------------------------------------

public class MainActivity extends Activity {
/**文字顯示TextView*/
private TextView mTextView;
/**下拉式清單Spinner */
private Spinner mSpinner;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById();
}
/**初始化控制項*/
private void findViewById() {
mTextView = (TextView) findViewById(R.id.view_city);
mSpinner = (Spinner) findViewById(R.id.my_spinner);
mSpinner.setOnItemSelectedListener(new DefultOnItemSelectedListener());
mSpinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, getData()));
}

/**自訂選擇事件類別 */
class DefultOnItemSelectedListener implements Spinner.OnItemSelectedListener {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mTextView.setText(parent.getItemAtPosition(position).toString());
}

@Override
public void onNothingSelected(AdapterView<?> parent) {
//暫未處理
}
};

/**設定些初始資料*/
private List<String> getData() {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10; i++) {
list.add("ldm_" + i);
}
return list;
}
}


Android常用UI之Spinner

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.