linearLayout 配合merge动态添加子view的二种方式

1 篇文章 0 订阅
1 篇文章 0 订阅

方式一:使用inflate配合merge,实现加载相关view,我这边加载的是textView

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/tv_name"
        style="@style/statistics_text_weight1"
        android:textStyle="bold"
        android:layout_weight="1" />
</merge>
java代码如下,需要注意的是,使用infalte加载merge的layout时,inflate第二个参数必须提供rootView,同时第三个参数attchToRoot必须为true

private String[] titleArr = new String[]{"分局", "待处理单数", "已处理单数", "台数"};
 for (int i = 0; i < titleArr.length; i++) {
            int layoutId = i == 0 ? R.layout.merge_text_weight2 : R.layout.merge_text_weight1;
            mInflate.inflate(layoutId, ll_title_container, true);
        }
        int childCount = ll_title_container.getChildCount();
        for (int i = 0; i < childCount; i++) {
            TextView textView = (TextView) ll_title_container.getChildAt(i);
            textView.setText(titleArr[i]);
        }

方式二,动态创建view,并设置相关参数,这里以textView为例

  for (int i = 0; i < titleArr.length; i++) {
            int weight = i == 0 ? 2 : 1;
            TextView textView = getTextView(weight);
            textView.setText(titleArr[i]);
            ll_title_container.addView(textView);
        }
 private TextView getTextView(int weight) {
        TextView textView = new TextView(mContext);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, weight);
        textView.setGravity(Gravity.CENTER);
        textView.setTextColor(textColor);
        textView.setTextSize(15);
        textView.setSingleLine(true);
        textView.setTypeface(Typeface.DEFAULT_BOLD);
        textView.setBackgroundResource(R.drawable.bg_text_sel);
        textView.setPadding(0, margin, 0, margin);
        textView.setLayoutParams(lp);
        return textView;
    }


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值