Переменное количество textedits в алертиддиалоге в андроиде? - PullRequest
2 голосов
/ 09 октября 2011

Можно ли установить переменное количество текстовых сообщений в alerttdialog? Я попытался динамически заполнить некоторые виды контейнера, такие как StackView или LinearLayout, но говорят, что метод addView не поддерживается в AdapterView (исключение). Какое решение?
Добавлено:
Я хочу построить алертилдиалог из динамической информации.

AlertDialog.Builder alert = new AlertDialog.Builder(context);

Теперь я могу настроить его вид так:

alert.setView(v);

но элемент v может быть только чем-то простым, например TextView или EditText. Что, если я хочу создать контейнерное представление, которое может содержать переменное количество элементов, например, 2 textviews и 3 edittexts? Как я могу это сделать? Теперь я просто создаю отдельный файл макета и раздуваю представление, но это не решение. Что я могу сделать?

Ответы [ 5 ]

0 голосов
/ 19 октября 2011

Самый простой способ - динамически раздувать представления. В вашем методе создания диалогов введите этот код для построения диалога:

AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Some title");
ViewGroup final mainLayout = getLayoutInflater().inflate(R.layout.the_custom_holder);
final EditText[] editors = new EditText[requiredItemCount];
for (int i = 0; i < requiredItemCount; i++) {
   View inputter = getLayoutInflater().inflate(R.layout.the_custom_line);
   editors[i] = inputter.findViewById(R.id.editorId);
}

alert.setPositiveButton(R.string.stringHelptextButtonOK,
   new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dialog, int whichButton) {
      // Accessing one of the edittexts
      String requiredText = editors[3].getText().toString();
      // TODO Do stuff with result
   }
alert.setView(mDlgLayout);
alert.create().show();
0 голосов
/ 19 октября 2011

вот ссылка ниже для статического макета диалогового окна

http://knol.google.com/k/thiyagaraaj-m-p/custom-dialog-box-popup-using-layout-in/1lfp8o9xxpx13/171#

если вы хотите добавить динамический макет или отредактировать существующий макет, вы можете получить его методом

RelativeLayout myMainLayout= (RelativeLayout)myDialog.findViewById(R.id.myMainLayout);

и добавьте представление по вашему выбору в основной макет, создав его в java и используя метод addView ().

myMainLayout.addView(yourChildView);
0 голосов
/ 12 октября 2011

Меняется ли число EditTexts, когда пользователь просматривает диалоговое окно, или к тому времени это число будет фиксированным?Если он фиксированный и время от времени меняется, вы можете создать собственный XML-макет для каждого из них, а затем с помощью оператора switch решить, какой XML-макет вы хотите отобразить в диалоговом окне.

ПользовательскийДиалоговое окно предупреждения может отображаться с этим кодом:

// This example shows how to add a custom layout to an AlertDialog
            LayoutInflater factory = LayoutInflater.from(this);
            final View textEntryView = factory.inflate(
                    R.layout.helpdialog_main, null);
            return new AlertDialog.Builder(Main.this)
                    .setView(textEntryView)
                    .setPositiveButton(R.string.stringHelptextButtonOK,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int whichButton) {

                                    // Popup is closed automatically, nothing
                                    // needs to be done here
                                }
                            }).create();
0 голосов
/ 12 октября 2011

Добавление LinearLayout должно работать очень хорошо:

В #onCreate(Bundle):

...
...
/*LinearLayout*/ mDlgLayout = new LinearLayout(this);
mDlgLayout.setOrientation(LinearLayout.VERTICAL);

AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Some title");
alert.setView(mDlgLayout);
alert.setNeutralButton("Regenerate", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dlg, int which) {
            // onClick will dismiss the dialog, just posting delayed
            // to pop up the dialog again & change the layout.
            mDlgLayout.postDelayed(new Runnable() {
                    public void run() {
                        alterDlgLayout();
                    }
                }, 200L);
        }
    });
/*AlertDialog*/ mDlg = alert.create();
...
...

В #alterDlgLayout()

void alterDlgLayout() {
    mDlgLayout.removeAllViews();
    Random rnd = new Random(System.currentTimeMillis());
    int n = rnd.nextInt(3) + 1;
    for (int i = 0; i < n; i++) {
        EditText txt = new EditText(this);
        txt.setHint("Some hint" + rnd.nextInt(100));
        mDlgLayout.addView(txt);
    }
    mDlgLayout.invalidate();
    mDlg.show();
}

В #onResume()

alterDlgLayout();

In #onPause()

mDlg.dismiss();
0 голосов
/ 12 октября 2011

Зачем вам нужно переменное число TextView с?Вы можете использовать одну для отображения нескольких строк.Если вам нужно что-то более сложное, вы можете создать свое собственное диалоговое действие с темой @android:style/Theme.Dialog, ограничив его размеры, чтобы оно не охватывало всю область отображения.

Обновление:

Вот пример того, как сделать диалоговую подобную активность:

:: ComplexDialog.java

public class ComplexDialog extends Activity {
    ...regular Activity stuff...

    protected void onCreate(Bundle savedInstanceState) {
        ...get extras from the intent, set up the layout, handle input, etc...

        LinearLayout dialogLayout = (LinearLayout) findViewById(R.id.dialogLayout);
        Display display = getWindowManager().getDefaultDisplay();
        int width = display.getWidth() > 640 ? 640 : (int) (display.getWidth() * 0.80);
        dialogLayout.setMinimumWidth(width);
        dialogLayout.invalidate();

        ...more regular stuff...
};

:: AndroidManifest.xml

<activity android:name=".ComplexDialog" android:theme="@android:style/Theme.Dialog"></activity>
...