Reputation: 2035
I have a ListView
with an empty view set as a view I create programmatically. I'd like to have it centered both horizontally and vertically. I found this code while searching how to do that on google.:
TextView myTv = new TextView(getActivity());
myTv.setText("No results");
RelativeLayout.LayoutParams param = new RelativeLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
param.addRule(RelativeLayout.CENTER_IN_PARENT, 0);
myTv.setLayoutParams(param);
myTv.setVisibility(View.GONE);
((RelativeLayout) mScheduleListView.getParent()).addView(myTv, 0);
mScheduleListView.setEmptyView(myTv);
The XML layout for the fragment holding the ListView above looks like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ScheduleFragment" >
<ListView android:id="@+id/mScheduleListView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
android:divider="@null"
android:dividerHeight="10.0sp" />
</RelativeLayout>
The layout shows, but not centered. I have no idea why it doesn't work. I tried messing with the LayoutParams
and change them to MATCH_PARENT
but apparently that wasn't the problem.
If so what could be the problem and how to solve it?
Upvotes: 0
Views: 460
Reputation: 541
Set Textview
Gravity in Center
Help Code:
myTv.setGravity(Gravity.CENTER);
Upvotes: 2
Reputation: 2035
Solved!
Apparently param.addRule(RelativeLayout.CENTER_IN_PARENT, -1)
works.
Thank to the documentation I figured out that the value for true
is -1.
All solutions I read about centering a view suggested true
was actually 0 (for the addRule
method).
Upvotes: 0
Reputation: 1996
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
write this code in your layout..It may works..
Upvotes: 1