我正在尝试做我的第一个Spinner,但遇到了一些困难,例如,我不知道是否可以通过spinner.getSelectItem == "some string"获得选择。

看到目前为止我的代码

填充微调器:

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);
}


试图做一个if语句:

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


要求的TextView代码:

<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" />


及其在类上的代码:

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

最佳答案

正如Stefano所指出的,您的比较应该使用equals(比较String的内容,而==比较对象的引用)。

否则,您的if语句应该可以工作,但是不清楚从何处调用它(这可能是问题的原因)。如果要在选择微调项之后立即进行比较,则需要设置一个OnItemSelectedListener并在那里进行比较。

这是如何内联声明此侦听器的示例:

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

10-07 19:23
查看更多