Подтвердить что ты не робот

Пользовательский вид не дает поля

Я работаю над тем, где я создал custom view, который я динамически добавляю в LinearLayout. Проблема в том, что я не могу дать разницу между пользовательскими представлениями, которые я добавляю.

Вот посмотрите на два вида, которые я добавил, которые находятся рядом друг с другом.

Screentshot:

введите описание изображения здесь

Код для динамического создания представлений:

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>

Пользовательские теги Класс:

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);
    };
}
4b9b3361

Ответ 1

Вы должны попробовать установить layout_margin на RelativeLayout в свой 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: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>   

Ответ 2

Вы устанавливаете поля в Пикселях. Попробуйте преобразовать их в dp, чтобы значение полей не зависело от плотности отображения.

@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:

Избавьтесь от кода поля в onLayout() и установите эти поля, когда вы ставите это представление внутри группы просмотра, например LinearLayout или RelativeLayout и т.д.

Ответ 3

Вы должны добавить левое поле для просмотра, добавляя его.

 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);

Ответ 4

Я думаю, что проблема лежит в этом фрагменте кода:

@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);
};

Здесь вы меняете параметры макета внутри метода onLayout(), и это должно привести к бесконечному расположению вашего представления: пользовательский вид родительского представления вызывает onLayout(), который вызывает setLayoutParams(), что приводит к onLayout()... И так оно и есть. Одним из способов предотвратить это поведение является добавление полей в файл tags.xml, как и с прокладками. Контур бесконечной компоновки исчезнет, ​​и ваше представление будет иметь шанс установить его поля.

Ответ 5

Я разработал представление динамически и дал такие параметры, как ваш, посмотрите на этот код:

fooobar.com/info/34033/...

и для преобразования в dp из пикселя используйте этот метод

private int getPixelsToDP(int dp) {
    float scale = getResources().getDisplayMetrics().density;
    int pixels = (int) (dp * scale + 0.5f);
    return pixels;
}