Android實現下拉式功能表Spinner效果_Android

來源:互聯網
上載者:User

Android 中下拉式功能表,即如html中的<select>,關鍵在於調用setDropDownViewResource方法,以XML的方式定義下拉式功能表要顯示的模樣

1.1.activity_main.xml

<?xml version="1.0" encoding="utf-8"?> <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"   tools:context="com.rj141.sb.kongjian.MainActivity">    <LinearLayout     android:orientation="horizontal"     android:layout_width="match_parent"     android:layout_height="wrap_content">     <TextView       android:layout_width="wrap_content"       android:layout_height="wrap_content"       android:textSize="18dp"       android:text="請選擇您最喜歡的水果:" />      <Spinner       android:layout_width="match_parent"       android:layout_height="wrap_content"       android:id="@+id/spinner" />   </LinearLayout>     <TextView     android:layout_width="wrap_content"     android:layout_height="wrap_content"     android:textSize="18dp"     android:id="@+id/tv" />  </LinearLayout> 

Spinner是下拉式清單的組件

1.2.MainActivity.class

public class MainActivity extends AppCompatActivity {    private Spinner s;   String[] data=new String[]{"蘋果","雪梨","西瓜","葡萄","橙子","草莓"};   private TextView tv;    @Override   protected void onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentView(R.layout.activity_main);      tv= (TextView) this.findViewById(R.id.tv);     s= (Spinner) this.findViewById(R.id.spinner);     s.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,data));     s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {       @Override       public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {         String str=data[position];         tv.setText("最喜歡的水果是:"+str);       }       @Override       public void onNothingSelected(AdapterView<?> parent) {       }     });   } } s.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,data));android.R.layout.simple_list_item_1是指安卓內建的下拉式清單格式,data是資料來源;s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()){..};是下拉式清單的監聽

效果圖:

以上就是本文的全部內容,希望對大家學習掌握Android實現下拉式功能表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.