如何根据微调器选择在 edittext 中设置值?

how to set values in edittext as per spinner selection?

我有以下回复,

{
    "1": {
        "name": "abc",
        "mobile_number": "123456789",
        "address": "streetno3",
        "landmark": "landmarksss",

    },
    "2": {
        "name": "def",
        "mobile_number": "123456789",
        "address": "streetno3",
        "landmark": "landmarksss",

    },
    "3": {
        "name": "ghi",
        "mobile_number": "23423423234",
        "address": "abcdefgh",
        "landmark": "usa",

    },
    "4": {
        "name": "vvb",
        "mobile_number": "55666655",
        "address": "xvgghg",
        "landmark": "fghgh",

    },
    "5": {
        "name": "test",
        "mobile_number": "77699231010",
        "address": "pune",
       "landmark": "fghgh",
    }
}

我正在获取 spinner 中的所有名称,直到这里它工作正常,现在我尝试的是默认情况下我有 abc selected,如果我 select 从微调器测试那么我如何在我的 edittexts 中显示他的详细信息,简而言之,根据名称 selection 我正在尝试在 edittext

中获取和设置详细信息

Java代码

class LoadAllStates extends AsyncTask<String, String, ArrayList<String>> {
        private ProgressDialog pDialog;
        private String test;
        private String username;
        private String usermobile;
        private String useraddress;
        private String userlandmark;
        private String usercity;
        private String userstate;
        private String userpincode;
        private String useremail;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ShippingAddress.this.getActivity());
            pDialog.setMessage("Please wait..");
            pDialog.setIndeterminate(true);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        protected ArrayList<String> doInBackground(
                String... args) {
            ServiceHandler sh = new ServiceHandler();
            // Making a request to url and getting response
            statedata = new ArrayList<String>();
            dispdata= new ArrayList<String>();

            String jsonStr = sh.makeServiceCall(GET_ADDRESS_DETAIL, ServiceHandler.GET);
            Log.d("Response: ", "> " + jsonStr);
            if (jsonStr != null) {
                try {

                    jsonObj = new JSONObject(jsonStr);
                    for (int i = 1; i <= jsonObj.length(); i++) {

                        JSONObject user = jsonObj.getJSONObject(""+i);
                        username= (user.has("name")) ? user.getString("name") : null;

                        usermobile= (user.has("mobile_number")) ? user.getString("mobile_number") : null;
                        useraddress= (user.has("address")) ? user.getString("address") : null;
                        userlandmark= (user.has("landmark")) ? user.getString("landmark") : null;
                        usercity= (user.has("city")) ? user.getString("city") : null;
                        userstate= (user.has("state")) ? user.getString("state") : null;
                        userpincode= (user.has("pin_code")) ? user.getString("pin_code") : null;
                        useremail= (user.has("email")) ? user.getString("email") : null;


                        if(username!=null) statedata.add(username+","+usermobile);
                       /* if(username!=null) dispdata.add(username);

                        if(usermobile!=null) dispdata.add(usermobile);*/


                        Log.i("inner",user.toString());
                        }
                    System.out.println("WifeBday"+statedata.size());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }
            return statedata;
        }

        protected void onPostExecute(ArrayList<String> result) {
            super.onPostExecute(result);
            pDialog.dismiss();
            arrallstates = new String[statedata.size()]; // you can also use "result" array instead
            for (int index = 0; index < statedata.size(); index++) {
                arrallstates[index] = statedata.get(index);// or result.get(index);
            }
            // pass arrConuntry array to ArrayAdapter<String> constroctor :
            adapterallstates = new ArrayAdapter<String>(
                    ShippingAddress.this.getActivity(),
                    android.R.layout.simple_spinner_dropdown_item, arrallstates);
            System.out.println("adpttest"+adapterallstates);
            spiner.setAdapter(adapterallstates);

            spiner.setOnItemSelectedListener(new OnItemSelectedListener() {

                @Override
                public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                    // TODO Auto-generated method stub

                    /*String abc=statedata.get(position);
                    System.out.println("abc"+abc);*/
                      edtname.setText(username);
                        edtmobile.setText(usermobile);
                        edtlandmark.setText(userlandmark);
                        edtemail.setText(useremail);
                        edtcity.setText(usercity);
                        edtstate.setText(userstate);
                        edtaddress.setText(useraddress);
                        edtpincode.setText(userpincode);
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                    // TODO Auto-generated method stub

                }
            });

        }
        }

你有两个选择

1.Create 自定义微调适配器,如下例

CustomAdapter.java

 /***** Adapter class extends with ArrayAdapter ******/
public class CustomAdapter extends ArrayAdapter<String>{

    private Activity activity;
    private ArrayList data;
    public Resources res;
    SpinnerModel tempValues=null;
    LayoutInflater inflater;

    /*************  CustomAdapter Constructor *****************/
    public CustomAdapter(
                          CustomSpinner activitySpinner, 
                          int textViewResourceId,   
                          ArrayList objects,
                          Resources resLocal
                         ) 
     {
        super(activitySpinner, textViewResourceId, objects);

        /********** Take passed values **********/
        activity = activitySpinner;
        data     = objects;
        res      = resLocal;

        /***********  Layout inflator to call external xml layout () **********************/
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

      }

    @Override
    public View getDropDownView(int position, View convertView,ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return getCustomView(position, convertView, parent);
    }

