2

Я использую этот код для отображения предупреждений DialogСделать AlertDialog Выборочная

holder.tv1.setOnClickListener(new View.OnClickListener() { 
        @Override 
        public void onClick(View v) { 
         AlertDialog.Builder nointernetconnection = new AlertDialog.Builder(
           temp); 
         nointernetconnection 
           .setIcon(R.drawable.ic_launcher) 
           .setTitle(list.get(position).getAS_name()) 
           .setMessage(list.get(position).getDesc_art()) 
           .setCancelable(true) 
           .setPositiveButton("OK", 
             new DialogInterface.OnClickListener() { 
                @Override 
              public void onClick(DialogInterface arg, 
                int arg1) { 



              } 
             }); 
         AlertDialog a = nointernetconnection.create(); 
         a.show(); 

enter image description here

Тело сообщения преобразуется в Scrollview автоматически в случае, если текст больше, но Текст заголовка не рассматривается полностью, ни пространство заголовка прокручивается.

Итак, я хочу развернуть область заголовка & также хочу, чтобы она прокручивалась & для этого я не хочу использовать пользовательский диалог, я хочу только реализовать его с помощью AlertDialog.

+1

использовать это с obj- setCustomTitle строителя (Посмотреть) – Manmohan

+2

http://stackoverflow.com/a/16923737/808940 – Merlin

+0

Смотрите комментарий Мерлина – SQLiteNoob

ответ

1

Этот пример некоторые, что типичный хак ... Вам не нужен пользовательский View также ...

private void showDialog() { 
    AlertDialog.Builder builder = new AlertDialog.Builder(this); 
    builder.setIcon(R.drawable.ic_launcher); 
    final String title = "This is a Big Title. This is a Big Title. This is a Big Title. This is a Big Title. This is a Big Title. This is a Big Title. "; 
    builder.setTitle(title); 
    builder.setMessage("This is a Message. This is a Message. This is a Message. This is a Message."); 
    builder.setCancelable(false); 
    builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
     @Override 
     public void onClick(DialogInterface dialog, int which) { 
      dialog.dismiss(); 
     } 
    }); 
    AlertDialog alertDialog = builder.create(); 
    alertDialog.setOnShowListener(new DialogInterface.OnShowListener() { 
     @Override 
     public void onShow(DialogInterface dialog) { 
      AlertDialog alertDialog = (AlertDialog) dialog; 
      ViewGroup viewGroup = (ViewGroup) alertDialog.getWindow() 
        .getDecorView(); 
      TextView textView = findTextViewWithTitle(viewGroup, title); 
      if (textView != null) { 
       textView.setEllipsize(null); 
       textView.setMaxHeight((int) (80 * alertDialog.getContext().getResources().getDisplayMetrics().density)); 
       textView.setMovementMethod(new ScrollingMovementMethod()); 
      } 
     } 
    }); 
    alertDialog.show(); 
} 

private TextView findTextViewWithTitle(ViewGroup viewGroup, String title) { 
    for (int i = 0, N = viewGroup.getChildCount(); i < N; i++) { 
     View child = viewGroup.getChildAt(i); 
     if (child instanceof TextView) { 
      TextView textView = (TextView) child; 
      if (textView.getText().equals(title)) { 
       return textView; 
      } 
     } else if (child instanceof ViewGroup) { 
      ViewGroup vGroup = (ViewGroup) child; 
      return findTextViewWithTitle(vGroup, title); 
     } 
    } 
    return null; 
} 
2

Вы можете использовать .setCustomTitle метод AlertDialog.Builder класса, чтобы указать файл пользовательского макета для элемента заголовка диалогового окна. (Как это все еще использует класс AlertDialog, а не на заказ (или подклассов) диалог, я думаю, это достойный ответ). Как так:

AlertDialog.Builder alert = new AlertDialog.Builder(this); 
LayoutInflater inflater = getLayoutInflater(); 
View view=inflater.inflate(R.layout.titlebar, null); 
alert.setCustomTitle(view); 

Android docs reference.setCustomTitle(View customTitleView)

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

1

Если вы действительно не хотите использовать вид пользовательского заголовка, вы можете сделать диалоговое название многострочный:

TextView title = (TextView) dialog.findViewById(android.R.id.title); 
title.setSingleLine(false); 

Если вы хотели бы иметь название прокрутки, или использовать пользовательский заголовок, тогда вы только (хорошо) вариант будет использовать пользовательские alertdialog названия. Это не очень сложно применять:

AlertDialog.Builder builder = new AlertDialog.Builder(context); 
TextView textView = new TextView(context); 
textView.setText("your very long title here"); 
builder.setCustomTitle(textView); 
+0

'dialog.findViewById (android.R.id.title);' возвращает 'null' ... –

+0

Вы должны заменить диалог своим собственным диалогом, в вашем случае: nointernetconnection – Mdlc

1

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

public class CustomDialogClass extends Dialog implements android.view.View.OnClickListener { 

public Activity c; 
public Dialog d; 
public Button yes, no; 
private int showButtons; 
private String tit, msg, yesT, noT; 
private boolean custom=false, all= false, progresss=false, spinner=false, indeterminateputted=false, indet=false; 
private TextView title, subtit; 
private ProgressBar progressBar, progressBar2; 
private int max; 
private int progress; 

public OnPositiveDialogButtonClicked positive; 

public CustomDialogClass(Activity a) { 

    super(a); 
    this.c = a; 
    this.custom = false; 
} 

public CustomDialogClass(Activity a, int botones) { 

    super(a); 
    this.c = a; 
    this.showButtons = botones; 
    this.custom = false; 
} 

public CustomDialogClass(Activity a, int botones, String tit, String message) { 

    super(a); 
    this.custom = true; 
    this.c = a; 
    this.showButtons = botones; 
    this.tit = tit; 
    this.msg = message; 
} 

public CustomDialogClass(Activity a, String tit, String message, String yes, String no) { 

    super(a); 
    this.custom = true; 
    this.c = a; 
    this.tit = tit; 
    this.msg = message; 
    this.yesT = yes; 
    this.noT = no; 
    this.all = true; 
} 

public CustomDialogClass(Activity a, String tit, String message, int max, int progress) { 

    super(a); 
    this.progresss = true; 
    this.tit = tit; 
    this.msg = message; 
    this.max = max; 
    this.progress = progress; 
} 

public CustomDialogClass(Activity a, String tit, String message, int max, int progress, boolean spinner) { 

    super(a); 
    this.tit = tit; 
    this.msg = message; 
    this.max = max; 
    this.progress = progress; 
    this.spinner = true; 
} 

public CustomDialogClass(Activity a, String tit, String message, boolean indet) { 

    super(a); 
    this.progresss = true; 
    this.indeterminateputted = true; 
    this.indet = indet; 
    this.tit = tit; 
    this.msg = message; 
} 

@Override 
protected void onCreate(Bundle savedInstanceState) { 

    super.onCreate(savedInstanceState); 
    requestWindowFeature(Window.FEATURE_NO_TITLE); 
    setContentView(R.layout.dialog_view); 
    yes = (Button) findViewById(R.id.btn_yes); 
    no = (Button) findViewById(R.id.btn_no); 
    title = (TextView) findViewById(R.id.txt_dia); 
    subtit = (TextView) findViewById(R.id.messageDialog); 
    progressBar = (ProgressBar) findViewById(R.id.dialogProgress); 
    progressBar2 = (ProgressBar) findViewById(R.id.dialogProgress2); 

    if(this.indeterminateputted) this.progressBar.setIndeterminate(indet); 

    yes.setOnClickListener(this); 
    no.setOnClickListener(this); 

    if(tit!=null && tit.length()>0) title.setText(tit); 
    if(msg!=null && msg.length()>0) subtit.setText(msg); 
    if(yesT!=null && yesT.length()>0) yes.setText(yesT); 
    if(noT!=null && noT.length()>0) no.setText(noT); 
    if(showButtons==0) { 

     yes.setVisibility(View.GONE); 
     no.setVisibility(View.GONE); 
    } 
    if(spinner) { 

     subtit.setVisibility(View.VISIBLE); 
     progressBar.setVisibility(View.GONE); 
     progressBar2.setVisibility(View.VISIBLE); 
     yes.setVisibility(View.GONE); 
     no.setVisibility(View.GONE); 
    } 
    if(progresss) { 

     subtit.setVisibility(View.VISIBLE); 
     progressBar.setVisibility(View.VISIBLE); 
     yes.setVisibility(View.GONE); 
     no.setVisibility(View.GONE); 
     progressBar.setMax(max); 
     progressBar.setProgress(0); 
    } 
    if(all) { 

     subtit.setVisibility(View.VISIBLE); 
     yes.setVisibility(View.VISIBLE); 
     no.setVisibility(View.VISIBLE); 
    } 
    else if(custom){ 

     subtit.setVisibility(View.VISIBLE); 
     yes.setVisibility(View.GONE); 
     no.setVisibility(View.GONE); 
    } 
} 

@Override 
public void onClick(View v) { 

    switch (v.getId()) { 

    case R.id.btn_yes: 

     positive.onPositive(true); 
     break; 
    case R.id.btn_no: 

     positive.onPositive(false); 
     dismiss(); 
     break; 
    default: 

     break; 
    } 
    dismiss(); 
} 

public void setButtonListener(OnPositiveDialogButtonClicked listener) { 

    positive = listener; 
} 

public void setProgress(int progress) { 

    if(progressBar!=null) { 

     this.progress = progress; 
     progressBar.setProgress(progress); 
    } 
} 

public void setMessage(String msg) { 

    if(subtit!=null) subtit.setText(msg); 
} 

public void setTitle(String titleee) { 

    if(title!=null) title.setText(titleee); 
} 

public int getProgress() { 

    return this.progress; 
} 

public int getMax() { 

    return this.max; 
} 

public void setIndeterminate(boolean indet) { 

    this.progresss = true; 
    this.indeterminateputted = true; 
    this.indet = indet; 
} 
} 

интерфейс для кнопок:

public interface OnPositiveDialogButtonClicked { 

public void onPositive(boolean clickedYes); 
} 

расположение:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:orientation="vertical" 
android:background="@color/white" > 

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:background="@drawable/gradientbackground" 
    android:orientation="horizontal" > 

    <TextView 
     android:id="@+id/txt_dia" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center" 
     android:layout_marginTop="20dp" 
     android:layout_marginBottom="20dp" 
     android:layout_marginLeft="10dp" 
     android:textColor="@android:color/white" 
     android:textSize="16sp" 
     android:textStyle="bold" 
     > 
    </TextView> 
</LinearLayout> 

<TextView 
    android:id="@+id/messageDialog" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:gravity="center" 
    android:layout_gravity="center" 
    android:layout_margin="10dp" 
    android:textColor="@color/black" 
    android:textSize="13sp" 
    android:visibility="gone" 
    android:textStyle="bold" > 
</TextView> 

<ProgressBar 
    style="@android:style/Widget.ProgressBar.Horizontal" 
    android:id="@+id/dialogProgress" 
    android:layout_margin="10dp" 
    android:visibility="gone" 
    android:layout_gravity="center" 
    android:layout_width="250dp" 
    android:layout_height="4dp" 
/> 

<ProgressBar 
    style="?android:attr/progressBarStyleLarge" 
    android:id="@+id/dialogProgress2" 
    android:visibility="gone" 
    android:layout_gravity="center" 
    android:layout_width="wrap_content" 
    android:layout_height="45dp" 
/> 

<LinearLayout 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_gravity="center" 
    android:layout_marginBottom="5dp" 
    android:background="@color/white" 
    android:orientation="horizontal" > 

    <Button 
     android:id="@+id/btn_yes" 
     android:layout_width="100dp" 
     android:layout_height="45dp" 
     android:background="@android:color/white" 
     android:clickable="true" 
     android:text="Yes" 
     android:textSize="13sp" 
     android:textColor="#5DBCD2" 
     android:textStyle="bold" /> 

    <Button 
     android:id="@+id/btn_no" 
     android:layout_width="100dp" 
     android:layout_height="45dp" 
     android:layout_marginLeft="5dp" 
     android:background="@android:color/white" 
     android:clickable="true" 
     android:text="No" 
     android:textSize="13sp" 
     android:textColor="#5DBCD2" 
     android:textStyle="bold" /> 
</LinearLayout> 

0

* Вы можете сделать диалог пользовательских предупреждений путем создания пользовательского макета.

* создать собственный файл XML в папке повторно/макет

* Вы можете спроектировать его на своем пути.

* в вас классе деятельности вы должны написать в на метод создания

я дома это будет полезно для вас.

Диалог d = новый диалог (MainActivity.this);

d.setcontentview(R.layout.custom);

// Например у вас есть один редактировать текст и кнопку, чем вы можете сделать это, объявив

EditText ed = (EditText)d.findViewById(R.id.ed1); 


Button b = (Button)d.finviewById(R.id.b1); 

Button b = (Button)d.finviewById(R.id.b1); 

// вы можете на щелчок по кнопке у слушателя, как

b.setOnClickListner(new .....); 

Предупреждение о предупреждении = d.create(); d.show();

1

У вас есть 2 Options-

  1. Вы можете создать представление диалогового и показать уры содержания. Ниже приведен пример

     final Dialog dialog1 = new Dialog(CatchTheCatActivity.this); 
        dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE); 
        dialog1.setContentView(R.layout.custom_alert); 
        Button ok = (Button) dialog1.findViewById(R.id.button1); 
    
        TextView title = (TextView) dialog1.findViewById(R.id.textview1); 
        TextView content = (TextView) dialog1.findViewById(R.id.textview2); 
        title.setText("your long title") 
        content.setText("your long content"); 
    
        ok.setOnClickListener(new OnClickListener() 
        { 
         @Override 
         public void onClick(View v) 
         { 
           dialog1.dismiss(); 
    
         } 
        }); 
        dialog1.show(); 
    

где R.layout.custom_alert является UI Вы хотите показать (в вашем случае 2 TextView с помощью кнопки в нижней части). Ref

  1. Использование popupwindow. Вот
1

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

LayoutInflater factory = LayoutInflater.from(context); 
     final View textEntryView = factory.inflate(your_layout_id, null); 
     Builder builder = new Builder(context); 
     builder.setTitle(title);//Optional can be added in layout 


     mAlertDialog = builder.create(); 
     mAlertDialog.setCancelable(false); 
     mAlertDialog.setView(textEntryView, 10, 10, 10, 10); 
Смежные вопросы