1
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Spinner s = new Spinner(this);

        RelativeLayout rl = (RelativeLayout) 
        findViewById(R.id.activity_main);

        String ss[] = {"--Select Item--", "Item1", "Item2", "Item3", 
                       "Item4", "Item5"};

        ArrayAdapter<String> ad = new ArrayAdapter<String>(this, 
                           android.R.layout.simple_dropdown_item_1line, ss);

        s.setAdapter(ad);


        rl.addView(s);


        s.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {

                TextView t = (TextView) v;
                Toast.makeText(MainActivity.this, t.getText().toString(), 
                               Toast.LENGTH_SHORT).show();
                return true;
            }
        });
}

}

When i am long pressing on an item in spinner I am not getting any Toast which should come as the code specifies it so above. Also, when long pressing the spinner itself (not the item in the dropdown list in the spinner) then the app is crashing. Why is that so?

Edit 1:

s.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                TextView t = (TextView) view;
                Toast.makeText(MainActivity.this, t.getText().toString(), Toast.LENGTH_SHORT).show();
                return true;
            }
        });

When using setOnItemLongClickListener instead of setOnLongClickListener then when long pressing an item in dropdown list of spinner should generate a toast but it is not giving so?

Ankit Srivastava
  • 135
  • 4
  • 11

1 Answers1

0

The longClickListener is set on a Spinner class and you are casting that view to a TextView inside the listener. That is why the app crashes.

Spinner.setOnLongClickListener is not the listener for each of the adapter items.

What you are looking for is Spinner.setOnItemSelectedListener(new OnItemSelectedListener())

Robert Estivill
  • 12,369
  • 8
  • 43
  • 64
  • one more doubt that when I am using setOnItemLongClickListener() thn it should give Toast when I long press on spinner item but it is not coming. I am adding that code in an edit.Please clarify that too.Thanks in advance – Ankit Srivastava Jul 06 '17 at 15:16