【问题标题】:Can't show Spinner DropDown list inside AlertDialog - Android无法在 AlertDialog 中显示 Spinner DropDown 列表 - Android
【发布时间】:2013-11-27 21:43:46
【问题描述】:

我在 AlertDialog 中有两个微调器,微调器看起来不错,并且项目列表是正确的,它显示了每个列表的第一个项目。但是当我单击两个微调器中的任何一个时,不会显示下拉列表以选择其他项目。纺纱厂什么都不做。当我是 AlertDialog 之外的两个微调器时,不会发生这种情况。

这是AlertDialog的代码:

private void mostrar_alertdialog_spinners() {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        TextView title = new TextView(this);
        title.setText("Selecciona un archivo:");
        title.setPadding(10, 10, 10, 10);
        title.setGravity(Gravity.CENTER);
        title.setTextColor(Color.rgb(0, 153, 204));
        title.setTextSize(23);
        builder.setCustomTitle(title);

        LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View layout_spinners = inflater.inflate(R.layout.layout_spinners,null);
        sp_titulos_carpetas = (Spinner) layout_spinners.findViewById(R.id.spinner_titulo_carpetas);
        sp_titulos_textos = (Spinner) layout_spinners.findViewById(R.id.spinner_textos_carpetas);

        builder.setView(layout_spinners);
        builder.setCancelable(false);
        builder.show();

        //configuracion de textos en memoria sd
        String path = Environment.getExternalStorageDirectory().toString()+"/Textos/";
        File f = new File(path);
        String[] fileStr = f.list();
        ArrayList<String> lista_lista_CARPETAS = new ArrayList<String>();
        for (String lista_texto : fileStr) {
            lista_lista_CARPETAS.add(lista_texto);
        }
        Collections.sort(lista_lista_CARPETAS, new AlphanumComparator());

        String[] lista_k = f.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                File f = new File(dir, name);
                return f.isDirectory();
            }
        });
        FileFilter fileFilter = new FileFilter() {
            public boolean accept(File file) {
                return file.isDirectory();
            }
        };
        File[] files = f.listFiles(fileFilter);

        ArrayAdapter<String> carpetas = new ArrayAdapter<String>(this,   android.R.layout.simple_spinner_item, lista_k);
        carpetas.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
        sp_titulos_carpetas.setAdapter(carpetas);

        //ARRAY CON TITULOS DE ARCHIVOS TXT
        String camino = Environment.getExternalStorageDirectory().toString()+"/Textos/" + "Naxos"+ "/";
        File t = new File(camino);
        String[] lista_textos = t.list();
        ArrayList<String> lista_lista_textos = new ArrayList<String>();
        for (String lista_texto : lista_textos) {
            if (lista_texto.toLowerCase().endsWith(".txt")) {
                lista_lista_textos.add(lista_texto);
            }
        }
        for (int index =0; index < lista_lista_textos.size(); index++){
            lista_lista_textos.set(index, WordUtils.capitalizeFully(lista_textos[index].toLowerCase().replace(".txt", "")));
        }
        Collections.sort(lista_lista_textos, new AlphanumComparator());

        ArrayAdapter<String> adaptador_textos = new ArrayAdapter<String>(this,   android.R.layout.simple_spinner_item, lista_lista_textos);
        adaptador_textos.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
        sp_titulos_textos.setAdapter(adaptador_textos);
        sp_titulos_textos.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String nombre_texto = parent.getSelectedItem().toString();
                File sdcard = new File( Environment.getExternalStorageDirectory().toString()+"/Textos/" + "Naxos/");

                //Get the text file
                File file = new File(sdcard, nombre_texto);

                //Read text from file
                StringBuilder text = new StringBuilder();

                int BUFFER_SIZE = 8192;

                try {
                    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "Cp1252"),BUFFER_SIZE);
                    String line;

                    while ((line = br.readLine()) != null) {
                        text.append(line);
                        text.append('\n');
                    }
                }
                catch (IOException e) {
                    //You'll need to add proper error handling here
                }
                String nuevoTexto = text.toString().replaceAll("\t", " ");
                String nuevoTextoA = nuevoTexto.replaceAll("\n", " ");
                Holmes1 = nuevoTextoA;
                delimitadores = " ";
                tokenHolmes1 = new StringTokenizer(Holmes1, " ");
                arrayHolmes1 = Holmes1.split(delimitadores);

            }

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

            }
        });
    }

还有微调器的 xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:weightSum="100"
    style="@style/spinner_rojo">
    <Spinner
        android:id="@+id/spinner_titulo_carpetas"
        android:layout_width="0dp"
        style="@style/spinner_rojo"
        android:background="@drawable/spinner_background_holo_light"
        android:layout_height="wrap_content"
        android:layout_weight="50"></Spinner>

    <Spinner
        android:id="@+id/spinner_textos_carpetas"
        android:layout_width="0dp"
        style="@style/spinner_rojo"

        android:background="@drawable/spinner_background_holo_light"
        android:layout_height="wrap_content"
        android:layout_weight="50"></Spinner>

</LinearLayout>

还有一张图片:

有人知道显示下拉列表的任何可能的问题吗?

【问题讨论】:

  • 据我了解,您的问题是微调器无法显示它的下拉选择以选择另一个选项,对吗?我刚刚复制了你的代码,对我来说效果很好。你怎么了?

标签: android dialog android-spinner android-alertdialog


【解决方案1】:

我刚刚复制了您的代码并编辑了 ArrayList。它完全适合我。

