我正在尝试使Spinner加载而没有选定的值。用户选择一个值后,它将带他们到另一个页面。
事实证明,这是一个问题,因为当前页面只是在用户获得选择权之前立即加载。
我的Spinner类的设置方法与Google的设置方法相同:http : //developer.android.com/resources/tutorials/views/hello-spinner.html
因此,基本上,是否有可能在不选择任何内容的情况下加载微调器,因为目前,它会加载我的字符串数组中的第一项。
我正在尝试使Spinner加载而没有选定的值。用户选择一个值后,它将带他们到另一个页面。
事实证明,这是一个问题,因为当前页面只是在用户获得选择权之前立即加载。
我的Spinner类的设置方法与Google的设置方法相同:http : //developer.android.com/resources/tutorials/views/hello-spinner.html
因此,基本上,是否有可能在不选择任何内容的情况下加载微调器,因为目前,它会加载我的字符串数组中的第一项。
Answers:
是否有可能在未选择任何内容的情况下加载微调器
仅当没有数据时。如果您的中有1+个项目SpinnerAdapter
,Spinner
则将始终有一个选择。
Spinners
不设计为命令小部件。用户不会期望在中进行选择Spinner
来启动活动。请考虑使用其他字符(例如ListView
或GridView
)代替Spinner
。
编辑
顺便说一句,我忘了提及-您总是可以在适配器中放置一个表示“无选择”的额外条目,并将其作为的初始选定项Spinner
。
或者,您可以覆盖微调适配器,并在getView方法中提供位置0的空白视图,并在getDropDownView
方法中提供高度为0dp的视图。
这样,您有一个初始文本,例如“选择选项...”,该文本在首次加载微调器时显示,但不是用户选择的选项(从技术上来说是这样,而是因为高度为0 ,他们看不到)。
这是Paul Bourdeaux想法的完整实现,即在getView()
位置0返回特殊的初始视图(或空视图)。
它对我有用,相对简单。您可能会考虑使用这种方法,特别是如果您已经为Spinner使用了自定义适配器。(就我而言,我使用自定义适配器是为了轻松自定义项目的布局,每个项目都有几个TextView。)
适配器将遵循以下原则:
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;
}
}
而已。请注意,如果您OnItemSelectedListener
在Spinner中使用,则onItemSelected()
还必须进行调整position
以考虑默认项,例如:
if (position == 0) {
return;
} else {
position = position - 1;
}
MyModel selected = items.get(position);
android.R.layout.simple_spinner_item
。进一步阅读:Spinner基础知识和定制的Spinner布局。
在我的情况下,尽管微调器中显示的是大小“ 2”,但在进行某些选择之前什么也不会发生!
我有一个xml文件(data_sizes.xml),其中列出了所有微调器值。
<?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>
在main.xml文件中:Spinner元素
<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;
在公共void函数中-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());
我的微调监听器:
/ *微调监听器* /
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]);
}
}
我的解决方案,如果您有一个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()
}
}
当您Spinner
使用该fill()
命令将项目加载到您的项目时,应该知道,索引也会增加。因此,如果您希望选择第三项,则现在应该选择第四项: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
}