分享

Fragment如何动态添加控件

 quasiceo 2016-12-18
Fragment如何动态添加控件?
现在有个程序是这样,在一个Fragment里嵌套一个viewpager,viewpager带有两个fragment页面可以滑动切换,现在第一个页面里有个功能是从一个网站获得若干条信息(条数每天都不一样),然后我要在fragment里动态生成textview用来显示标题,当天有多少条信息就生成多少个textview。。我在activity里做了一个,可以用,但是当我想把这个已经做好的activity改装成fragment的时候总是不对。。动态生成部分的代码如下:
public void make_table(String className,String ClassRoom,int weeks,int classes,int gridHeight,int[] background){
final TextView mine = (TextView)getView().findViewById(R.id.add_tx);
//Textview mine.setText(className + "\n@" + ClassRoom);
//填入文字
RelativeLayout.LayoutParams eng = new RelativeLayout.LayoutParams(aveWidth * 31 / 32, (gridHeight - 5) * 2);
//textview定位,根据填入数据的不同textview显示的位置也不同
if (classes % 2 == 0) {
classes = classes + 1;
 }
eng.topMargin = 5 + (classes - 1) * gridHeight;
eng.leftMargin = 1;
eng.addRule(RelativeLayout.RIGHT_OF, weeks);
 mine.setGravity(Gravity.CENTER); // 设置一种背景 mine.setBackgroundResource(background[weeks-1]);
mine.setTextSize(12);
 mine.setLayoutParams(eng);
mine.setTextColor(Color.WHITE);
//设置不透明度
mine.getBackground().setAlpha(222);
course_table_layout.addView(mine);
} … 
添加评论
查看全部 2 个回答
于猛 linghuayicao.top
最近也在做这个,占地,解决好了来答
------分割线-------
解决。

public View course(View cFragment){
        //找到周几的线性布局
        LinearLayout course_linearLayout  = (LinearLayout)cFragment.findViewById(R.id.one);
        //创建button
        Button b = new Button(course_linearLayout.getContext());
        //设置高度
        b.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,toPx(116)));
        //设置文字 内容与颜色
        b.setText("test");
        b.setTextColor(Color.parseColor("#F5F5DC"));
        //设置背景色
        b.setBackgroundColor(Color.parseColor("#FF4081"));
        //设置button所属的位置
        ViewGroup.MarginLayoutParams margin = new ViewGroup.MarginLayoutParams(b.getLayoutParams());
        margin.setMargins(margin.leftMargin, toPx(120), margin.rightMargin, toPx(120) + margin.height);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(margin);
        b.setLayoutParams(layoutParams);
        //添加到线性布局
        course_linearLayout.addView(b);
        return cFragment;
    }

在onCreateView中调用。

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View cFragment = inflater.inflate(R.layout.fragment_course_table, container, false);
        cFragment = course(cFragment);
        return cFragment;
    }

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多