2

I have read various answers such as Stackoverflow . Please answer the question with respect to the code which I used.

This is my array list in 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>

This is my code

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) {

        }
    });

}
}

I want a hint like select planet. But remember my toast message is set on onItemClick so toast also should be show when I SELECT an item and not automatically at the startup. And hint should also not be shown in List.

Thanks

Community
  • 1
  • 1

2 Answers2

1

Try adding the first item as

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

And in the listener check for first position

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 : for the second question Try creating a list without the first item of the string array and create a array adapter and set it to the spinner if position is greater than 0 and else otherwise

Sanoop Surendran
  • 3,484
  • 4
  • 28
  • 49
  • This is ok but not entirely as when I click on spinner "Select Planet" will also show in the list – Shubham Singh Jun 28 '16 at 06:17
  • first create two array adapters .. since your list is small it wont create performance issues .. one array with the hint and other without.. try it.. And lemme know.. Will help if theres any difficulty, :) @SWARNVEERSINGH – Sanoop Surendran Jun 28 '16 at 06:18
  • I tried that but it has 2 problems. 1) Redundancy of data. This is a small example but if there is more data then there is problem. 2) I setAdapter(duplicate_data) in position>0 of onItemSelected. First time that I click on spinner, select planet shows and then if I click on any planet toast message shows but the selected item on spinner is always mercury as the duplicate array is set – Shubham Singh Jun 28 '16 at 06:32
  • See the image with the code [link](https://s32.postimg.org/xm843uh5x/Capture.png) – Shubham Singh Jun 28 '16 at 06:34
  • Lemme come up with an other solution (Y) – Sanoop Surendran Jun 28 '16 at 06:35
  • and its `list2[position]` @SWARNVEERSINGH – Sanoop Surendran Jun 28 '16 at 06:37
  • you can switch by setting `list` and `list2` to null if either is used – Sanoop Surendran Jun 28 '16 at 06:38
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/115787/discussion-between-swarnveer-singh-and-sanoop). – Shubham Singh Jun 28 '16 at 06:41
0

I have used this link to answer your question, which might help you to do what you want: How to make an Android Spinner with initial text "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);
    }
 }
}

Change your Spinner in layout file with NoDefaultSpinner.For ex:

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

And this is your own class where set hint first to spinner and then change it when any item is selected as below:

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) {

    }
  });

}
}
Community
  • 1
  • 1
Dhruvi
  • 1,971
  • 2
  • 10
  • 18