Android ViewGroup动态添加子View,子View

2018-03-20  本文已影响0人  hansduo

前言:自定义ViewGroup做流式布局(简化鸿洋大神的),虽然github上已经有许多现有的控件提供使用,但是还是想动手做一个。做完调试,发现在布局里面写,并添加了N个TextView,效果完美实现。但是当我在实际用的时候,动态添加子View的时候,发现子View的布局属性全部失效了。
这是子view的XML布局。

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tv_item"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/tab_style_unselected"
    android:gravity="center"
    android:text="tag文字"
    android:padding="30dp"
    android:layout_marginLeft="20dp"
    android:layout_marginRight="25dp"
    android:layout_marginTop="20dp"
    android:layout_marginBottom="25dp"
    android:textColor="@color/black" />

0、有一种特别简单的方法,就是在TextView上加一层父容器,RelativeLayout或者LinearLayout都可以,textview的属性就都能生效了。但是布局层级都凭空多了一层无用布局。

1、首先,我是通过下面方式实例化TextView。

TextView textView = (TextView) View.inflate(context,R.layout.tag_text_layout, null);
flowLayout.addView(textView);

这种情况,子view的margin和paddding属性在父容器里,都读不到。
ok,失败了,换方法。

2、经过和度娘一番交流后,找到了第二种方法。

LayoutInflater inflater = getLayoutInflater();
TextView textView = (TextView) inflater.inflate(R.layout.tag_text_layout, articleFlow, false);
articleFlow.addView(textView);

articleFlow是父容器,也就是要添加textview的布局。这样添加,margin属性就可以拿到了~。
但是,我发现我的还没有生效,padding值还是拿不到。

3、仔细检查代码,发现我在拿到textview之后,根据状态重新设置了background,所以将XML中的paddding给覆盖掉了。
删除drawable文件中的padding设置,OK生效。达到效果~

因为重新设置background,导致到第二部问题还未解决,所以思维还是认为是同一个问题,没成想是两个问题一起导致的。所以还是要认真仔细。不然写得越快,给自己埋坑越多。

参考:https://www.jianshu.com/p/515ff7d62785
http://blog.csdn.net/u011494050/article/details/42555139

上一篇下一篇

猜你喜欢

热点阅读