Как использовать Spinner внутри AlertDialog.builder? - PullRequest
3 голосов
/ 16 ноября 2011

ОБНОВЛЕНО:
Привет, я использую счетчик в AlertDialog.Builder, чтобы показать список опций для выбора.Но spinner показывает только первый элемент String array, когда не нажата кнопка.Если щелкнуть, показывается принудительное закрытие.Мой код ниже.

AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater li=LayoutInflater.from(this);
View v=li.inflate(R.layout.searchme, null);
builder.setIcon(android.R.drawable.ic_input_get);
builder.setView(v);

builder.setTitle("Search");
LayoutInflater factory = LayoutInflater.from(getApplicationContext());
final View textEntryView = factory.inflate(R.layout.searchme, null);
builder.setView(textEntryView);
Spinner spin=(Spinner)textEntryView.findViewById(R.id.searchspinner);

    Utilities.ManageDeptSpinner(this, spin);

    for(int i=0;i<spin.getCount();i++)
    {
        long id=spin.getItemIdAtPosition(i);

            spin.setSelection(i, true);
            break;
    }
    spin.setOnItemSelectedListener(new MyOnItemSelectedListener());

    builder.setPositiveButton("Go",new DialogInterface.OnClickListener() 
    {       
        public void onClick(DialogInterface dialog, int id) 
        {
            try
            {
                titletext = (EditText) textEntryView.findViewById(R.id.titleText1);
                persontext = (EditText) textEntryView.findViewById(R.id.personText2);
                prioritytext = (EditText) textEntryView.findViewById(R.id.priorityText3);

                title_text = titletext.getText().toString();
                person_text = persontext.getText().toString();
                priority_text = prioritytext.getText().toString();

                String condition = "titlee='"+title_text+"' or pname ='"+person_text+"' or prior='"+priority_text+"'";
                refresh_data(" ASC","prior",condition);
            }
            catch(Exception e)
            {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
            }
    }});

    builder.setNegativeButton("Cancel",new DialogInterface.OnClickListener() 
    {       
        public void onClick(DialogInterface dialog, int id) 
        {
            dialog.cancel();
                // Do nothing
        }   
    });

    AlertDialog alert = builder.create();
    alert.show();

MyOnItemSelectedListener.java:

public class MyOnItemSelectedListener implements OnItemSelectedListener 
{
    @SuppressWarnings("unused")
    public void onItemSelected(AdapterView<?> parent,View view, int pos, long id) 
    {
    try
        {
        switch(parent.getId())
        {
            case R.id.searchspinner:
                Toast.makeText(getApplicationContext(),"\n Selected : "+parent.getItemAtPosition(pos).toString()+"\n",Toast.LENGTH_LONG).show();
                break;
        }
        }catch(Exception e)
        {
            e.printStackTrace();
        }
    }
    public void onNothingSelected(AdapterView<?> parent) 
    {
            //  Do nothing.
    }
}

Я получаю исключение следующим образом:

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application

Мой вывод:

enter image description here

Если я нажму на этот счетчик, произойдет принудительное закрытие.

Любая помощь будет высоко оценена и заранее спасибо

Ответы [ 3 ]

2 голосов
/ 16 ноября 2011

попробуйте использовать ClassName.this вместо getApplicationContext() при объявлении LayoutInflator.

1 голос
/ 16 ноября 2011

Я думаю, что вы используете плохой контекст, попробуйте использовать правильный контекст.

LayoutInflater factory = LayoutInflater.from(getApplicationContext());

вместо getApplicationContext() попробуйте Activity_name.this or getParent();

0 голосов
/ 16 ноября 2011

до этого builder.setView (v); вызывается дважды, чтобы удалить ненужного.

Ошибка должна быть в new MyOnItemSelectedListener() или в xml, где вы устанавливаете записи.

поделитесь кодом для обоих и errorlog.

...