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

时间:2013-11-27 21:43:46

标签: android dialog android-spinner android-alertdialog

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

一张图片:

enter image description here

任何人都知道任何可能出现的下拉列表?

4 个答案:

答案 0 :(得分:2)

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

enter image description here

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) {

        }
    });
}

答案 1 :(得分:0)

将其移至代码的末尾,因此您在设置完所有内容后执行此操作:

builder.show();

答案 2 :(得分: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布局虚增为警告对话框。确保使用上下文对话框获取每个微调器。请参阅上面的代码。

希望它有所帮助。干杯!

答案 3 :(得分:0)

由于内存泄漏,发生这种情况,当你打开一个微调器时,它能够获得有效的上下文,但是当你第二次尝试检索另一个微调器时,它实际上正在获取{ {1}}作为上下文而不填充任何内容。但是当您在null中使用Activity中的微调器时,它实际上总是得到Alert-Dialog。因此,在那段时间内,您没有收到任何错误,并且填充正确。

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

getApplicationContext()