使用Java代码来创建view

使用Java代码来创建view

一、简介

需要了解的知识

二、方法

1)java代码创建view方法
* 1、先建view对象

View view= View.inflate(this, R.layout.activity01, null);

* 2、在view中填充R.layout.activity01页面

View view= View.inflate(this, R.layout.activity01, null);
* 3、然后在view对象中添加各种控件(例如TextView,Button等),注意要转化成ViewGroup类型才可以添加

创建TextView控件

((RelativeLayout)view).addView(textView);
* 4、最后将view对象填充到页面,也就是把setContentView的值填充为view对象,

setContentView(view);


2)创建控件方法,以TextView为例
* 1、创建TextView对象

TextView textView=new TextView(this);
* 2、给TextView对象设置布局参数

LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);

textView.setLayoutParams(layoutParams);
* 3、给TextView对象设置其它属性

textView.setBackgroundColor(Color.CYAN);
textView.setText("你好,陌生人!!!");

三、代码实例

效果图

 

代码

fry.Activity01

 1 package fry;
 2 
 3 
 4 import com.fry.javaCreateView.R;
 5 
 6 import android.app.Activity;
 7 import android.graphics.Color;
 8 import android.os.Bundle;
 9 import android.view.View;
10 import android.view.ViewGroup.LayoutParams;
11 import android.widget.RelativeLayout;
12 import android.widget.TextView;
13 
14 public class Activity01 extends Activity{
15     @Override
16     protected void onCreate(Bundle savedInstanceState) {
17         // TODO Auto-generated method stub
18         setTitle("java代码创建view");
19         super.onCreate(savedInstanceState);
20         /*
21          * java代码创建view方法
22          * 1、先建view对象
23          * 2、在view中填充R.layout.activity01页面
24          * 3、然后在view对象中添加各种控件(例如TextView,Button等),注意要转化成ViewGroup类型才可以添加
25          * 4、最后将view对象填充到页面,也就是把setContentView的值填充为view对象,
26          * 
27          * 创建控件方法,以TextView为例
28          * 1、创建TextView对象
29          * 2、给TextView对象设置布局参数
30          * 3、给TextView对象设置其它属性
31          * 
32          */
33         View view= View.inflate(this, R.layout.activity01, null);
34         
35         LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT,
36                 LayoutParams.WRAP_CONTENT);
37         TextView textView=new TextView(this);
38         textView.setLayoutParams(layoutParams);
39         textView.setBackgroundColor(Color.CYAN);
40         textView.setText("你好,陌生人!!!");
41         
42         
43         ((RelativeLayout)view).addView(textView);
44         
45         
46         setContentView(view);
47     }
48 }
原文地址:https://www.cnblogs.com/Renyi-Fan/p/7279299.html