21

How to set gravity in programmingcally in a relativelayout. I have a XML layout with name chat_viewer_message.xml as below:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/background"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingRight="4dip"
    android:paddingBottom="4dip"
    android:gravity="left"
    android:background="@drawable/chat_bg_in">

    <ImageView
        android:id="@+id/avatar"
        android:layout_width="32dip"
        android:layout_height="32dip"
        android:layout_marginLeft="4dip"
        android:src="@drawable/avatar_1_1"
        />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/avatar"
        android:paddingLeft="4dip"
        />

</RelativeLayout>

And code view in programming is as below:

@Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final int type = getItemViewType(position);
        final View view;
        if (convertView == null) {
            final int resource = R.layout.chat_viewer_message;
            view = activity.getLayoutInflater()
                    .inflate(resource, parent, false);
            if (type == TYPE_MESSAGE)
                ((TextView) view.findViewById(R.id.text)).setTextAppearance(
                        activity, appearanceStyle);
        } else
            view = convertView;



        final MessageItem messageItem = (MessageItem) getItem(position);
        String name;
        final String account = messageItem.getChat().getAccount();
        final String user = messageItem.getChat().getUser();
        final String resource = messageItem.getResource();
        final boolean incoming = messageItem.isIncoming();
        final String server_host = view.getResources().getString(
                R.string.server_host);
        if (isMUC) {
            name = resource;
        } 


        if (incoming) {
            view.setBackgroundResource(R.drawable.chat_bg_in);
        } else {
            // I WANT TO GRAVITY TO RIGHT. HOW TO CODE? THANKS
            view.setBackgroundResource(R.drawable.chat_bg_out);
        }

        return view;
}

See gravity at the relativelayout with id = background, the default gravity is LEFT, So I want to if !incoming the value gravity at relativelayout be RIGHT instead LEFT.

Thanks.

Nargis
  • 4,687
  • 1
  • 28
  • 45
Loren Ramly
  • 1,091
  • 4
  • 13
  • 21

6 Answers6

28

Cast view to container layout, in this case RelativeLayout, and use setGravity(int) on it:

if (incoming) {
    view.setBackgroundResource(R.drawable.chat_bg_in);
} else {
    // I WANT TO GRAVITY TO RIGHT. HOW TO CODE? THANKS
    view.setBackgroundResource(R.drawable.chat_bg_out);

    ((RelativeLayout) view).setGravity(Gravity.RIGHT);
}

A word of caution (from the docs):

Note that since RelativeLayout considers the positioning of each child relative to one another to be significant, setting gravity will affect the positioning of all children as a single unit within the parent. This happens after children have been relatively positioned.

Vikram
  • 51,313
  • 11
  • 93
  • 122
16

There are two main ways to programmatically set the gravity in a RelativeLayout. You can either set the gravity for all child views (setGravity(int)) or set the gravity individually (params.addRule(int)). Note: These methods are not available for LinearLayouts.

To set the gravity for all children:

RelativeLayout relativeLayout = findViewById(R.id.myRelativeLaout);
relativeLayout.setGravity(Gravity.CENTER);

To set the gravity for a single view within a RelativeLayout:

MyView myView = findViewById(R.id.myView);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
myView.setLayoutParams(params);

Sources:

Anonsage
  • 8,030
  • 5
  • 48
  • 51
8

It works perfectly for my case:

    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);

    layoutParams.topMargin = 700;//in my case
    layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);//in my case
    varButton.setLayoutParams(layoutParams);
0

You can use:

RelativeLayout.LayoutParams paramas = new RelativeLayout.LayoutParams();
params.gravity = Gravity.RIGHT;
view.setLayoutParams(params);

For more info about gravity parameters u can check this: Gravity

Jilberta
  • 2,836
  • 5
  • 30
  • 44
  • Error: java.lang.ClassCastException: android.widget.AbsListView$LayoutParams cannot be cast to android.widget.RelativeLayout$LayoutParams – Loren Ramly Sep 03 '13 at 05:10
  • you're inflating the wrong layout: final int resource = R.layout.chat_viewer_message; Your ListView item layout id is background, which is RelativeLayout isn't it ? – Jilberta Sep 03 '13 at 06:19
  • Solved, background I move to textview, which id is text – Loren Ramly Sep 03 '13 at 06:25
  • 11
    RelativeLayout.LayoutParams does not have a gravity field – Jason Jul 19 '15 at 03:57
0

Use method, setGravity(int) http://developer.android.com/reference/android/widget/RelativeLayout.html#setGravity(int)

It's better way to set child's gravity by using RelativeLayout.LayoutParams. See this. How to programmatically set the layout_align_parent_right attribute of a Button in Relative Layout?

Community
  • 1
  • 1
0

Building up chat layout and manipulating it programmatically & sDirectionHasmap contains direction of each message.

if (sDirectionHashMap.get(idsList.get(position)).equals("incoming")) {
            holder.messageLayout.setGravity(Gravity.LEFT);
        } else {
            holder.messageLayout.setGravity(Gravity.RIGHT);
        }
Bilal Shahid
  • 490
  • 9
  • 16