简体   繁体   中英

Android - Spinner setting TextView visible/invisible

I'm trying to do my first Spinner , and I have encountered some difficulties, such as that I don't know if I can get an option by spinner.getSelectItem == "some string" .

Take a look at my code so far

Populating the spinner:

public void addItemsOnSpinner() {
    Spinner buttonSpinner = (Spinner) findViewById(R.id.buttonSpinner);
    List<String> list = new ArrayList<String>();
    list.add("Ultimos 5 lancamentos");
    list.add("Ultimos 7 lancamentos");
    list.add("Ultimos 10 lancamentos");
    ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, list);
    dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    buttonSpinner.setAdapter(dataAdapter);
}

Trying to make an if statement:

if(buttonSpinner.getSelectedItem().toString() == "Ultimos 10 lancamentos"){
    textView.setVisibility(View.VISIBLE);
}

TextView code as requested:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:text="Deposito"
    android:visibility="invisible"
    android:id="@+id/textView"
    android:layout_row="2"
    android:layout_column="0"
    android:layout_gravity="center|left" />                

And its code on the class:

TextView textView = (TextView)findViewById(R.id.textView);

是的,您可以做到,并且可以正常工作,但是请使用

buttonSpinner.getSelectedItem().toString().equals("Ultimos 10 lancamentos");

As Stefano has pointed out, your comparison should be using equals (which compares the String contents, vs == which compares the object references).

Otherwise your if statement should work, however its not clear where you are calling it from (and that might be the cause of the problem). If you want to make the comparison immediately after a spinner item is selected then you need to set an OnItemSelectedListener and make the comparison there.

Here is an example of how you might declare this listener inline:

buttonSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener()
{
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
    {
        String selectedItem = parent.getSelectedItem().toString();

        if (selectedItem.equals("Ultimos 10 lancamentos"))
        {
            textView.setVisibility(View.VISIBLE);
        }
    }

    public void onNothingSelected(AdapterView<?> parent)
    {
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM