我想使用一个微调器,最初(当用户还没有做出选择时)显示文本“Select One”。当用户单击微调器时,将显示项目列表,用户可以选择其中一个选项。用户做出选择后,所选项目将显示在微调器中,而不是“Select One”。
我有以下代码来创建一个旋转器:
String[] items = new String[] {"One", "Two", "Three"};
Spinner spinner = (Spinner) findViewById(R.id.mySpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, items);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
使用这段代码,最初会显示项目“One”。我可以在项目中添加一个新项目“Select One”,但“Select One”也会作为第一项显示在下拉列表中,这不是我想要的。
我该如何解决这个问题?
最好的解决方案,我发现这实际上不是使用一个纺纱机,而是一个AutoCompleteTextView。它基本上是一个带有附加Spinner的EditText,可以在你输入时显示建议-但是,通过正确的配置,它可以完全按照OP的要求进行操作。
XML:
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/item"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.AppCompatAutoCompleteTextView
android:id="@+id/input"
android:hint="Select one"
style="@style/AutoCompleteTextViewDropDown"/>
</com.google.android.material.textfield.TextInputLayout>
风格:
<style name="AutoCompleteTextViewDropDown">
<item name="android:clickable">false</item>
<item name="android:cursorVisible">false</item>
<item name="android:focusable">false</item>
<item name="android:focusableInTouchMode">false</item>
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
</style>
至于适配器,使用基本的ArrayAdapter或扩展它来创建自己的适配器,但不需要在适配器方面进行额外的定制。在AutoCompleteTextView上设置适配器。
之前提交的答案都没有真正按照我想要的方式解决这个问题。对我来说,理想的解决方案是在旋转器第一次显示时提供“Select One”(或任何初始文本)。当用户点击转轮时,初始文本不应该是显示的下拉框的一部分。
为了使我的特定情况更加复杂,我的旋转器数据来自通过LoaderManager回调加载的游标。
经过大量的实验,我想出了以下解决方案:
public class MyFragment extends Fragment implements
LoaderManager.LoaderCallbacks<Cursor>{
private static final String SPINNER_INIT_VALUE = "Select A Widget";
private Spinner mSpinner;
private int mSpinnerPosition;
private boolean mSpinnerDropDownShowing = false;
private View mSpinnerDropDown;
private MyCursorAdapter mCursorAdapter;
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
...
mCursorAdapter = new MyCursorAdapter(getActivity());
mSpinner = (Spinner) rootView.findViewById(R.id.theSpinner);
mSpinner.setOnTouchListener(mSpinnerTouchListener);
mSpinner.setAdapter(mCursorAdapter);
...
}
//Capture the touch events to toggle the spinner's dropdown visibility
private OnTouchListener mSpinnerTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if(mSpinnerDropDown != null && mSpinnerDropDownShowing == false){
mSpinnerDropDownShowing = true;
mSpinnerDropDown.setVisibility(View.VISIBLE);
}
return false;
}
};
//Capture the click event on the spinner drop down items
protected OnClickListener spinnerItemClick = new OnClickListener(){
@Override
public void onClick(View view) {
String widget = ((TextView) view.findViewById(android.R.id.text1)).getText().toString();
if(!widget.equals(SPINNER_INIT_VALUE)){
if(mCursorAdapter != null){
Cursor cursor = mCursorAdapter.getCursor();
if(cursor.moveToFirst()){
while(!cursor.isAfterLast()){
if(widget.equals(cursor.getString(WidgetQuery.WIDGET_NAME))){
...
//Set the spinner to the correct item
mSpinnerPosition = cursor.getPosition() + 1;
mSpinner.setSelection(mSpinnerPosition);
break;
}
cursor.moveToNext();
}
}
}
}
//Hide the drop down. Not the most elegent solution but it is the only way I could hide/dismiss the drop down
mSpinnerDropDown = view.getRootView();
mSpinnerDropDownShowing = false;
mSpinnerDropDown.setVisibility(View.GONE);
}
};
private class MyCursorAdapter extends CursorAdapter {
private final int DISPLACEMENT = 1;
private final int DEFAULT_ITEM_ID = Integer.MAX_VALUE;
private Activity mActivity;
public MyCursorAdapter(Activity activity) {
super(activity, null, false);
mActivity = activity;
}
//When loading the regular views, inject the defualt item
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(position == 0){
if(convertView == null){
convertView = mActivity.getLayoutInflater().inflate(R.layout.list_item_widget, parent, false);
}
return getDefaultItem(convertView);
}
return super.getView(position - DISPLACEMENT, convertView, parent);
}
//When loading the drop down views, set the onClickListener for each view
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent){
View view = super.getDropDownView(position, convertView, parent);
view.setOnClickListener(spinnerItemClick);
return view;
}
//The special default item that is being injected
private View getDefaultItem(View convertView){
TextView text = (TextView) convertView.findViewById(android.R.id.text1);
text.setText(SPINNER_INIT_VALUE);
return convertView;
}
@Override
public long getItemId(int position) {
if (position == 0) {
return DEFAULT_ITEM_ID;
}
return super.getItemId(position - DISPLACEMENT);
}
@Override
public boolean isEnabled(int position) {
return position == 0 ? true : super.isEnabled(position - DISPLACEMENT);
}
@Override
public int getViewTypeCount() {
return super.getViewTypeCount() + DISPLACEMENT;
}
@Override
public int getItemViewType(int position) {
if (position == 0) {
return super.getViewTypeCount();
}
return super.getItemViewType(position - DISPLACEMENT);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return mActivity.getLayoutInflater().inflate(R.layout.list_item_widget, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor){
if(cursor.isAfterLast()){
return;
}
TextView text = (TextView) view.findViewById(android.R.id.text1);
String WidgetName = cursor.getString(WidgetQuery.WIDGET_NAME);
text.setText(WidgetName);
}
}
}
private boolean isFirst = true;
private void setAdapter() {
final ArrayList<String> spinnerArray = new ArrayList<String>();
spinnerArray.add("Select your option");
spinnerArray.add("Option 1");
spinnerArray.add("Option 2");
spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
TextView tv = (TextView)selectedItemView;
String res = tv.getText().toString().trim();
if (res.equals("Option 1")) {
//do Something
} else if (res.equals("Option 2")) {
//do Something else
}
}
@Override
public void onNothingSelected(AdapterView<?> parentView) { }
});
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.my_spinner_style,spinnerArray) {
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 25, getResources().getDisplayMetrics());
((TextView) v).setTypeface(tf2);
((TextView) v).getLayoutParams().height = height;
((TextView) v).setGravity(Gravity.CENTER);
((TextView) v).setTextSize(TypedValue.COMPLEX_UNIT_SP, 19);
((TextView) v).setTextColor(Color.WHITE);
return v;
}
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
if (isFirst) {
isFirst = false;
spinnerArray.remove(0);
}
View v = super.getDropDownView(position, convertView, parent);
((TextView) v).setTextColor(Color.argb(255, 70, 70, 70));
((TextView) v).setTypeface(tf2);
((TextView) v).setGravity(Gravity.CENTER);
return v;
}
};
spin.setAdapter(adapter);
}
对此,我找到了很多好的解决方案。大多数是通过在适配器的末尾添加一个项来工作的,并且不在下拉列表中显示最后一个项。
对我来说最大的问题是旋转器下拉列表将从列表的底部开始。所以用户看到的最后一个项目,而不是第一个项目(在情况下有许多项目显示),触摸转轮后,第一次。
所以我把提示项放在列表的开头。并在下拉列表中隐藏第一项。
private void loadSpinner(){
HintArrayAdapter hintAdapter = new HintArrayAdapter<String>(context, 0);
hintAdapter.add("Hint to be displayed");
hintAdapter.add("Item 1");
hintAdapter.add("Item 2");
.
.
hintAdapter.add("Item 30");
spinner1.setAdapter(hintAdapter);
//spinner1.setSelection(0); //display hint. Actually you can ignore it, because the default is already 0
//spinner1.setSelection(0, false); //use this if don't want to onItemClick called for the hint
spinner1.setOnItemSelectedListener(yourListener);
}
private class HintArrayAdapter<T> extends ArrayAdapter<T> {
Context mContext;
public HintArrayAdapter(Context context, int resource) {
super(context, resource);
this.mContext = context
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(android.R.layout.simple_spinner_item, parent, false);
TextView texview = (TextView) view.findViewById(android.R.id.text1);
if(position == 0) {
texview.setText("");
texview.setHint(getItem(position).toString()); //"Hint to be displayed"
} else {
texview.setText(getItem(position).toString());
}
return view;
}
@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view;
if(position == 0){
view = inflater.inflate(R.layout.spinner_hint_list_item_layout, parent, false); // Hide first row
} else {
view = inflater.inflate(android.R.layout.simple_spinner_dropdown_item, parent, false);
TextView texview = (TextView) view.findViewById(android.R.id.text1);
texview.setText(getItem(position).toString());
}
return view;
}
}
在@Override getDropDownView()中设置下面的布局,当position为0时,隐藏第一个提示行。
R.layout.spinner_hint_list_item_layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</LinearLayout>