12

I am working on an activity where I created a custom view that I am adding dynamically within a LinearLayout. The problem is that I am unable to give margin between the custom views I add.

Here is a look at the two views I added which are next to each other.

Screentshot:

enter image description here

Code for creating the views dynamically:

private void AddSelectedTagUI(final com.main.feedify.serializers.Tags tag){

    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = inflater.inflate(R.layout.tags,tags_section_selectedtags,false);

    TextView tagName = (TextView)v.findViewById(R.id.customview_tags_name);
    tagName.setText(tag.getTagName());

    ImageView close_button = (ImageView)v.findViewById(R.id.customview_tags_close);

    close_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RemoveTag(tag.getTagID(), selectedTags);
        }
    });

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

    tags_section_selectedtags.addView(v, params);


    // cast view to tags and add it in our layout.
    // this will help us find out the tag we wanna delete.

    view_selectedTags.add(v);
    this.UpdateMessage(true);
}

tags.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:orientation="horizontal"
    android:background="@drawable/tags"
    android:padding="5dp"
    android:id="@+id/custom_tag"
    >

    <TextView android:id="@+id/customview_tags_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Beyonce"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="3dp"
        android:layout_centerVertical="true"
        android:textColor="@android:color/white"
        android:textSize="@dimen/title" />

    <ImageView
        android:id="@+id/customview_tags_close"
        android:layout_width="wrap_content"
        android:layout_marginTop="2dp"
        android:layout_toRightOf="@+id/customview_tags_name"
        android:layout_height="wrap_content"
        android:src="@drawable/close"
        android:layout_marginLeft="3dp"
        android:layout_marginRight="10dp"
        />

</RelativeLayout>

activity_tags.xml

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

    <TextView
        android:id="@+id/tags_lbl_taginfo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="Add at least 4 favorite topics"
        android:layout_marginTop="20dp"
        />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_below="@+id/tags_lbl_taginfo"
        android:layout_width="match_parent"
        android:layout_height="190dp"
        android:layout_marginTop="15dp"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp"
        android:id="@+id/tags_section_selectedtags">




    </LinearLayout>


    <EditText
        android:id="@+id/tags_txt_tags"
        android:layout_below="@+id/tags_section_selectedtags"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="35dp"
        android:hint="Add tags ..."
        android:textColor="@color/tags_edittext"
        android:paddingTop="15dp"
        android:singleLine="true"
        android:paddingLeft="9dp"
        android:paddingBottom="15dp"
        android:background="@drawable/tags_edittext"
        />

    <TextView
        android:id="@+id/tags_lbl_tagsuggestion"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="Suggestions"
        android:layout_marginTop="15dp"
        android:layout_below="@id/tags_txt_tags"
        />

</RelativeLayout>

Custom Tags Class:

package com.main.feedify.custom_views;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.main.feedify.feedify_mockup.R;
import com.tokenautocomplete.TokenCompleteTextView;
/**
 * Created by Muazzam on 10/17/2015.
 */
public class Tags extends RelativeLayout{

    private com.main.feedify.serializers.Tags tag;

    public Tags(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        LayoutInflater inflater = LayoutInflater.from(context);
        inflater.inflate(R.layout.tags,this);
    }

    public void setTag(com.main.feedify.serializers.Tags t){
        this.tag = t;
    }

    public com.main.feedify.serializers.Tags getTag(){
        return this.tag;
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        MarginLayoutParams margins = MarginLayoutParams.class.cast(getLayoutParams());
        int margin = 5;
        margins.topMargin = 0;
        margins.bottomMargin = 0;
        margins.leftMargin = margin;
        margins.rightMargin = 0;
        setLayoutParams(margins);
    };
}
Mj1992
  • 3,404
  • 13
  • 63
  • 102

5 Answers5

8

You are setting margins in Pixels. Try converting them into dp, so that the margins value becomes independent of display density.

@Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        MarginLayoutParams margins = MarginLayoutParams.class.cast(getLayoutParams());
        int margin = pxToDp(5);
        margins.topMargin = 0;
        margins.bottomMargin = 0;
        margins.leftMargin = margin;
        margins.rightMargin = 0;
        setLayoutParams(margins);
    };

private int pxToDp(int px) {
         return (int) (px / Resources.getSystem().getDisplayMetrics().density);
}

