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

方式一:使用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;
    }


阅读更多
个人分类: android inflate merge
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