Manuel Castro
Manuel Castro

Reputation: 1723

How center custom dialog title on Android

I'm writing a custom dialog on android. I did this using the onCreateView method.

public class CheckpointLongPressDialog extends DialogFragment {

public void CheckpointLongPressDialog() {}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_checkpoint_long_press_dialog, container);
    getDialog().setTitle("TITLE");
    return view;
}    

How can i center the title programmatically?

Upvotes: 1

Views: 5089

Answers (5)

Ankit Bansal
Ankit Bansal

Reputation: 1811

The title view is using default theme. You have 2 ways to do what you want, first one is better for having a more customized experience:

  1. Use this to have a dialog without title, and then make custom title bar in the layout of this fragment.

    dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);

  2. Extend the default theme for the dialog and update it, then set it in this dialog.

Upvotes: 0

Manuel Castro
Manuel Castro

Reputation: 1723

I solve the problem using a builder and inflating the xml layout.

private AlertDialog.Builder builder;

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the Builder class for convenient dialog construction
    builder = new AlertDialog.Builder(getActivity());

    LayoutInflater inflater = getActivity().getLayoutInflater();

    builder.setView(inflater.inflate(R.layout.fragment_checkpoint_long_press_dialog, null));


    // Create the AlertDialog object and return it
    return builder.create();
}

Upvotes: 1

Tofasio
Tofasio

Reputation: 425

What if you use the whole layout to inflate also your custom title?. Instead of getDialog().setTitle("TITLE"); you can also include a TextView in your custom layout for the title.

Upvotes: 0

Jagadesh Seeram
Jagadesh Seeram

Reputation: 2664

Try this..

final int titleId = getActivity().getResources().getIdentifier("alertTitle", "id", "android");
TextView title = (TextView) getDialog().findViewById(titleId);
if (title != null) {
    title.setGravity(Gravity.CENTER);
}

Upvotes: 0

Hemanth
Hemanth

Reputation: 2737

Maybe its not the best way, I use a custom title TextView.

TextView title = new TextView(mainActivity);
title.setText(alertTitle);
title.setBackgroundResource(R.drawable.gradient);
title.setPadding(10, 10, 10, 10);
title.setGravity(Gravity.CENTER); // this is required to bring it to center.
title.setTextSize(22);
getDialog().setCustomTitle(title);

Upvotes: 3

Related Questions