Android动态设置布局,为LinearLayout动态添加子控件

这篇博客详细介绍了如何在Android中动态地为LinearLayout添加子视图TextView。通过LayoutInflater加载布局,设置LayoutParams以调整视图间隔,并为每个TextView设置文字、颜色、背景和点击事件。点击事件用于更新选中状态并关闭PopupWindow。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

       View view = getActivity().getLayoutInflater().inflate(R.layout.category_select_popupwindow_right, null);
        LinearLayout linearLayoutContainer=(LinearLayout)view.findViewById(R.id.linear_layout_container);


        /*public LinearLayout.LayoutParams (int width, int height) */
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT);
        /*setMargins (int left, int top, int right, int bottom) */
        lp.setMargins(0, 10, 0, 10);
        
        /*服务器的标签*/
        Drawable drawable_new = resources.getDrawable(R.drawable.category_new);
        AllTypeBean mDatas=mAllTypeBean;
        /*如果在循环体外边创建对象,将会抛出异常*/
        /*java.lang.IllegalStateException: The specified child already has a parent.
         You must call removeView() on the child's parent first.*/
        /*每个控件View只能有一个父类*/
//        TextView tvCategory = new TextView(getActivity());
        for (int i = 0; i < mAllTypeBean.getBody().size(); i++) {
            Log.v(TAG, "likes :" + mAllTypeBean.getBody().get(i).getName());
            /*不要再循环体里边创建对象*/
            /*但是这里的需求是每一个循环都要创建一个对象,就是要通过循环创建多个对象*/
            TextView tvCategory = new TextView(getActivity());
            tvCategory.setText(mAllTypeBean.getBody().get(i).getName());
            tvCategory.setTextColor(Color.BLUE);
            tvCategory.setBackgroundDrawable(drawable_new);
            tvCategory.setLayoutParams(lp);
            tvCategory.setGravity(Gravity.CENTER);
            final int id = mDatas.getBody().get(i).getId();
            final int type = mDatas.getBody().get(i).getType();
            tvCategory.setTag(id);
            final String name=mAllTypeBean.getBody().get(i).getName();
            tvCategory.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    ToastUtil.showShortToast(getActivity(), "您选中了:" +name);
                    selectCategory.setText(name);
                    selectCategory.setTag(R.id.tag_id, id);
                    selectCategory.setTag(R.id.tag_type, type);
                    EventBus.getDefault().post(new ClosePopupWindow());
                }
            });
            linearLayoutContainer.addView(tvCategory);
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值