    // This funtion called for each row ( Called data.size() times )
    public View getCustomView(int position, View convertView, ViewGroup parent) {

        /********** Inflate spinner_rows.xml file for each row ( Defined below ) ************/
        View row = inflater.inflate(R.layout.spinner_rows, parent, false);

        /***** Get each Model object from Arraylist ********/
        tempValues = null;
        tempValues = (SpinnerModel) data.get(position);

        TextView label        = (TextView)row.findViewById(R.id.company);
        TextView sub          = (TextView)row.findViewById(R.id.sub);
        ImageView companyLogo = (ImageView)row.findViewById(R.id.image);

        if(position==0){

            // Default selected Spinner item 
            label.setText("Please select company");
            sub.setText("");
        }
        else
        {
            // Set values for spinner each row 
            label.setText(tempValues.getCompanyName());
            sub.setText(tempValues.getUrl());
            companyLogo.setImageResource(res.getIdentifier
                                         ("com.androidexample.customspinner:drawable/"
                                          + tempValues.getImage(),null,null));

        }   

        return row;
      }
 }

spinner_rows.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:orientation="vertical"
 android:padding="3dip"
>
    <ImageView
         android:id="@+id/image"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         />
    <TextView
         android:layout_toRightOf="@+id/image"
         android:padding="3dip"
         android:layout_marginTop="2dip"
         android:textColor="@drawable/red"
         android:textStyle="bold"
         android:id="@+id/company"
         android:layout_marginLeft="5dip"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"/>
     <TextView
         android:layout_toRightOf="@+id/image"
         android:padding="2dip"
         android:textColor="@drawable/darkgrey"
         android:layout_marginLeft="5dip"
         android:id="@+id/sub"
         android:layout_below="@+id/company"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"/>
</RelativeLayout>

SpinnerModel.java

public class SpinnerModel {

        private  String CompanyName="";
        private  String Image=""; 
        private  String Url="";

        /*********** Set Methods ******************/
        public void setCompanyName(String CompanyName)
        {
            this.CompanyName = CompanyName;
        }

        public void setImage(String Image)
        {
            this.Image = Image;
        }

        public void setUrl(String Url)
        {
            this.Url = Url;
        }

        /*********** Get Methods ****************/
        public String getCompanyName()
        {
            return this.CompanyName;
        }

        public String getImage()
        {
            return this.Image;
        }

        public String getUrl()
        {
            return this.Url;
        }   
  }

activity_custom_spinner.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:orientation="vertical"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent">

      <TextView
          android:paddingTop="20dip"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"/>

      <Spinner
          android:id="@+id/spinner"
          android:drawSelectorOnTop="true"
          android:prompt="@string/defaultText"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"

          />

      <TextView
          android:paddingTop="20dip"
          android:paddingLeft="20dip"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:id="@+id/output"
          />

  </LinearLayout>

CustomSpinner.java

public class CustomSpinner extends Activity {

    /**************  Intialize Variables *************/
    public  ArrayList<SpinnerModel> CustomListViewValuesArr = new ArrayList<SpinnerModel>();
    TextView output = null;
    CustomAdapter adapter;
    CustomSpinner activity = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_spinner);

        activity  = this;

        Spinner  SpinnerExample = (Spinner)findViewById(R.id.spinner);
        output                  = (TextView)findViewById(R.id.output);

        // Set data in arraylist
        setListData();

        // Resources passed to adapter to get image
        Resources res = getResources(); 

        // Create custom adapter object ( see below CustomAdapter.java )
        adapter = new CustomAdapter(activity, R.layout.spinner_rows, CustomListViewValuesArr,res);

        // Set adapter to spinner
        SpinnerExample.setAdapter(adapter);

        // Listener called when spinner item selected
        SpinnerExample.setOnItemSelectedListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View v, int position, long id) {
                // your code here

                // Get selected row data to show on screen
                String Company    = ((TextView) v.findViewById(R.id.company)).getText().toString();
                String CompanyUrl = ((TextView) v.findViewById(R.id.sub)).getText().toString();

                String OutputMsg = "Selected Company : \n\n"+Company+"\n"+CompanyUrl;
                output.setText(OutputMsg);

                Toast.makeText(
                        getApplicationContext(),OutputMsg, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parentView) {
                // your code here
            }

        });
    }

    /****** Function to set data in ArrayList *************/
    public void setListData()
    {

        // Now i have taken static values by loop.
        // For further inhancement we can take data by webservice / json / xml;

        for (int i = 0; i < 11; i++) {

            final SpinnerModel sched = new SpinnerModel();

              /******* Firstly take data in model object ******/
               sched.setCompanyName("Company "+i);
               sched.setImage("image"+i);
               sched.setUrl("http:\www."+i+".com");

            /******** Take Model Object in ArrayList **********/
            CustomListViewValuesArr.add(sched);
        }

    }

  }
  1. 创建一个 bean 类型数组列表并按照您在 arrallstates 中存储的相同顺序存储所有详细信息,在微调器的 onItemSelected 方法中您总是获得位置并且在两个数组列表中您具有相同的数据位置所以现在获取数据来自 bean 类型数组列表,然后根据需要进行设置

这种数据最好做成POJOclass,方便数据管理。但是,如果您还没有使用 POJO class,那么现在您可以从其位置获取微调器数据并将其拆分以在 EditText 中打印。

假设如果您在微调器中的 ItemSelected 上的 data 字符串中获取数据,您可以按照以下代码将其打印在 edittext 中。

String split[]=data.split(",");
String name=split[0];
String mobile=split[1];