Android编程之代码创建布局实例分析
本文实例讲述了Android编程之代码创建布局使用方法。分享给大家供大家参考,具体如下:
大概描述一下效果:最外层是一个 RelativeLayout 里面有自定义个LinearLayout,每个LinearLayout有两个TextView。that's it !!!
private void initView() { // 获取xml的RelativeLayout layout = (RelativeLayout) findViewById(R.id.liner); for (int i = 0; i < 5; i++) { RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); // 每行都有一个linearlayout LinearLayout lLayout = new LinearLayout(mContext); lLayout.setId(i + 10); lLayout.setOrientation(LinearLayout.HORIZONTAL); LinearLayout.LayoutParams lLayoutlayoutParams = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); lLayout.setLayoutParams(lLayoutlayoutParams); TextView tv = new TextView(mContext); tv.setId(i); tv.setText("这是第" + i + "个文本框"); tv.setTextColor(Color.BLUE); TextView tv_num = new TextView(mContext); tv_num.setId(i + 20); tv_num.setText(i + "台"); tv_num.setTextColor(Color.RED); // 为TextView添加长高设置 LinearLayout.LayoutParams layoutParams_txt = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); tv.setLayoutParams(layoutParams_txt); tv_num.setLayoutParams(layoutParams_txt); // 添加到每行的linearlayout中 lLayout.addView(tv); lLayout.addView(tv_num); // 每个linearlayout都在前一个的下面,第一个在顶,不处理 if (i > 0) { relativeParams.addRule(RelativeLayout.BELOW, i + 10 - 1); } // 把每个linearlayout加到relativelayout中 layout.addView(lLayout, relativeParams); } }
希望本文所述对大家Android程序设计有所帮助。
赞 (0)