1. 程式人生 > >Android動態設定佈局,為LinearLayout動態新增子控制元件

Android動態設定佈局,為LinearLayout動態新增子控制元件

       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); }