John
John

Reputation: 127

Obtain Android Spinner ID

I just learned android studio a week ago, thus I'm sorry if I don't know much.

I'm writing a just-for-fun app which called "Sell-A-Planet". (not a school assignment I promise!)

My idea is to create a simple spinner that has list of planets (Earth, Mars, Jupiter), then a total price will be updated every time a user select different planet.

Unfortunately, I already had a problem with the spinner. Anyway, here's my code:

activity_main.xml

<Spinner
        android:id="@+id/planets_spinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

strings.xml

<resources>
  <string name="app_name">Spinner Practice</string>

  <string-array name="planets_array">
    <item> Mercury ($100 billion)</item>
    <item> Venus ($200 billion)</item>
    <item> Mars ($300 billion)</item>
  </string-array>
</resources>

Then I read from the android developer and another site, that I have to create new java class like this:

spinnerList.java

public class spinnerActivity implements OnItemSelectedListener {

     public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
         "OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
            Toast.LENGTH_SHORT).show();
     }

     public void onNothingSelected(AdapterView<?> parent) {
         // Another interface callback
     }
}

MainActivity.java

public void addListenerOnSpinnerItemSelection() {
     Spinner spinnerPlanet = (Spinner) findViewById(R.id.planets_spinner);
     spinnerPlanet.setOnItemSelectedListener(new spinnerActivity ());
}

At this stage, I'm trying to test whether the spinner works or not by printing the selected value using toast. However, it doesn't display anything whenever I changed the planet.

Can anyone please inform me why these don't work?

Furthermore, is it also possible (later on) that different planet will display different total price dynamically?

Thank you!

Upvotes: 0

Views: 94

Answers (2)

Android enthusiast
Android enthusiast

Reputation: 41

you should follow the following method to populate a spinner.First of all create spinner in Xml

 <Spinner
        android:id="@+id/spinnerplanet"
        android:layout_width="match_parent"
        android:layout_height="58dp"
        style="@style/spinner_style"
        android:spinnerMode="dropdown"/>

Then in Your MainActivity Uh should call the spinner through its id and then create an adapter for it.

        spinnerplanetshow= (Spinner) findViewById(R.id.spinnerplanet);

        adapterModule = new ArrayAdapter<String(getApplicationContext(), R.layout.spinner_item, your Array);

    spinnerplanetshow.setAdapter(adapterModule);

Now your array with planet names will be populated inside the spinner.Similarily populate another array with the prices and then you need to use OnItemSelected Listener and it will do your job of changing price according to selected planet.

    spinnerplanetshow.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view,
                                   int position, long id) {
            if (position == 0) {
       System.out.println("position is 0");
              //Set the string you want to show on click of first   position in spinner.


            } else if (position == 1) {
              System.out.println("position is 1");
    Toast.maketext(getApplicationContext,"position is 1",LENGTH.LONG).show();
             //Set the string you want to show on click of second position in spinner.  

This is the way you can achieve your desired result. }

Upvotes: 2

Sohail Zahid
Sohail Zahid

Reputation: 8149

Full working demo

MainActivity

public class MainActivity extends AppCompatActivity {

    private Context context;
    Spinner spinner;
    private TextView mTextView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;

        List<String> categories = new ArrayList<String>();
        categories.add("A");
        categories.add("B");
        categories.add("C");
        categories.add("D");

        mTextView = (TextView) findViewById(R.id.textView2);
        mTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "your selected id is  " + spinner.getSelectedItemId(), Toast.LENGTH_LONG).show();
            }
        });

        spinner = (Spinner) findViewById(R.id.spinner);
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(dataAdapter);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this, "you selected " + spinner.getSelectedItem(), Toast.LENGTH_LONG).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                Toast.makeText(MainActivity.this, "Nothing selected", Toast.LENGTH_LONG).show();
            }
        });
    }
}

activity_main

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/base"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:orientation="horizontal">


    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_margin="10dp"
        android:text="Click to get selected item"
        android:textSize="20dp" />

    <Spinner
        android:id="@+id/spinner"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView2"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

Upvotes: 1

Related Questions