String str[] = new String{"Select Gender","male", "female" };
然后在onItemSelected中
@Override
public void onItemSelected(AdapterView<?> main, View view, int position,
long Id) {
if(position > 0){
// get spinner value
}else{
// show toast select gender
}
}
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
/**
* A SpinnerAdapter which does not show the value of the initial selection initially,
* but an initialText.
* To use the spinner with initial selection instead call notifyDataSetChanged().
*/
public class SpinnerAdapterWithInitialText<T> extends ArrayAdapter<T> {
private Context context;
private int resource;
private boolean initialTextWasShown = false;
private String initialText = "Please select";
/**
* Constructor
*
* @param context The current context.
* @param resource The resource ID for a layout file containing a TextView to use when
* instantiating views.
* @param objects The objects to represent in the ListView.
*/
public SpinnerAdapterWithInitialText(@NonNull Context context, int resource, @NonNull T[] objects) {
super(context, resource, objects);
this.context = context;
this.resource = resource;
}
/**
* Returns whether the user has selected a spinner item, or if still the initial text is shown.
* @param spinner The spinner the SpinnerAdapterWithInitialText is assigned to.
* @return true if the user has selected a spinner item, false if not.
*/
public boolean selectionMade(Spinner spinner) {
return !((TextView)spinner.getSelectedView()).getText().toString().equals(initialText);
}
/**
* Returns a TextView with the initialText the first time getView is called.
* So the Spinner has an initialText which does not represent the selected item.
* To use the spinner with initial selection instead call notifyDataSetChanged(),
* after assigning the SpinnerAdapterWithInitialText.
*/
@Override
public View getView(int position, View recycle, ViewGroup container) {
if(initialTextWasShown) {
return super.getView(position, recycle, container);
} else {
initialTextWasShown = true;
LayoutInflater inflater = LayoutInflater.from(context);
final View view = inflater.inflate(resource, container, false);
((TextView) view).setText(initialText);
return view;
}
}
}
4条答案
按热度按时间vbopmzt11#
这里pos是整数(数组项位置)
数组如下所示,然后
pos = 0;
然后在onItemSelected中
dsf9zpds2#
我通过扩展
ArrayAdapter
和重写getView
方法找到了一个解决方案。Android在初始化Spinner时所做的是在为
T[] objects
中的所有项目调用getView之前为选定项目调用getView。SpinnerAdapterWithInitialText
返回TextView
,其中initialText
在第一次调用时,它调用super.getView
,这是ArrayAdapter
的getView
方法,如果您正常使用Spinner,则调用ArrayAdapter
方法。若要确定用户是否选择了微调控制项,或者微调控制项是否仍显示
initialText
,请调用selectionMade
并交出分配给适配器的微调控制项。2nbm6dog3#
微调不支持提示,我建议你做一个自定义微调适配器。
检查此链接:https://stackoverflow.com/a/13878692/1725748
5t7ly7z54#
请尝试以下内容: