Adding custom layout in an AlertDialog - android

How to I use my xml as a layout for my dialog? This class is used to show a dialog but the problem is i want to set my own layout.
public static void showRateDialog(final Context mContext, final SharedPreferences.Editor editor) {
final Dialog dialog = new Dialog(mContext);
dialog.setTitle("Rate " + APP_TITLE);
LinearLayout ll = new LinearLayout(mContext);
ll.setOrientation(LinearLayout.VERTICAL);
TextView tv = new TextView(mContext);
tv.setText("If you enjoy using " + APP_TITLE + ", please take a moment to rate it. Thanks for your support!");
tv.setWidth(240);
tv.setPadding(4, 0, 4, 10);
ll.addView(tv);
Button b1 = new Button(mContext);
b1.setText("Rate " + APP_TITLE);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + APP_PNAME)));
dialog.dismiss();
}
});
ll.addView(b1);
Button b2 = new Button(mContext);
b2.setText("Remind me later");
b2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
ll.addView(b2);
Button b3 = new Button(mContext);
b3.setText("No, thanks");
b3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (editor != null) {
editor.putBoolean("dontshowagain", true);
editor.commit();
}
dialog.dismiss();
}
});
ll.addView(b3);
dialog.setContentView(ll);
dialog.show();
}
I want it to have 3 buttons and a picture. Is it possible to do so?

You can set custom layout to your dialog like below:
Create a custom layout file:
custom.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FFF" />
<TextView
android:id="#+id/text2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FFF"/>
</RelativeLayout>
Then in your activity:
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.custom);
dialog.setTitle("Title");
// set the custom dialog components - text, image and button
TextView text = (TextView) dialog.findViewById(R.id.text1);
text.setText("Text view 1");
TextView text = (TextView) dialog.findViewById(R.id.text2);
text.setText("Text view 2");
dialog.show();

DialogFragment is now the canonical way to display overlays; using Dialog directly is considered bad practice
Usage
Custom View
<!-- fragment_edit_name.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/edit_name"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="center" android:orientation="vertical" >
<TextView
android:id="#+id/lbl_your_name" android:text="Your name"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
<EditText
android:id="#+id/txt_your_name"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:inputType="text"
android:imeOptions="actionDone" />
</LinearLayout>
and DialogFragment will be
import android.support.v4.app.DialogFragment;
// ...
public class EditNameDialogFragment extends DialogFragment {
private EditText mEditText;
public EditNameDialogFragment() {
// Empty constructor is required for DialogFragment
// Make sure not to add arguments to the constructor
// Use `newInstance` instead as shown below
}
public static EditNameDialogFragment newInstance(String title) {
EditNameDialogFragment frag = new EditNameDialogFragment();
Bundle args = new Bundle();
args.putString("title", title);
frag.setArguments(args);
return frag;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_edit_name, container);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Get field from view
mEditText = (EditText) view.findViewById(R.id.txt_your_name);
// Fetch arguments from bundle and set title
String title = getArguments().getString("title", "Enter Name");
getDialog().setTitle(title);
// Show soft keyboard automatically and request focus to field
mEditText.requestFocus();
getDialog().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
}
}
and showing the dialog in an Activity:
public class DialogDemoActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
showEditDialog();
}
private void showEditDialog() {
FragmentManager fm = getSupportFragmentManager();
EditNameDialogFragment editNameDialogFragment = EditNameDialogFragment.newInstance("Some Title");
editNameDialogFragment.show(fm, "fragment_edit_name");
}
}

Custom alert dialog
* using create custom alert dialog box*/
private void Multiple_spinner_alert(int position) {
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.multiple_spinner_recycler_layout);
dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(dialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
lp.gravity = Gravity.CENTER;
dialog.getWindow().setAttributes(lp);
Window window = dialog.getWindow();
final RecyclerView recycler_spinner = (RecyclerView) dialog.findViewById(R.id.recycler_spinner);
LinearLayoutManager layoutManager = new LinearLayoutManager(context);
recycler_spinner.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, true));
recycler_spinner.setLayoutManager(layoutManager);
mAdapter = new MultipleSpinnerRecyclerAdapter(context, getSetList,listPK_ProviderTypeOptions_ID);
recycler_spinner.setAdapter(mAdapter);
final TextView alert_tv_ok=(TextView)dialog.findViewById(R.id.alert_tv_ok);
onChangeSelectedReceivers();
alert_tv_ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { {
// do your code
dialog.dismiss();
}
});
dialog.show();
}
I am using custom dialog inflate layout like this
set dialog height and width according to your requirements
it helps you

In your layout resource file make sure the android:layout_width is
android:layout_height = "wrap_content"
and not
android:layout_height = "match_parent"

Related

AlertDialog with ImageView and TextView

I want to make an AlertDialog with ImageView and TextView.
I wrote this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp">
<ImageView
android:id="#+id/imgCustomToast"
android:layout_width="170dp"
android:layout_height="220dp"
android:background="#drawable/ycp"
android:gravity="center_horizontal"
android:layout_gravity="center"
android:layout_marginRight="10dp" />
<TextView
android:id="#+id/txtCustomToast"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="C#"
android:gravity="center_horizontal"
android:layout_gravity="center"
android:textSize="20sp"/>
</LinearLayout>
MainActivity:
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
Button button = FindViewById<Button>(Resource.Id.MyButton);
button.Click += delegate
{
AlertDialog.Builder alertadd = new AlertDialog.Builder(this);
LayoutInflater factory = LayoutInflater.From(this);
View view = factory.Inflate(Resource.Layout.sample, null);
alertadd.SetView(view);
alertadd.SetPositiveButton("To Close", (senderAlert, args) =>
{
Toast.MakeText(this, "Closed", ToastLength.Short).Show();
});
alertadd.Show();
};
}
}
I want to change size, font and text of the textview with in MainActivity:
TextView textView = FindViewById<TextView>(Resource.Id.txtCustomToast);
string str = "sample text";
textView.Text = str;
Typeface typeP = Typeface.CreateFromAsset(this.Assets, "fonts/BLOTUS.TTF");
textView.SetTypeface(typeP, TypefaceStyle.Normal);
textView.SetTextSize(Android.Util.ComplexUnitType.Sp, 18);
But I see this error:
System.NullReferenceException
How can I change size, font and text of the textview programmatically?
You are doing wrong way you can access the TextView below way,
Change this line
TextView textView = FindViewById<TextView>(Resource.Id.txtCustomToast);
to this
TextView textView = view.FindViewById<TextView>(Resource.Id.txtCustomToast);
You need to find your view using instance of Alert Dialog like below.
TextView textView = view.FindViewById<TextView>(Resource.Id.txtCustomToast);
View view = factory.Inflate(Resource.Layout.sample, null);
TextView textView = view.findViewById<TextView>(Resource.Id.txtCustomToast);
string str = "sample text";
textView.setText(str);
Call this method,That display an AlertDialog with ImageView and TextView
private void showDialog(Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Title");
builder.setMessage("Message");
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
ImageView imageView = new ImageView(context);
TextView textView = new TextView(context);
linearLayout.addView(imageView);
linearLayout.addView(textView);
builder.setCancelable(false);
builder.setView(linearLayout);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//ok
}
});
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// negative button logic
}
});
AlertDialog dialog = builder.create();
// display dialog
dialog.show();
}

Android, dialog_fragment. dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)

I'm using dialog fragment and everything is fine until I'm trying to remove title bar. There is a code:
Dialog XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#f0f0f0">
<GridView
android:id="#+id/gv_registration_avatars"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_margin="#dimen/avatar_layout_margin"
android:columnWidth="100dp"
android:drawSelectorOnTop="true"
android:gravity="center"
android:numColumns="2"
android:stretchMode="columnWidth"
android:focusable="true"
android:clickable="true"
/>
<Button
android:id="#+id/dismiss"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/avatar_layout_margin"
android:layout_marginRight="#dimen/avatar_layout_margin"
android:layout_below="#id/gv_registration_avatars"
android:text="Ok"
android:layout_gravity="right"/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar_avatars"
android:layout_centerInParent="true"
android:visibility="gone"/>
DialogFragment class is :
public class AvatarPickDialogFragment extends DialogFragment {
private GridView mGridView;
private ProgressBar mProgressBar;
private GridViewAvatarAdapter mGridAdapter;
private ArrayList<String> mGridData;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.avatar_pick_dialog_fragment, container, false);
mGridView = (GridView) rootView.findViewById(R.id.gv_registration_avatars);
mProgressBar = (ProgressBar) rootView.findViewById(R.id.progressBar_avatars);
mGridData = new ArrayList<>();
mGridAdapter = new GridViewAvatarAdapter(getActivity(), R.layout.grid_item_avatar_layout, mGridData);
mGridView.setAdapter(mGridAdapter);
mProgressBar.setVisibility(View.VISIBLE);
String item;
for (int i = 0; i < 10; i++) {
item = new String();
item= new String("string");
mGridData.add(item);
}
mProgressBar.setVisibility(View.GONE);
mGridAdapter.setGridData(mGridData);
Button dismiss = (Button) rootView.findViewById(R.id.dismiss);
dismiss.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dismiss();
}
});
return rootView;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// The only reason you might override this method when using onCreateView() is
// to modify any dialog characteristics. For example, the dialog includes a
// title by default, but your custom layout might not need it. So here you can
// remove the dialog title, but you must call the superclass to get the Dialog.
Dialog dialog = super.onCreateDialog(savedInstanceState);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
return dialog;
}
}
When I am using dialog.requestWindowFeature(Window.FEATURE_NO_TITLE) title bar disappear, but my dialog window width changes to very short and I don't know why, because with title bar it is fine. Any suggestions?
You can try setting fragment width in fragment's onStart() method
#Override
public void onStart()
{
super.onStart();
if (getDialog() == null)
return;
getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}

How to tag data in toggle buttons and loop through them to fetch the selected button's data

I am trying to add toggle buttons dynamically in a linear layout. I have successfully done this- 2 rows with each row having 2 buttons.
Below is the code for it::
public class MainActivity extends Activity
{
LinearLayout VertLayout;
LayoutInflater inflater;
LinearLayout lnrLay_forXaxis;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
make_seat();
}
private void initialize()
{
VertLayout = (LinearLayout) findViewById(R.id.lnrLyMain);
inflater = (LayoutInflater) this.getLayoutInflater();
}
private void make_seat()
{
try{
for(int y=0;y<2;y++)
{
lnrLay_forXaxis = new LinearLayout(this);
lnrLay_forXaxis.setBackgroundColor(Color.CYAN);
lnrLay_forXaxis.setOrientation(LinearLayout.HORIZONTAL);
LayoutParams LLParams = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
lnrLay_forXaxis.setLayoutParams(LLParams);
for(int x=0;x<2;x++)
{
final View sngl_lnrLay = (View) inflater.inflate(R.layout.lnrly_btn, null);
final ToggleButton btt = (ToggleButton) sngl_lnrLay.findViewById(R.id.ToggleButton01);
btt.setChecked(false);
btt.setText("btn-"+x+y);
btt.setTextOn("btn-"+ x+y+" -ON");
btt.setTextOff("btn-"+x+y);
lnrLay_forXaxis.addView(sngl_lnrLay);
}
VertLayout.addView(lnrLay_forXaxis);
}
}
catch(Exception ex)
{Log.d("exp",ex.toString());}
}
}
in activity_main.xml:
<LinearLayout
android:id="#+id/lnrLyMain"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#CCFFCC"
android:orientation="vertical" >
</LinearLayout>
in lnrly_btn.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<ToggleButton
android:background="#drawable/btn_toggle_bg"
style="#style/YourThemeName"
android:checked="true"
android:id="#+id/ToggleButton01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="3dp">
</ToggleButton>
</LinearLayout>
Now i want to add some data with each toggle button(think it should be tag i should be using) and add another button to the activity(lets say button-x). So, after selecting few toggle buttons and then clicking on button-x; a toast/Log will appear showing the selected toggle buttons added/tagged values.
How can i do this.
You can do something like that:
Add field to your Activity:
ArrayList<View> toggles = new ArrayList<>();
Then:
for(int y=0;y<2;y++)
{
lnrLay_forXaxis = new LinearLayout(this);
lnrLay_forXaxis.setBackgroundColor(Color.CYAN);
lnrLay_forXaxis.setOrientation(LinearLayout.HORIZONTAL);
LayoutParams LLParams = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
lnrLay_forXaxis.setLayoutParams(LLParams);
for(int x=0;x<2;x++)
{
final View sngl_lnrLay = (View) inflater.inflate(R.layout.lnrly_btn, null);
final ToggleButton btt = (ToggleButton) sngl_lnrLay.findViewById(R.id.ToggleButton01);
Object tag; //your object,int, string ,whatever
//init your tag
btt.setTag(tag);
btt.setChecked(false);
btt.setText("btn-" + x + y);
btt.setTextOn("btn-" + x + y + " -ON");
btt.setTextOff("btn-" + x + y);
toggles.add(btt);
lnrLay_forXaxis.addView(sngl_lnrLay);
}
VertLayout.addView(lnrLay_forXaxis);
}
Button add = new Button(this);
LayoutParams btParams = new LayoutParams(ActionBar.LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
btParams.gravity = Gravity.CENTER;
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (View toggle: toggles)
Log.d("TAG", toggle.getTag().toString());
}
});
VertLayout.addView(add, btParams);

insert a new TextView in a dialog box after pressing on a button in the dialog box

i have a custom dialog box, it has a textview an edittext and 2 buttons. i'm trying to create a new textview that containes the text of the edittext everytime the user presses on the 'add' button,and locate it beneath the buttons. how can i do that? here's what i tried:
ingDlgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//showDialog(INGS_DIALOG);
final Dialog customIngsDlg = new Dialog(context);
customIngsDlg.setContentView(R.layout.custom_ings_dialog);
customIngsDlg.setTitle("Ingredients");
TextView ingsDlgTitle = (TextView)findViewById(R.id.ingsDialogTitleTv);
final EditText ingsEt = (EditText)customIngsDlg.findViewById(R.id.ingsDialogEt);
final Button ingsAddBtn = (Button)customIngsDlg.findViewById(R.id.ingsAddButton);
final Button ingsFinishBtn = (Button)findViewById(R.id.ingsFinishButton);
ingsAddBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// ArrayList<String> ingsTmp = new ArrayList<String>();
String ingredient = ingsEt.getText().toString();
ingredients.add(ingredient);
ingsEt.setText("");
TextView ingItemTv = new TextView(customIngsDlg.getContext());
ingItemTv.setText(ingredient);
RelativeLayout layout = new RelativeLayout(OwnRecipeAdding.this);
RelativeLayout.LayoutParams parms = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
parms.addRule(RelativeLayout.BELOW,ingsEt.getId());
layout.setLayoutParams(parms);
customIngsDlg.addContentView(ingItemTv,parms);
}
});
// ingsFinishBtn.setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View v) {
//
// customIngsDlg.dismiss();
// }
// });
customIngsDlg.show();
}
});
I would suggest adding the text view to your custom layout in the .xml file and then add text to that when the add button is pressed.
This needs a bit of styling, but it's functional. You'll likely need a scroll view in there when the list becomes too long.
Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/dialog_fragment_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/dialog_textview_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:text="Add Ingredients" />
<EditText
android:id="#+id/dialog_edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="left" />
<LinearLayout
android:id="#+id/button_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<Button
android:id="#+id/button_add"
style="?android:attr/buttonBarButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add" />
<Button
android:id="#+id/button_finish"
style="?android:attr/buttonBarButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Finish" />
</LinearLayout>
<TextView
android:id="#+id/dialog_textview_2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:text="" />
</LinearLayout>
DialogFragment class:
public class TestDialogFragment extends DialogFragment {
private Button buttonAdd;
private Button buttonFinish;
private TextView addTextView;
private EditText editText;
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialoglayout = inflater.inflate(R.layout.dialog_fragment, null);
buttonAdd = (Button)dialoglayout.findViewById(R.id.button_add);
buttonFinish = (Button)dialoglayout.findViewById(R.id.button_finish);
editText = (EditText)dialoglayout.findViewById(R.id.dialog_edittext);
addTextView = (TextView)dialoglayout.findViewById(R.id.dialog_textview_2);
buttonAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String text = addTextView.getText().toString();
text = text + "\n" + editText.getText().toString();
addTextView.setText(text);
editText.setText("");
}
});
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(dialoglayout)
.setTitle("Ingredients")
.setCancelable(false)
.setInverseBackgroundForced(true);
AlertDialog dialog = builder.create();
return dialog;
}
}

