我正在尝试让下拉框(Spinner)不选择任何值就加载。一旦用户选择了一个值,它就会带他们去另一个页面。
目前出现的问题是,在用户有机会进行选择之前,页面立即加载。
我的Spinner类的设置与Google的设置相同:http://developer.android.com/resources/tutorials/views/hello-spinner.html
所以基本上,有没有可能让Spinner在加载时不选中任何内容?因为目前它会加载字符串数组中的第一项。
我正在尝试让下拉框(Spinner)不选择任何值就加载。一旦用户选择了一个值,它就会带他们去另一个页面。
目前出现的问题是,在用户有机会进行选择之前,页面立即加载。
我的Spinner类的设置与Google的设置相同:http://developer.android.com/resources/tutorials/views/hello-spinner.html
所以基本上,有没有可能让Spinner在加载时不选中任何内容?因为目前它会加载字符串数组中的第一项。
或者,您可以重写自己的"spinner adapter",并在getView方法中为位置0提供一个空视图,在getDropDownView
方法中提供一个高度为0dp的视图。
这样,当Spinner首次加载时,您将拥有一个初始文本,例如"选择一个选项...",但用户不能选择它(技术上可以,但因为高度为0,他们看不到它)。
这是Paul Bourdeaux的思路的完整实现,即在getView()
方法中,为位置0返回一个特殊的初始视图(或空视图)。
对我来说它很有效,也相对简单。如果您已经有了自定义的Spinner适配器,您可能会考虑采用这种方法,尤其是如果您想要轻松定制每个项目的布局。(在我的情况下,我使用自定义适配器以方便地自定义项目的布局,每个项目都有几个TextViews。)
适配器大致如下:
public class MySpinnerAdapter extends ArrayAdapter<MyModel> {
public MySpinnerAdapter(Context context, List<MyModel> items) {
super(context, R.layout.my_spinner_row, items);
}
@Override
public View getDropDownView(int position, View convertView, @NonNull ViewGroup parent) {
if (position == 0) {
return initialSelection(true);
}
return getCustomView(position, convertView, parent);
}
@NonNull
@Override
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
if (position == 0) {
return initialSelection(false);
}
return getCustomView(position, convertView, parent);
}
@Override
public int getCount() {
return super.getCount() + 1; // Adjust for initial selection item
}
private View initialSelection(boolean dropdown) {
// Just an example using a simple TextView. Create whatever default view
// to suit your needs, inflating a separate layout if it's cleaner.
TextView view = new TextView(getContext());
view.setText(R.string.select_one);
int spacing = getContext().getResources().getDimensionPixelSize(R.dimen.spacing_smaller);
view.setPadding(0, spacing, 0, spacing);
if (dropdown) { // Hidden when the dropdown is opened
view.setHeight(0);
}
return view;
}
private View getCustomView(int position, View convertView, ViewGroup parent) {
// Distinguish "real" spinner items (that can be reused) from initial selection item
View row = convertView != null && !(convertView instanceof TextView)
? convertView :
LayoutInflater.from(getContext()).inflate(R.layout.my_spinner_row, parent, false);
position = position - 1; // Adjust for initial selection item
MyModel item = getItem(position);
// ... Resolve views & populate with data ...
return row;
}
}
就是这样。请注意,如果您在Spinner中使用OnItemSelectedListener
,那么在onItemSelected()
中,您还需要调整position
以考虑默认项,例如:
if (position == 0) {
return;
} else {
position = position - 1;
}
MyModel selected = items.get(position);
android.R.layout.simple_spinner_item
。更多阅读:Spinner基础知识和自定义Spinner布局。 - Jonik<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="chunks">
<item>2</item>
<item>4</item>
<item>8</item>
<item>16</item>
<item>32</item>
</string-array>
</resources>
<Spinner android:id="@+id/spinnerSize"
android:layout_marginLeft="50px"
android:layout_width="fill_parent"
android:drawSelectorOnTop="true"
android:layout_marginTop="5dip"
android:prompt="@string/SelectSize"
android:layout_marginRight="30px"
android:layout_height="35px" />
然后在我的Java代码中,我添加了:
在我的活动中声明:
Spinner spinnerSize;
ArrayAdapter adapter;
在一个公共的无返回值函数 - initControls() 中:定义
spinnerSize = (Spinner)findViewById(R.id.spinnerSize);
adapter = ArrayAdapter.createFromResource(this, R.array.chunks, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSize.setAdapter(adapter);
spinnerSize.setOnItemSelectedListener(new MyOnItemSelectedListener());
我的Spinner监听器:
/* Spinner 监听器 */
class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
chunkSize = new Integer(parent.getItemAtPosition(pos).toString()).intValue();
}
public void onNothingSelected(AdapterView<?> parent) {
// Dummy
}
}
使用自定义的下拉菜单布局,像这样:
<?xml version="1.0" encoding="utf-8"?>
<Spinner xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/spinnerTarget"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="14dp"
android:textColor="#000000"/>
在这个活动中:
// populate the list
ArrayList<String> dataList = new ArrayList<String>();
for (int i = 0; i < 4; i++) {
dataList.add("Item");
}
// set custom layout spinner_layout.xml and adapter
Spinner spinnerObject = (Spinner) findViewById(R.id.spinnerObject);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, R.drawable.spinner_layout, dataList);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerObject.setAdapter(dataAdapter);
spinnerObject.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// to set value of first selection, because setOnItemSelectedListener will not dispatch if the user selects first element
TextView spinnerTarget = (TextView)v.findViewById(R.id.spinnerTarget);
spinnerTarget.setText(spinnerObject.getSelectedItem().toString());
return false;
}
});
spinnerObject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
private boolean selectionControl = true;
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
// just the first time
if(selectionControl){
// find TextView in layout
TextView spinnerTarget = (TextView)parent.findViewById(R.id.spinnerTarget);
// set spinner text empty
spinnerTarget.setText("");
selectionControl = false;
}
else{
// select object
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
private long previousItemId = 0;
@Override
public long getItemId(int position) {
long nextItemId = random.nextInt(Integer.MAX_VALUE);
while(previousItemId == nextItemId) {
nextItemId = random.nextInt(Integer.MAX_VALUE);
}
previousItemId = nextItemId;
return nextItemId;
}
通过这个答案:
public class SpinnerInteractionListener
implements AdapterView.OnItemSelectedListener, View.OnTouchListener {
private AdapterView.OnItemSelectedListener onItemSelectedListener;
public SpinnerInteractionListener(AdapterView.OnItemSelectedListener selectedListener) {
this.onItemSelectedListener = selectedListener;
}
boolean userSelect = false;
@Override
public boolean onTouch(View v, MotionEvent event) {
userSelect = true;
return false;
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if(userSelect) {
onItemSelectedListener.onItemSelected(parent, view, pos, id);
userSelect = false;
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
if(userSelect) {
onItemSelectedListener.onNothingSelected(parent);
userSelect = false;
}
}
}
您可以将数组中的第一个单元格留空({"","some","some",...}),如果位置为0,则什么也不做。
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position>0) {
label.setText(MainActivity.questions[position - 1]);
}
}
我的解决方案是,如果您的Spinner每行使用的是TextView:
// TODO: add a fake item as the last one of "items"
final ArrayAdapter<String> adapter=new ArrayAdapter<String>(..,..,items)
{
@Override
public View getDropDownView(final int position,final View convertView,final ViewGroup parent)
{
final View dropDownView=super.getDropDownView(position,convertView,parent);
((TextView)dropDownView.findViewById(android.R.id.text1)).setHeight(position==getCount()-1?0:getDimensionFromAttribute(..,R.attr.dropdownListPreferredItemHeight));
dropDownView.getLayoutParams().height=position==getCount()-1?0:LayoutParams.MATCH_PARENT;
return dropDownView;
}
}
...
spinner.setAdapter(adapter);
_actionModeSpinnerView.setSelection(dataAdapter.getCount()-1,false);
public static int getDimensionFromAttribute(final Context context,final int attr)
{
final TypedValue typedValue=new TypedValue();
if(context.getTheme().resolveAttribute(attr,typedValue,true))
return TypedValue.complexToDimensionPixelSize(typedValue.data,context.getResources().getDisplayMetrics());
return 0;
}
Spinner
(这是Spinner
的一个奇怪功能,不能在未选择项目的情况下显示列表)。 您应该添加一个包含数据的类:data class YourData(val id: Int, val name: String?)
class YourAdapter(
context: Context,
private val textViewResourceId: Int,
private var items: ArrayList<YourData>
) : ArrayAdapter<YourData>(context, textViewResourceId, items) {
private var inflater: LayoutInflater = context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
override fun getCount(): Int = items.size + 1
override fun getItem(position: Int): YourData? =
if (position == 0) YourData(0, "") else items[position - 1]
override fun getItemId(position: Int): Long = position.toLong()
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View =
if (position == 0) {
getFirstTextView(convertView)
} else {
getTextView(convertView, parent, position - 1)
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View =
getView(position, convertView, parent)
private fun getFirstTextView(convertView: View?): View {
// Just simple TextView as initial selection.
var textView: TextView? = convertView as? TextView
val holder: FirstViewHolder
if (textView?.tag !is FirstViewHolder) {
textView = TextView(context) // inflater.inflate(R.layout.your_text, parent, false) as TextView
textView.height = 0 // Hide first item.
holder = FirstViewHolder()
holder.textView = textView
textView.tag = holder
}
return textView
}
private fun getTextView(
convertView: View?,
parent: ViewGroup,
position: Int
): TextView {
var textView: TextView? = convertView as? TextView
val holder: ViewHolder
if (textView?.tag is ViewHolder) {
holder = textView.tag as ViewHolder
} else {
textView = inflater.inflate(textViewResourceId, parent, false) as TextView
holder = ViewHolder()
holder.textView = textView
textView.tag = holder
}
holder.textView.text = items[position].name
return textView
}
private class FirstViewHolder {
lateinit var textView: TextView
}
private class ViewHolder {
lateinit var textView: TextView
}
}
要创建:
YourAdapter(context!!, R.layout.text_item, ArrayList())
添加项目:
private fun fill(items: List<YourData>, adapter: YourAdapter) {
adapter.run {
clear()
addAll(items)
notifyDataSetChanged()
}
}
fill()
命令将项加载到Spinner
中时,应该知道索引也会递增。因此,如果您希望选择第3个项目,则现在应选择第4个:spinner?.setSelection(index + 1)
基于@Jonik的答案,我创建了一个完全功能的ArrayAdapter扩展。
class SpinnerArrayAdapter<T> : ArrayAdapter<T> {
private val selectText : String
private val resource: Int
private val fieldId : Int
private val inflater : LayoutInflater
constructor(context: Context?, resource: Int, objects: Array<T>, selectText : String? = null) : super(context, resource, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = 0
this.inflater = LayoutInflater.from(context)
}
constructor(context: Context?, resource : Int, objects: List<T>, selectText : String? = null) : super(context, resource, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = 0
this.inflater = LayoutInflater.from(context)
}
constructor(context: Context?, resource: Int, textViewResourceId: Int, objects: Array<T>, selectText : String? = null) : super(context, resource, textViewResourceId, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = textViewResourceId
this.inflater = LayoutInflater.from(context)
}
constructor(context: Context?, resource : Int, textViewResourceId: Int, objects: List<T>, selectText : String? = null) : super(context, resource, textViewResourceId, objects) {
this.selectText = selectText ?: context?.getString(R.string.spinner_default_select_text) ?: ""
this.resource = resource
this.fieldId = textViewResourceId
this.inflater = LayoutInflater.from(context)
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup?): View {
if(position == 0) {
return initialSelection(true)
}
return createViewFromResource(inflater, position -1, convertView, parent, resource)
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
if(position == 0) {
return initialSelection(false)
}
return createViewFromResource(inflater, position -1, convertView, parent, resource)
}
override fun getCount(): Int {
return super.getCount() + 1 // adjust for initial selection
}
private fun initialSelection(inDropDown: Boolean) : View {
// Just simple TextView as initial selection.
val view = TextView(context)
view.setText(selectText)
view.setPadding(8, 0, 8, 0)
if(inDropDown) {
// Hide when dropdown is open
view.height = 0
}
return view
}
private fun createViewFromResource(inflater: LayoutInflater, position: Int,
@Nullable convertView: View?, parent: ViewGroup?, resource: Int): View {
val view: View
val text: TextView?
if (convertView == null || (convertView is TextView)) {
view = inflater.inflate(resource, parent, false)
} else {
view = convertView
}
try {
if (fieldId === 0) {
// If no custom field is assigned, assume the whole resource is a TextView
text = view as TextView
} else {
// Otherwise, find the TextView field within the layout
text = view.findViewById(fieldId)
if (text == null) {
throw RuntimeException("Failed to find view with ID "
+ context.getResources().getResourceName(fieldId)
+ " in item layout")
}
}
} catch (e: ClassCastException) {
Log.e("ArrayAdapter", "You must supply a resource ID for a TextView")
throw IllegalStateException(
"ArrayAdapter requires the resource ID to be a TextView", e)
}
val item = getItem(position)
if (item is CharSequence) {
text.text = item
} else {
text.text = item!!.toString()
}
return view
}