J. Doe J. Doe - 4 months ago 21
Android Question

In android, how to make empty TextView stay in the middle vertically?

In android, I want to add an empty message in the middle of screen when my GridView is empty. But the layout below makes the text in the middle-top of the screen. How can I make the text in the middle also in vertical direction ?

GridView gridview = (GridView) findViewById(R.id.gridview);
TextView emptyText = (TextView)findViewById(R.id.empty);
gridview.setEmptyView(emptyText);



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


<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:columnWidth="100dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:paddingTop="?android:attr/actionBarSize"
android:gravity="center"

/>


<TextView
android:id="@+id/empty"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"

android:gravity="center"
android:text="No project files found"
android:textColor="#FFFFFF" />


</LinearLayout>

Answer

Make the parent view as RelativeLayout and then set centerInParent="true" for TextView

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/grey">

    <TextView
        android:layout_centerInParent="true"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>