无法在AlertDialog中显示Spinner下拉列表 - Android

5
我在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>

并且有一张图片:

输入图像描述

是否有人知道如何解决显示下拉列表的问题?


据我所知,您的问题是下拉框无法显示其下拉选项以选择其他选项,对吗?我刚刚复制了您的代码,它在我的电脑上运行良好。你出了什么问题? - Thein
4个回答

2

我刚刚复制了你的代码并修改了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) {

        }
    });
}

0

为同一目的创建自定义警告对话框。请尝试此操作。

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布局膨胀到警报对话框中。确保您使用上下文获取每个旋转器以便于对话框。请参见上面的代码。

希望能有所帮助。干杯!


0
由于内存泄漏的发生,当您打开一个下拉框时,它能够获取有效的上下文,但第二次尝试检索另一个下拉框时,实际上会得到null作为上下文,并且不会填充任何内容。但是,当您在Alert-Dialog之外的Activity中使用这两个下拉框时,它总是获得有效的上下文。因此,在那个时间里,您不会遇到任何错误,并且它会正确地填充。
因此,为了避免内存泄漏,请使用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);

0
将此代码移至末尾,以便在设置完所有内容后再执行它:
builder.show();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接