`
bogongjie
  • 浏览: 230495 次
  • 性别: Icon_minigender_1
  • 来自: 苏州
社区版块
存档分类
最新评论

android 动态 布局

阅读更多

动态增加布局:

private void addLayout(Context context) {
		LinearLayout layout = new LinearLayout(context);
		//设置宽高属性
		LayoutParams fullParams = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT);
		//设置布局方向
		layout.setOrientation(LinearLayout.VERTICAL);
		//设置背景颜色
		layout.setBackgroundColor(getResources().getColor(R.color.black));

		int id = 0;
		//设置权重
		LayoutParams weightParams = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT, 1.0f);
		ArrayList<LinearLayout> list = new ArrayList<>();
		for (int i = 0; i < line; i++) {
			for (int j = 0; j < column; j++) {
				LinearLayout tempLayout = new LinearLayout(context);
				tempLayout.setBackgroundColor(getResources().getColor(R.color.gray));
				tempLayout.setId(id++);//设置id
				list.add(tempLayout);
			}
		}

		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
				LayoutParams.MATCH_PARENT, 1.0f);
		params.setMargins(1, 0, 1, 0);

		int index = 0;
		for (int i = 0; i < line; i++) {
			LinearLayout hor = new LinearLayout(context);
			for (int j = 0; j < column; j++) {
				hor.addView(list.get(index), params);
				index++;
			}
			weightParams.setMargins(0, 1, 0, 1);
			layout.addView(hor, weightParams);
		}

		setContentView(layout, fullParams);

		LinearLayout linearLayout = (LinearLayout) findViewById(10);
		linearLayout.setBackgroundColor(getResources().getColor(R.color.red));
	}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics