Android - How To Display A Spinner With Value But Display A Different One
For my Android app, I need to use a spinner which displays a XML tree. This tree is necesarry for the user to understand the level of the value he can select. Here is a picture of
Solution 1:
you can do this with the idea that
make your spinner invisible put an textView behind the spinner set TextView text to spinner selected item with
textView.settext(spinner.getSelectedItem().replace(">","").trim()));
dont forget to put spinner over the textView otherwise you will not get spinner click event
Solution 2:
Here is the code I used if someone needs it:
First, replace your spinner by the folowing portion of code:
<RelativeLayoutandroid:layout_width="190dp"android:layout_height="40dp"android:layout_marginRight="5dp"><Spinnerandroid:id="@+id/spinner"android:layout_width="fill_parent"android:layout_height="fill_parent"android:background="@drawable/custom_spinner"android:visibility="invisible" /><Buttonandroid:id="@+id/fake_btn"android:layout_width="fill_parent"android:layout_height="fill_parent"android:background="@drawable/custom_spinner" /><TextViewandroid:id="@+id/fake_text"android:layout_width="140dp"android:layout_height="40dp"android:layout_marginLeft="10dp"android:gravity="center_vertical"android:textColor="#000000" /></RelativeLayout>
Create a new XML file in your drawable folder named custom_spinner.xml
and puts that code:
<?xml version="1.0" encoding="utf-8"?><selectorxmlns:android="http://schemas.android.com/apk/res/android"><itemandroid:state_focused="true"android:state_pressed="false"android:drawable="@drawable/spinner_pressed" /><itemandroid:state_focused="true"android:state_pressed="true"android:drawable="@drawable/spinner_pressed" /><itemandroid:state_focused="false"android:state_pressed="true"android:drawable="@drawable/spinner_pressed" /><itemandroid:drawable="@drawable/spinner_normal" /></selector>
Download those two pictures and add them into your drawable folder (spinner_pressed.9.png
and spinner_normal.9.png
):
In your activity, add the following variables:
private Spinner spinner;
private Button fake_btn;
private TextView fake_text;
In the onCreate method, add:
spinner = (Spinner) findViewById(R.id.spinner);
fake_btn = (Button) findViewById(R.id.fake_btn);
fake_text = (TextView) findViewById(R.id.fake_text);
fake_btn.setOnClickListener(newOnClickListener() {
publicvoidonClick(View v)
{
spinner.performClick();
}
});
spinner_manual.setOnItemSelectedListener(newAdapterView.OnItemSelectedListener() {
publicvoidonItemSelected(AdapterView parentView, View childView, int position, long id)
{
String value = (String) spinner.getItemAtPosition(position);
fake_text.setText(value);
}
publicvoidonNothingSelected(AdapterView parentView) {}
});
There you are, it should work.
Post a Comment for "Android - How To Display A Spinner With Value But Display A Different One"