免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1417 | 回复: 1

[Android] 使用java代码添加控件 [复制链接]

论坛徽章:
0
发表于 2015-06-11 09:41 |显示全部楼层
平时多习惯于采用xml文件来添加布局和控件,采用java代码在activity中添加控件也是一种方式,下面简单举两个例子:

1、addContentView

addContentView作用类似于setContentView()来为activity初始化布局:
  1. public class MainActivity extends Activity {
  2. 2
  3. 3     @Override
  4. 4     protected void onCreate(Bundle savedInstanceState) {
  5. 5         super.onCreate(savedInstanceState);
  6. 6         //setContentView(R.layout.activity_main);
  7. 7         TextView tv=new TextView(getApplicationContext());
  8. 8         tv.setText("hello world1");
  9. 9         tv.setBackgroundColor(Color.GRAY);
  10. 10         tv.setGravity(Gravity.CENTER);
  11. 11         int x=LayoutParams.MATCH_PARENT;
  12. 12         int y=LayoutParams.WRAP_CONTENT;
  13. 13         LinearLayout.LayoutParams params=new LinearLayout.LayoutParams(x,y);
  14. 14         this.addContentView(tv, params);
  15. 15         
  16. 16         
  17. 17     }
  18. 18 }
复制代码
在java代码中添加控件同样可以设置各种属性,如例中setText,setBackgroundColor等。效果:
1.jpg
2、addView

addView在父控件的基础上添加子控件,作用类似于在xml文件中添加一个控件:
  1. public class addViewActivity extends Activity {
  2.     @Override
  3.     protected void onCreate(Bundle savedInstanceState) {
  4.         super.onCreate(savedInstanceState);
  5.         setContentView(R.layout.activity_main);
  6.         LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
  7.         TextView tv = new TextView(getApplicationContext());
  8.         tv.setText("hello world2");
  9.         tv.setBackgroundColor(Color.GRAY);
  10.         tv.setGravity(Gravity.CENTER);

  11.         ll.addView(tv);

  12.     }

  13. }
复制代码
xml文件:
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2. 2     xmlns:tools="http://schemas.android.com/tools"
  3. 3     android:id="@+id/ll"
  4. 4     android:layout_width="match_parent"
  5. 5     android:layout_height="wrap_content"
  6. 6     android:orientation="vertical" >
  7. 7
  8. 8 </LinearLayout>
复制代码
同样可以添加控件的各种属性。效果:
1.jpg

论坛徽章:
59
2015七夕节徽章
日期:2015-08-24 11:17:25ChinaUnix专家徽章
日期:2015-07-20 09:19:30每周论坛发贴之星
日期:2015-07-20 09:19:42ChinaUnix元老
日期:2015-07-20 11:04:38荣誉版主
日期:2015-07-20 11:05:19巳蛇
日期:2015-07-20 11:05:26CU十二周年纪念徽章
日期:2015-07-20 11:05:27IT运维版块每日发帖之星
日期:2015-07-20 11:05:34操作系统版块每日发帖之星
日期:2015-07-20 11:05:36程序设计版块每日发帖之星
日期:2015-07-20 11:05:40数据库技术版块每日发帖之星
日期:2015-07-20 11:05:432015年辞旧岁徽章
日期:2015-07-20 11:05:44
发表于 2015-07-02 09:11 |显示全部楼层
一两个控件使用代码添加还行。如果太多还得使用Layout文件来定义。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP