Как добавить заголовок в пользовательский диалог? - PullRequest
6 голосов
/ 31 января 2011

Как я могу добавить заголовок в это настраиваемое диалоговое окно ??

enter image description here

Я пытался вот так

public void customDialog()
 {
  Dialog dialog=new Dialog(this);
  dialog.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
  dialog.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.string.app_name );
  dialog.setContentView(R.layout.dialog_submit);
  TextView edit_model=(TextView) dialog.findViewById(R.id.edit_model);
  edit_model.setText(android.os.Build.DEVICE);
  dialog.show();
 }//end of custom dialog function

Я пытался установить заголовок какэто тоже .. dialog.setTitle("Enter Details"); но это тоже не дало никакого результата.Так как же мне установить заголовок для этого настраиваемого диалогового окна ??

Это мой файл dialog_submit.xml, используемый для настраиваемого диалогового окна.

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/layout_root"
          android:orientation="vertical" 
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:padding="10dp"
          >
  <TextView android:id="@+id/txt_name"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:textColor="#FFF"
          android:text="Name"
          android:textStyle="bold"
          />
  <EditText android:id="@+id/edit_name"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:layout_below="@+id/txt_name"
          />
<TextView android:id="@+id/txt_model"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:textColor="#FFF"
          android:layout_below="@+id/edit_name"
          android:text="Phone Model"
          />
<TextView android:id="@+id/edit_model"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:layout_below="@+id/txt_model"
          />

<Button android:id="@+id/but_cancel"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_below="@+id/edit_model"
          android:text="Cancel"     
          />
<Button android:id="@+id/but_submit"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_below="@+id/edit_model"
          android:layout_toRightOf="@+id/but_cancel"    
          android:text="Submit"     
          />                       
</RelativeLayout>

Ответы [ 7 ]

16 голосов
/ 22 октября 2011

Используя часть вашего фрагмента:

public void customDialog() {
    Dialog dialog=new Dialog(this);
    dialog.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
    dialog.setContentView(R.layout.dialog_submit);
    dialog.getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
    dialog.show();
}

Рез / макет / custom_title.xml

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="This is a custom title"/>
3 голосов
/ 31 января 2011

Используя ваше определение макета и этот фрагмент кода:

public void customDialog()
{
    Dialog dialog = new Dialog( this );
    dialog.setContentView( R.layout.dialog_submit );
    TextView edit_model = (TextView) dialog.findViewById( R.id.edit_model );
    edit_model.setText( android.os.Build.DEVICE );
    dialog.setTitle( "Enter Details" );
    dialog.show( );
}


Я получаю этот диалог:

enter image description here


Итак, вы можете захотеть попробовать dialog.setTitle («Введите данные») снова.
Я использовал эмулятор под управлением Android 2.1.

3 голосов
/ 31 января 2011

Вы пробовали?

dialog.setTitle(R.string.app_name);
0 голосов
/ 09 июня 2017

Используйте эту строку, чтобы скрыть встроенный заголовок из диалога

dialog.requestWindowFeature (Window.FEATURE_NO_TITLE);

и добавьте textView в ваш файл макета .

0 голосов
/ 01 декабря 2014

Этот вопрос старый, но мое решение заключается в использовании относительной компоновки в основной относительной компоновке. Таким образом, вы можете создать свой собственный заголовок. Он не видит верхнего TextView в качестве заголовка, если вы используете его таким образом:

  <?xml version="1.0" encoding="utf-8"?>
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:orientation="vertical" 
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:padding="10dp"
      >
 <RelativeLayout
      android:id="@+id/layout_root"
      android:orientation="vertical" 
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      >
 <TextView android:id="@+id/txt_name"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textColor="#FFF"
      android:text="Name"
      android:textStyle="bold"
      />
 <EditText android:id="@+id/edit_name"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_below="@+id/txt_name"
      />
<TextView android:id="@+id/txt_model"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textColor="#FFF"
      android:layout_below="@+id/edit_name"
      android:text="Phone Model"
      />
 <TextView android:id="@+id/edit_model"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_below="@+id/txt_model"
      />

 <Button android:id="@+id/but_cancel"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@+id/edit_model"
      android:text="Cancel"     
      />
 <Button android:id="@+id/but_submit"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_below="@+id/edit_model"
      android:layout_toRightOf="@+id/but_cancel"    
      android:text="Submit"     
      />   
 </RelativeLayout>                    
 </RelativeLayout>

