在Android開發中,Spinner是一個下拉列表控件,可以用于在列表視圖中進行嵌套
activity_main.xml
布局文件中添加一個ListView
控件。 xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
list_item.xml
,其中包含一個TextView
和一個Spinner
控件。<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="8dp">
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Item Text" />
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity.java
中,創建一個自定義的適配器CustomAdapter
,繼承自BaseAdapter
。public class CustomAdapter extends BaseAdapter {
private Context context;
private List<String> data;
public CustomAdapter(Context context, List<String> data) {
this.context = context;
this.data = data;
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
}
TextView textView = convertView.findViewById(R.id.textView);
Spinner spinner = convertView.findViewById(R.id.spinner);
textView.setText(data.get(position));
ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter.createFromResource(context,
R.array.spinner_items, android.R.layout.simple_spinner_item);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerAdapter);
return convertView;
}
}
strings.xml
中添加Spinner的數據源。 <string name="app_name">SpinnerInListView</string>
<array name="spinner_items">
<item>Option 1</item>
<item>Option 2</item>
<item>Option 3</item>
</array>
</resources>
MainActivity.java
中設置ListView
的適配器。public class MainActivity extends AppCompatActivity {
private ListView listView;
private CustomAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
List<String> data = new ArrayList<>();
for (int i = 1; i <= 20; i++) {
data.add("Item " + i);
}
adapter = new CustomAdapter(this, data);
listView.setAdapter(adapter);
}
}
現在運行應用程序,你將看到一個包含20個列表項的ListView
,每個列表項都有一個TextView
和一個Spinner
。用戶可以在每個列表項中選擇不同的選項。