EDIT:

Get rid of the margin code in onLayout() and set those margins, when you are puting this view inside a viewgroup like LinearLayout or RelativeLayout etc.

Umer Farooq
  • 7,356
  • 7
  • 42
  • 67
  • Hi, thanks for the answer, but this one is not working, i tried to debug the app and found out the debugger is not stopping on this function when i try to add a tag dynamically. – Mj1992 Oct 25 '15 at 18:02
  • It isn't possible onLayout() doesn't get called. Looking at your code, Why are you assigning the params again if you have already assigned them inside onLayout(). Second use RelativeLayout params if the parent of the tag view is RelativeLayout. I think it's better to assign params to the tag view once you have inflated them, not inside onLayout(). – Umer Farooq Oct 25 '15 at 18:36
  • I am debugging it and it's not calling. Otherwise it would have stopped there when I add a view. Than I also renamed my `Tags` class and try to run the same activity and it runs smoothly with the same problems. I feel like the `Tags` activity is not being used or not playing it's role properly. Where do you want me to use RelativeLayout params ? I didn't get that – Mj1992 Oct 25 '15 at 20:01
  • Hi the onLayoutParam is being called and I am using your code but it's still not working. Can you please help me out with this since I've been stuck here for a long time now. – Mj1992 Oct 30 '15 at 12:27
  • 1
    Get rid of the margin code in onLayout() and set those margins, when you are puting this view inside a viewgroup like LinearLayout or RelativeLayout etc. Besides what is the parent view of your Tag view? – Umer Farooq Oct 30 '15 at 14:19
3

You should try setting the layout_margin to your RelativeLayoutin your XML file, same as you did with the padding.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:orientation="horizontal"
    android:background="@drawable/tags"
    android:layout_margin="5dp"
    android:padding="5dp"
    android:id="@+id/custom_tag">

    <TextView android:id="@+id/customview_tags_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Beyonce"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="3dp"
        android:layout_centerVertical="true"
        android:textColor="@android:color/white"
        android:textSize="@dimen/title" />

    <ImageView
        android:id="@+id/customview_tags_close"
        android:layout_width="wrap_content"
        android:layout_marginTop="2dp"
        android:layout_toRightOf="@+id/customview_tags_name"
        android:layout_height="wrap_content"
        android:src="@drawable/close"
        android:layout_marginLeft="3dp"
        android:layout_marginRight="10dp" />

</RelativeLayout>   
Marko
  • 20,385
  • 13
  • 48
  • 64
  • Just want to add an aside: doing this will create an extra RelativeLayout to be created. For example `customview_tags_name` will be two levels away from the rot with `custom_tag` being the only child of the outer RelativeLayout. – CodyEngel Jun 27 '17 at 17:54
2

You should add left margin to view while adding it.

 RelativeLayout.LayoutParams params =  new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
//add this line 
    params.leftMargin=50;
//end
    tags_section_selectedtags.addView(v, params);
Vishavjeet Singh
  • 1,385
  • 11
  • 13
1

I think that the problem lays in this piece of code:

@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
    MarginLayoutParams margins = MarginLayoutParams.class.cast(getLayoutParams());
    int margin = 5;
    margins.topMargin = 0;
    margins.bottomMargin = 0;
    margins.leftMargin = margin;
    margins.rightMargin = 0;
    setLayoutParams(margins);
};

Here you change the layout parameters inside the onLayout() method and it should lead to the infinite layout of your view: custom view's parent view calls onLayout() which calls setLayoutParams() which results in onLayout()... And so it goes.
One way to prevent this behavior is to add your margins in tags.xml file, just like you did with the paddings. The infinite layout loop will be gone and your view will have a chance to set its margins.

aga
  • 27,954
  • 13
  • 86
  • 121
0

I have designed a view dynamically and have given parameters such like yours, have a look at this code:

https://stackoverflow.com/a/33339420/5479863

and to convert into dp from pixel use this method

private int getPixelsToDP(int dp) {
    float scale = getResources().getDisplayMetrics().density;
    int pixels = (int) (dp * scale + 0.5f);
    return pixels;
}
Community
  • 1
  • 1
Abdul Aziz
  • 442
  • 5
  • 12