private void mostrar_alertdialog_spinners() {

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    TextView title = new TextView(this);
    title.setText("Selecciona un archivo:");
    title.setPadding(10, 10, 10, 10);
    title.setGravity(Gravity.CENTER);
    title.setTextColor(Color.rgb(0, 153, 204));
    title.setTextSize(23);
    builder.setCustomTitle(title);

    LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View layout_spinners = inflater.inflate(R.layout.spinner_layout,null);
    Spinner sp_titulos_carpetas = (Spinner) layout_spinners.findViewById(R.id.spinner_titulo_carpetas);
    Spinner sp_titulos_textos = (Spinner) layout_spinners.findViewById(R.id.spinner_textos_carpetas);

    builder.setView(layout_spinners);
    builder.setCancelable(false);
    builder.show();


    ArrayList<String> lista_k = new ArrayList<String>();
    lista_k.add("Path A");
    lista_k.add("Path B");

    ArrayAdapter<String> carpetas = new ArrayAdapter<String>(this,   android.R.layout.simple_spinner_item, lista_k);
    carpetas.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
    sp_titulos_carpetas.setAdapter(carpetas);



    ArrayList<String> lista_lista_textos = new ArrayList<String>();
    lista_lista_textos.add("Path C");
    lista_lista_textos.add("Path D");

    ArrayAdapter<String> adaptador_textos = new ArrayAdapter<String>(this,   android.R.layout.simple_spinner_item, lista_lista_textos);
    adaptador_textos.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
    sp_titulos_textos.setAdapter(adaptador_textos);
    sp_titulos_textos.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        }

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

        }
    });
}

【讨论】:

    【解决方案2】:

    将此移至代码末尾,以便在设置完所有内容后执行此操作:

    builder.show();
    

    【讨论】:

      【解决方案3】:

      为此创建自定义警报对话框。试试这个

      Dialog new_dialog = new Dialog(getParent());                                                            
      // new_dialog.setTitle("Book your appointment");
      new_dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
      new_dialog.setContentView(R.layout.customize_dialog_list_view);
      new_dialog.setCancelable(false);
      cuc = new CommanUtilityClass();
      SharedPreferences sp = getSharedPreferences("provider",0);
      String services = sp.getString("services",  "");
      TextView service = (TextView) new_dialog
              .findViewById(R.id.cdlv_service_provider);
      TextView hour = (TextView) new_dialog.findViewById(R.id.cdlv_working_hours);
      TextView appointment_time = (TextView) new_dialog.findViewById(R.id.cdlv_appoint_time);
      TextView appointment_date = (TextView) new_dialog.findViewById(R.id.cdlv_appoint_date);
      //String[] ampm = myTiming[which].split(":");
      /*String[] range = myTiming[which].split(":");
      int startTimeInt = Integer.parseInt(range[0])
              * 60 + Integer.parseInt(range[1]);
      String finalvalue = "";
      if(startTimeInt >= 720){
           if(startTimeInt >= 780){
      
           }else{
      
           }
      }else{
          finalvalue = String.valueOf(range[0] + ":" + range[1] + " AM");
      }
      
      for (int i = 0; i < range.length; i++) {
          String startTimeString = range[i].split("-")[0];
          String endTimeString = range[i].split("-")[1];
          Log.d("Minutes", "startTimeString = " + startTimeString);
          Log.d("Minutes", "endTimeString = " + endTimeString);
          int startTimeInt = Integer.parseInt(startTimeString.split(":")[0])
                  * 60 + Integer.parseInt(startTimeString.split(":")[1]);
          int endTimeInt = Integer.parseInt(endTimeString.split(":")[0]) * 60
                  + Integer.parseInt(endTimeString.split(":")[1]);
      
      
      }*/
      
      
      appointment_time.setText(Html.fromHtml("<b>Appointment time :</b>" + myTimingToShow[which].split("/")[0]));
      appointment_date.setText(Html.fromHtml("<b>Appointment date :</b>" + selected));
      
      service.setText(Html
              .fromHtml("<b>Service provider :</b>"
                      + cuc.toTheUpperCase(bsp_name)));
      
      hour.setText(Html
              .fromHtml("<b>Working hours :</b>"
                      + cuc.toTheUpperCase(bsp_availability)));
      
      try {
          lv = (ListView) new_dialog
                  .findViewById(R.id.cdlv_list);
      
          CustomDialogArrayAdapter cdaa = new CustomDialogArrayAdapter(
                  getApplicationContext(),
                  m_ArrayList);
      
          lv.setAdapter(cdaa);
      } catch (Exception e) {
          e.printStackTrace();
      }
        new_dialog.show();
      

      在这里,我刚刚将 xml 布局膨胀为警报对话框。确保将每个带有上下文的微调器获取到对话框。参见上面的代码。

      希望对您有所帮助。干杯!

      【讨论】:

        【解决方案4】:

        由于 内存泄漏,发生这种情况,当您打开一个微调器时,它能够获取有效的上下文,但是当您第二次尝试检索另一个微调器时,它实际上得到了 @ 987654321@ 作为上下文,不填充任何内容。但是,当您同时使用ActivityAlert-Dialog 中的微调器时,它实际上总是得到valid context。因此,在那个时候,您没有收到任何错误,并且它会正确填充。

        因此,为避免内存泄漏,请使用getApplicationContext() 检索微调器 ArrayAdapter 的上下文

        ArrayAdapter<String> carpetas = new ArrayAdapter<String>
               (getApplicationContext(),android.R.layout.simple_spinner_item, lista_k);
        
        
        ArrayAdapter<String> adaptador_textos = new ArrayAdapter<String>
              (getApplicationContext(),android.R.layout.simple_spinner_item, lista_lista_textos);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-09-02
          • 1970-01-01
          相关资源
          最近更新 更多