以编程方式创建用户界面

作者:追风剑情 发布于:2015-7-26 12:08 分类:Android

使用代码创建用户界面是一个非常费力的工作。因此,只有在必要时才使用代码来动态生成用户界面。

  1. package com.example.androidtest;
  2.  
  3. import android.app.Activity;
  4. import android.os.Bundle;
  5. import android.view.Menu;
  6. import android.view.MenuItem;
  7. import android.view.ViewGroup.LayoutParams;
  8. import android.widget.Button;
  9. import android.widget.LinearLayout;
  10. import android.widget.TextView;
  11.  
  12. public class UICodeActivity extends Activity {
  13.  
  14. @Override
  15. protected void onCreate(Bundle savedInstanceState) {
  16. super.onCreate(savedInstanceState);
  17. //setContentView(R.layout.activity_uicode);//必须注释掉
  18. LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
  19. LinearLayout layout = new LinearLayout(this);
  20. layout.setOrientation(LinearLayout.VERTICAL);
  21. TextView tv = new TextView(this);
  22. tv.setText("This is a TextView");
  23. tv.setLayoutParams(params);
  24. Button btn = new Button(this);
  25. btn.setText("This is a Button");
  26. btn.setLayoutParams(params);
  27. layout.addView(tv);
  28. layout.addView(btn);
  29. LinearLayout.LayoutParams layoutParam = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
  30. this.addContentView(layout, layoutParam);
  31. }
  32. }

运行效果

11111111111.png

标签: Android

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号