Nishant Agarwal
Nishant Agarwal

Reputation: 455

Cannot set a text view as Title on a custom dialog with setTitle method

I have created a custom dialog with

Dialog dialog = new Dialog(loginPage.this);

Then I have created a text view to use it as title for this dialog:

TextView title = new TextView(this);
title.setText("Custom Centered Title");
title.setGravity(Gravity.CENTER);

But for some reason this line throws an error even though Dialog class has a method as setTitle(@StringRes int titleId).

dialog.setTitle(title.getId());

Am I missing something?? :/

Update:

Found out the reason for error. But still cannot set the text view as title on the dialog. Can anyone point me in the right direction?

Upvotes: 0

Views: 400

Answers (1)

Amir Hossein Mirzaei
Amir Hossein Mirzaei

Reputation: 2375

dialog.setTitle(title.getId()); just gets the text from your strings resources and set's it to the dialog title and your should use String res id or String !

if you want to use custom view in your dialog follow this steps :

1- create your dialog layout inside layout folder some thing like this :

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

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/message"
        android:layout_width="match_parent"

        android:layout_height="wrap_content"
        android:textSize="16sp" />

   </LinearLayout>

2- create your dialog and disable default titleBar :

   Dialog dialog = new Dialog(MainActivity.this);

   dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); 

3- set your layout id to the dialog and obtain your views from the layout then your can initialize them :

dialog.setContentView(R.layout.my_dialog);

TextView title = dialog.findViewById(R.id.title);

TextView message = dialog.findViewById(R.id.message);

title.setText("Hello");

message.setText("Good luck");

and finally your dialog looks like this :

enter image description here

Upvotes: 1

Related Questions