Make AlertDialog Custom

I am using this code to display Alert Dialog
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();
Message body is converted into scrollView automatically in case the text is more but Title text has not been viewed completely nor the title space is scrollable.
So, I want to expand the Title area & also want to make it scrollable & for this i don't wanna use custom Dialog, i want to only implement it by AlertDialog.
You can use the .setCustomTitle method of the AlertDialog.Builder class, to specify a custom layout file for the title element of the dialog .(As this is still using the AlertDialog class and not a custom (or subclassed) dialog, I think it's a worthy answer). Like so:
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)
Or you could just make the title font a smaller size, but depending on how much content there is, it may become pointless even having the title there, if it's too small to read.
This example is some what a typical hack... You don't need a custom View also...
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;
}
If you really do not want to use a custom title view, you can make the dialog title multiline:
TextView title = (TextView) dialog.findViewById(android.R.id.title);
title.setSingleLine(false);
If you would like to have a scrolling title, or use a custom title, Then you only (good) option would be to use a custom alertdialog title. It's not very hard to apply:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
TextView textView = new TextView(context);
textView.setText("your very long title here");
builder.setCustomTitle(textView);
Here is my customdialogclass. It has several constructors in function of what you want to display: buttons, progress, nothing more than a title and a message... Customizing the layout you will be able to have a longer title or not. You could even insert one custom textview that adopts its font size to the space avaible for it. Hope it helps.
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;
}
}
the interface for the buttons:
public interface OnPositiveDialogButtonClicked {
public void onPositive(boolean clickedYes);
}
the layout:
<?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>
You have 2 options-
You could create a custom dialog view and show ur content. Here is an example
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();
where R.layout.custom_alert is UI You want to show (in your case 2 textview with a button at the bottom). Ref
Use popupwindow. Here is an example
You can import a layout completely in a dialog, if you want u can set a title to dialog or put a text field in layout acting as title.
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);
*You can do custom alert dialog by creating custom layout.
*create a custom XML file in re/layout folder
*you can design it in your way.
*in you activity class you have to write in on create method
i home this will be useful for you.
Dialog d = new Dialog(MainActivity.this);
d.setcontentview(R.layout.custom);
//For example you have one edit text and button than you can make it by declaring
EditText ed = (EditText)d.findViewById(R.id.ed1);
Button b = (Button)d.finviewById(R.id.b1);
Button b = (Button)d.finviewById(R.id.b1);
//you can on click listner on button like
b.setOnClickListner(new .....);
Alert alert = d.create();
d.show();

Categories

Resources