1

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?

Shivam Verma
  • 7,973
  • 3
  • 26
  • 34
Manuel Castro
  • 1,633
  • 3
  • 24
  • 38

5 Answers5

3

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);
Hemanth
  • 2,717
  • 2
  • 21
  • 29
1

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();
}
Manuel Castro
  • 1,633
  • 3
  • 24
  • 38
0

Try this..

final int titleId = getActivity().getResources().getIdentifier("alertTitle", "id", "android");
TextView title = (TextView) getDialog().findViewById(titleId);
if (title != null) {
    title.setGravity(Gravity.CENTER);
}
Jagadesh Seeram
  • 2,630
  • 1
  • 16
  • 29
0

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.

Tofasio
  • 425
  • 3
  • 14
0

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.

Ankit Bansal
  • 1,801
  • 17
  • 34