我试图使用旋转器来显示项目从数组使用ArrayAdapter.Spinner必须像textView一样显示提示



我读过各种答案,如Stackoverflow。请回答关于我使用的代码的问题。

这是我在string。xml中的数组列表

<string-array name="planets_array">
    <item>Mercury</item>
    <item>Venus</item>
    <item>Earth</item>
    <item>Mars</item>
    <item>Jupiter</item>
    <item>Saturn</item>
    <item>Uranus</item>
    <item>Neptune</item>
</string-array>

这是我的代码

public class spinner extends AppCompatActivity {
String[] list;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_spinner);
    list = getResources().getStringArray(R.array.planets_array);
    final Spinner spinner = (Spinner) findViewById(R.id.spinner);
    final ArrayAdapter arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,list);
    arrayAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
    spinner.setAdapter(arrayAdapter);
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            spinner.setPrompt("Select a planet");
            Toast.makeText(getApplicationContext(),"You have selected "+list[position],Toast.LENGTH_SHORT).show();
        }
        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });
}
}

我想要一个像select planet这样的提示。但是请记住,我的toast消息是在onItemClick上设置的,所以toast也应该在我选择一个项目时显示,而不是在启动时自动显示。提示也不应该在List中显示

谢谢

尝试将第一项添加为

<string-array name="planets_array">
  <item>Select planet</item>
  <item>Mercury</item>
  <item>Venus</item>
  ...
  ...
 </string-array>

在监听器中检查第一个位置

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    if (position > 0) {
        Toast.makeText(getApplicationContext(),"You have selected "+list[position],Toast.LENGTH_SHORT).show();
      }
    }
    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }
});

EDIT:为第二个问题尝试创建一个不包含字符串数组第一项的列表,并创建一个数组适配器,如果position大于0,则将其设置为旋转控件,否则

我已经用这个链接来回答你的问题,这可能会帮助你做你想做的事情:如何制作一个带有初始文本"Select One"

public class NoDefaultSpinner extends Spinner {
public NoDefaultSpinner(Context context) {
    super(context);
}
public NoDefaultSpinner(Context context, AttributeSet attrs) {
    super(context, attrs);
}
public NoDefaultSpinner(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}
@Override
public void setAdapter(SpinnerAdapter orig ) {
    final SpinnerAdapter adapter = newProxy(orig);
    super.setAdapter(adapter);
    try {
        final Method m = AdapterView.class.getDeclaredMethod(
                "setNextSelectedPositionInt",int.class);
        m.setAccessible(true);
        m.invoke(this,-1);
        final Method n = AdapterView.class.getDeclaredMethod(
                "setSelectedPositionInt",int.class);
        n.setAccessible(true);
        n.invoke(this,-1);
    }
    catch( Exception e ) {
        throw new RuntimeException(e);
    }
}
protected SpinnerAdapter newProxy(SpinnerAdapter obj) {
    return (SpinnerAdapter) java.lang.reflect.Proxy.newProxyInstance(
            obj.getClass().getClassLoader(),
            new Class[]{SpinnerAdapter.class},
            new SpinnerAdapterProxy(obj));
}

/**
 * Intercepts getView() to display the prompt if position < 0
 */
protected class SpinnerAdapterProxy implements InvocationHandler {
    protected SpinnerAdapter obj;
    protected Method getView;

    protected SpinnerAdapterProxy(SpinnerAdapter obj) {
        this.obj = obj;
        try {
            this.getView = SpinnerAdapter.class.getMethod(
                    "getView",int.class,View.class,ViewGroup.class);
        }
        catch( Exception e ) {
            throw new RuntimeException(e);
        }
    }
    public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
        try {
            return m.equals(getView) &&
                    (Integer)(args[0])<0 ?
                    getView((Integer)args[0],(View)args[1],(ViewGroup)args[2]) :
                    m.invoke(obj, args);
        }
        catch (InvocationTargetException e) {
            throw e.getTargetException();
        }
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    protected View getView(int position, View convertView, ViewGroup parent)
            throws IllegalAccessException {
        if( position<0 ) {
            final TextView v =
                    (TextView) ((LayoutInflater)getContext().getSystemService(
                            Context.LAYOUT_INFLATER_SERVICE)).inflate(
                            android.R.layout.simple_spinner_item,parent,false);
            v.setText(getPrompt());
            return v;
        }
        return obj.getView(position,convertView,parent);
    }
 }
}

用NoDefaultSpinner改变布局文件中的旋转器。例:

<yourPackageName.NoDefaultSpinner 
    android:id="@+id/spinner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"></yourPackageName.NoDefaultSpinner>

这是你自己的类,首先将提示设置为旋转器,然后在任何项目被选中时更改它,如下所示:

public class spinner extends AppCompatActivity {
   String[] list;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_spinner);
    list = getResources().getStringArray(R.array.planets_array);
    final Spinner spinner = (Spinner) findViewById(R.id.spinner);
    //set first time hint here
    spinner.setPrompt("Select a planet");

    final ArrayAdapter arrayAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,list);
            arrayAdapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
    spinner.setAdapter(arrayAdapter);
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        //change your hint here
        spinner.setPrompt(list[position]);
        Toast.makeText(getApplicationContext(),"You have selected "+list[position],Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }
  });
}
}

最新更新