Android常用UI之Spinner

来源:互联网 发布:linux创建目录 ls 编辑:程序博客网 时间:2024/05/01 15:06

    在做应用时,经常要用到下拉列表选择操作,比如我们点击下拉列表选择省市区,选择性别等。我们可以用多种方法实现,比如可以用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;
}
}


0 0
原创粉丝点击