Abbath
Abbath

Reputation: 1012

change text gravity to top in Android

I need to dynamically change Android text Gravity to the TOP in My ListItems. Code used for ListItem:

XML layout file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="horizontal"
          android:layout_width="match_parent"
          android:layout_height="@dimen/ma_list_item_height">
                   ..............
<TextView
        android:id="@+id/driver_passage_text_view"
        android:layout_width="0dp"
        android:layout_height="@dimen/ma_list_item_height"
        android:layout_weight="1"
        android:gravity="center_horizontal|center_vertical"
        android:text="Ivanov Ivan Ivanich"
        android:padding="0"
        />

I have read about Gravity and property setIncludeFontPadding, I have tried to use it but it is not working in my case, Code used :

 private void setGravityAndText(TextView textView,String text){
   if(text.length()>24){
        textView.setIncludeFontPadding(true);
        textView.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
   }
    else {
       textView.setIncludeFontPadding(false);
       textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
   }
    textView.setText(text);

}

Horizontal alignment is working successfully, but on the top anyway doesn't work? What did I do wrong?

Please Help.

Thanks in Advance.

Upvotes: 1

Views: 1521

Answers (2)

Pratik Butani
Pratik Butani

Reputation: 62411

Remove android:gravity from xml and change android:height="fill_parent", Try like this:

for XML:

<TextView
        android:id="@+id/driver_passage_text_view"
        android:layout_width="0dp"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:text="Ivanov Ivan Ivanich"
        android:padding="0"
        />

for Java:

private void setGravityAndText(TextView textView,String text){
   if(text.length()>24){
        textView.setIncludeFontPadding(true);
        textView.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP);
   }
    else {
       textView.setIncludeFontPadding(false);
       textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
   }
    textView.setText(text);

}

Upvotes: 3

Vaibs_Cool
Vaibs_Cool

Reputation: 6156

Try with EDITTEXT

<EditText 
    android:id="@+id/driver_passage_text_view"
    android:layout_width="0dp"
    android:layout_height="@dimen/ma_list_item_height"
    android:layout_weight="1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:ellipsize="start" 
    android:maxLines="1"
    android:gravity="center"
    android:hint="Some hint text"
></EditText>

Upvotes: 0

Related Questions