简体   繁体   中英

I am working on android and i am finding difficulty on validating spinner items and adding value for spinner items

hello i am working on android and i am finding difficulty on validating spinner items and adding value for the spinner items i will show u the code as following .

This code is the UI section code.

<TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:text="@string/fa_star"
                android:textColor="#97c740"
                android:layout_marginRight="10dp"
                android:id="@+id/choosehotel"
                android:textSize="20dp"
                android:layout_marginTop="13dp"
                android:layout_weight="1" />

            <Spinner
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:inputType="text"
                android:hint="Choose your hotel"
                android:layout_marginTop="13dp"
                android:ems="10"
                android:textSize="25dp"
                android:fontFamily="sans-serif"
                android:id="@+id/hotelpreferance"
                android:layout_weight="15"

                android:singleLine="true" />
            <TextView
                android:id="@+id/text0"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content" />

the following is the java section code

this is the code where array adapter is used have changed the code a bit

public void spinnerdata(){

 hotelpref = (Spinner)findViewById(R.id.hotelpreferance);


   MyClass[] obj2 ={

            new MyClass("No Preference", ""),
            new MyClass("2 star", "2"),
            new MyClass("3 star", "3"),
            new MyClass("4 star", "4"),
            new MyClass("5 star", "5")

    };


    hoteladapter = new SpinAdapter(this ,R.id.spinneritem,obj2 );
    hoteladapter.setDropDownViewResource(R.layout.spinner_items);
    hotelpref.setAdapter(hoteladapter);
    hotelpref.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {


            Toast.makeText(getBaseContext() ,parent.getItemIdAtPosition(position)+"selected", Toast.LENGTH_LONG).show();

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

}

Following is the code to set the value and the text and set the value for each text have changed this code just have created two classes by name MyClass and SpinAdapter

class MyClass{

    private String text;
    private String value;


    public MyClass(String text, String value){
        this.text = text;
        this.value = value;
    }

    public void setText(String text){
        this.text = text;
    }

    public String getText(){
        return this.text;
    }

    public void setValue(String value){
        this.value = value;
    }

    public String getValue(){
        return this.value;
    }

     @Override
     public String toString() {
         return this.text;
     }
 }



 class SpinAdapter extends ArrayAdapter<MyClass>{

    // Your sent context
    private Context context;
    // Your custom values for the spinner (User)
    private MyClass[] values;

    public SpinAdapter(Context context, int textViewResourceId,
                       MyClass[] values) {
        super(context, R.layout.spinner_items, textViewResourceId, values);
        this.context = context;
        this.values = values;
    }

    public int getCount(){
        return values.length;
    }

    public MyClass getItem(int position){
        return values[position];
    }

    public long getItemId(int position){
        return position;
    }


    // And the "magic" goes here
    // This is for the "passive" state of the spinner
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // I created a dynamic TextView here, but you can reference your own  custom layout for each spinner item
        TextView label = new TextView(context);
        label.setTextColor(Color.BLACK);
        // Then you can get the current item using the values array (Users array) and the current position
        // You can NOW reference each method you has created in your bean object (User class)
        label.setText(values[position].getText());

        // And finally return your dynamic (or custom) view for each spinner item
        return label;
    }

    // And here is when the "chooser" is popped up
    // Normally is the same view, but you can customize it if you want
    @Override
    public View getDropDownView(int position, View convertView,
                                ViewGroup parent) {
        TextView label = new TextView(context);
        label.setTextColor(Color.BLACK);
        label.setText(values[position].getText());

        return label;
    }

Also have a validation code this code is on button click.

 if(hoteladapter != null){
                String text = ((MyClass)hoteladapter.getItem(hotelpref.getSelectedItemPosition())).getValue();
                if(text.trim().length() == 0){
                    ((TextView)( (LinearLayout)hotelpref.getSelectedView()).findViewById(R.id.spinneritem)).setError("sada");
                }
            }

Few change's has been made in this code but cant figure out whats the main problem is not actually getting the validation happening at desired place . I should again describe you what i am suppose to do .

I want to add validation in this spinner on submit button click so that form the selected items the first item as" No preference " as it has no value or value "0" if it is selected one should get an error message as "please select an item "

Inside your onItemSelectedListener, use this:

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    MyClass myClass = (MyClass) parent.getItemAtPosition(position);
// Validate your spinner values here:
int value = myClass.getValue();
String text = myClass.getText();
                }

I would suggest, that you use an ArrayList over an array of your MyClass. Something like:

ArrayList<MyClass> myClassList = new ArrayList<MyClass>();

and then, create MyClass objects where ever you want, and add them to the array list.

MyClass myClass = new MyClass("2 star", 1);
myClassList.add(myClass);

This would be a cleaner approach. Hope this helps....

okay, so on your submit button click:

btnSubmit.setOnClickListener(new View.OnClickListener() {


                @Override
                public void onClick(View v) {

int pos = spinner.getSelectedItemPosition();
MyClass myClass = (MyClass)spinner.getAdapter().getItem(pos);
if(myClass.getValue() == 0){
// Your toast msg here
}


 }
            });

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