一聚教程网:一个值得你收藏的教程网站

热门教程

Android Studio绑定下拉框数据详解

时间:2022-06-25 23:18:33 编辑:袖梨 来源:一聚教程网

效果显示:


1、页面xml代码(项目的代码,直接复制会有错,自己修改一下就好)





2、java创建自定义参数

Spinner consultation_et_section;//挂号科室:

3、获取选择控件(Spinner)

consultation_et_section = (Spinner) findViewById(R.id.consultation_et_section);

4、获取JSON数据和绑定数据,可以参考前一篇文章

(1)、创建自定义参数

List listMemDoctorData = null;

(2)、获取数据和绑定数据

/**
 * 获取JSON医生信息数据
 */
public void findDoctorData(int sectionId){
 AsyncHttpClient client = new AsyncHttpClient();
 client.get(AbAppConfig.DATA_URL + "appGVConsultation/findDoctorData?sectionId="+sectionId, null, new AsyncHttpResponseHandler() {
  @Override
  public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
   try {
    JSONObject object = new JSONObject(new String(responseBody));//获取json数据
    JSONArray jsonArray = object.getJSONArray("obj");//获取数据集名称为obj的数据
    Log.d("jsonArray数据输出:", String.valueOf(jsonArray));
    listMemDoctor = new ArrayList<>();
    for (int i = 0; i < jsonArray.length();i++) {
     MemDoctor doctor = MemDoctor.doctorData(jsonArray.getJSONObject(i));//把数据存在novels集合中
     if (doctor != null){
      listMemDoctor.add(doctor);
     }
    }

    if (jsonArray.length() > 0){
     listMemDoctorData = new ArrayList<>();
     doctor_id = listMemDoctor.get(0).id;//获取第一个医生的ID
     for (int i = 0; i < listMemDoctor.size(); i++){
      MemDoctor section = listMemDoctor.get(i);
      listMemDoctorData.add(section.doctorName);
     }

     //建立 Adapter并且绑定数据源
     ArrayAdapter arrayAdapter = new ArrayAdapter<>(GV_Consultation.this, android.R.layout.simple_spinner_item, listMemDoctorData);
     //设置样式
     arrayAdapter.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
     //绑定 Adapter到控件
     consultation_et_doctor.setAdapter(arrayAdapter);
    }else {
     consultation_et_doctor.setAdapter(null);
     doctor_id = 0;
     Toast.makeText(GV_Consultation.this, "该科室没有医生信息数据", Toast.LENGTH_SHORT).show();
    }

   } catch (JSONException e) {
    Toast.makeText(GV_Consultation.this, "数据请求失败,请稍后重试", Toast.LENGTH_SHORT).show();
   }
  }

  @Override
  public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
   //请求失败的回调处理
   Toast.makeText(GV_Consultation.this, "请链接网络,稍后重试", Toast.LENGTH_SHORT).show();
  }
 });
}


5、创建点击事件

//医生选择点击事件
consultation_et_doctor.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
 @Override
 public void onItemSelected(AdapterView parent, View view, int pos, long id) {
 doctor_id = listMemDoctor.get((int) id).id;//获取选择医生的ID
 }
 @Override
 public void onNothingSelected(AdapterView parent) {
 }
});

热门栏目