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); }
Android动态设置布局,为LinearLayout动态添加子控件
最新推荐文章于 2025-06-28 21:39:02 发布