[Android学习日记]2014.07.27

来源:互联网 发布:网络上游初始化失败 编辑:程序博客网 时间:2024/06/05 11:56

自定义Spinner下拉框

方法一:自定义Adapter,重载getView和getDropdownView函数;

方法二:自己写下拉框的布局,创建adapter时作为参数传入或调用,代码如下

下拉框布局文件spinner_dropdown.xml(layout文件夹下)

<?xml version="1.0" encoding="utf-8"?>  <TextView xmlns:android ="http://schemas.android.com/apk/res/android"            android:id="@+id/SpinnerText"            android:layout_gravity="center_vertical|left"            android:layout_width="fill_parent"            android:layout_height="wrap_content"            android:textSize="12pt"            android:layout_marginTop="8px"            android:layout_marginBottom="8px"            style ="?android:attr/spinnerDropDownItemStyle"  />  



创建adapter并设定

</pre><pre name="code" class="java">ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);  adapter.setDropDownViewResource(R.layout.spinner_dropdown);  xmlListSpinner.setAdapter(adapter);  


创建adapter时传入的布局为显示条目时的布局,这里用的系统自带的android.R.layout.simple_spinner_item。
调用setDropDownViewResource函数时传入的布局为下拉框的布局,这里自定义了spinner_dropdown文件,改变了字体大小和间距。

遇到的问题

ArrayAdapter requires the resource ID to be a TextView XML

在stackoverflow上找到了解答

The ArrayAdapter requires the resource ID to be a TextView XML        exception means you don't supply what the ArrayAdapter expects. When you use this constructor:

new ArrayAdapter<String>(this, R.layout.a_layout_file, this.file)  

R.Layout.a_layout_file must be the id of a xml layout file containing only a TextView(the TextView can't be wrapped by another layout, like a LinearLayout, RelativeLayout etc!), something like this:

<?xml version="1.0" encoding="utf-8"?>

       <TextView xmlns:android="http://schemas.android.com/apk/res/android"

                  android:layout_width="fill_parent"

                  android:layout_height="wrap_content"

                   //otherattributesoftheTextView

        />  

If you want your list row layout to be something a little different then a simple TextView widget use this constructor:

new ArrayAdapter<String>(this, R.layout.a_layout_file,    R.id.the_id_of_a_textview_from_the_layout, this.file) 

where you supply the id of a layout that can contain various views, but also must contain a TextView with and id(the third parameter) that you pass to your ArrayAdapter so it can know where to put the Strings in the row layout.

0 0
原创粉丝点击