Кажется, это самый простой способ.

0 голосов
/ 23 августа 2013

Почему бы не использовать AlertDialog, если у вас 3 или менее кнопок?

Мой AlertDialog выглядит так:

enter image description here

Мой код Java:

LayoutInflater inflater = (LayoutInflater)getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.add_filter, null);

AlertDialog alertDialog = new AlertDialog.Builder(this)
        .create();
alertDialog.setTitle("AlertDialog title");
alertDialog.setMessage("AlertDialog message");
alertDialog.setView(view);
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,
                    int which) {
                dialog.dismiss();
            }
        });
alertDialog.show();

Мой XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical" >

    <Spinner
        android:id="@+id/spinner_filter"
        android:layout_width="wrap_content"
        android:spinnerMode="dropdown"
        android:layout_height="wrap_content"
        android:entries="@array/filter_array"
        android:prompt="@string/filter_prompt" />

</LinearLayout>

Простой, но делает то, что вам нужно.

0 голосов
/ 29 марта 2011

Что вы можете попробовать, если вам все еще нужен ответ, это AlertDialog.Builder Объект.В этом объекте вы также можете вызвать метод setMessage("Title"), который установит заголовок в Dialog, который вы в конечном итоге создадите с помощью него.Кроме того, вы также можете указать positiveButton, neutralButton и negativeButton (скажем, «Добавить», «ОК» и «Отмена» в этом порядке, хотя вы можете указать свой собственный текст).

Я считаю, что проблема заключается в том, что когда вы звоните Dialog dialog = new Dialog(this), вызывается onCreateDialog(int id).Но здесь есть одна загвоздка: этот метод вызывается один раз и выдает Dialog, который используется повторно, когда вам нужен новый Dialog.Однако Dialog больше нельзя редактировать (насколько я знаю).Ну, может быть, с помощью метода onPrepareDialog(int id, Dialog dialog), но я все еще пытаюсь заставить это работать самостоятельно.Я хочу сказать, что после создания вы больше не можете редактировать интерфейс пользователя в диалоге.Таким образом, способ, который работает, заключается в переопределении onCreateDialog(int id) в вашем коде, создании AlertDialog.Builder (или на чем вы основываете Dialog на: ProgressDialog / AlertDialog / etc.) И установке заголовка,макет и кнопки здесь.После этого вы можете вызвать метод create(), который на самом деле создаст Dialog с вашими настройками.

@Override
public dialog onCreateDialog(int id){
    // Create the View to use in the Dialog.
    LayoutInflater inflater = getLayoutInflater();
    // Inflate the View you want to set as the layout.
    final View layout = inflater.inflate(R.layout.your_dialog_layout,
                                         (ViewGroup) findViewById(R.id.your_parent_view);
    // Create Dialog Builder Object to create Dialog from.
    AlertDialog.Builder adBuilder = new AlertDialog.Builder(this);
    // Set the title to use.
    adBuilder.setMessage("Your title");
    // Add only a positive button.
    adBuilder.setPositiveButton("Add", new DialogInterface.OnClickListener(){
        @Override
        public void onClick(DialogInterface dialog, int which){
            // Handle click on positive button here.
        }
    };
    // Set the layout which you want to use (inflated at the beginning).
    adBuilder.setLayout(layout);
    // After you've set all the options you want to set, call this method.
    AlertDialog dialog = adBuilder.create();
    return dialog;
}

Это создаст Dialog с заголовком, установленным на "Your Title",который использует макет, который вы указали, и имеет одну кнопку с текстом «Добавить».Обратите внимание, что основное различие между положительными, нейтральными и отрицательными кнопками заключается в том, что их расположение на Dialog изменяется соответствующим образом (положительное = влево, нейтральное = среднее и отрицательное = правое).

Для получения дополнительной информации я бы посоветовалчтобы увидеть документацию об этом.

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