安卓课本例子-02-使用Java控制UI界面

 1 package com.javaui;
 2 
 3 import android.graphics.Color;
 4 import android.support.v7.app.AppCompatActivity;
 5 import android.os.Bundle;
 6 import android.util.TypedValue;
 7 import android.view.Gravity;
 8 import android.view.ViewGroup;
 9 import android.widget.FrameLayout;
10 import android.widget.FrameLayout.LayoutParams;
11 import android.widget.TextView;
12 
13 public class MainActivity extends AppCompatActivity {
14 
15     @Override
16     protected void onCreate(Bundle savedInstanceState) {
17         super.onCreate(savedInstanceState);
18         FrameLayout frameLayout = new FrameLayout(this);
19         // 设置Activity中显示frameLayout
20         setContentView(frameLayout);
21         // 添加Text1
22         TextView text1 = new TextView(this);
23         // 设置显示的文字
24         text1.setText("在Java代码中控制UI界面");
25         // 设置文字的大小
26         text1.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
27         text1.setTextColor(Color.rgb(1, 1, 1));
28         frameLayout.addView(text1);
29         // 添加text2
30         TextView text2 = new TextView(this);
31         // 设置text2显示的文字
32         text2.setText("单击进入游戏");
33         // 设置text2文字大小
34         text2.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20);
35         // 设置text2文字颜色
36         text2.setTextColor(Color.rgb(1, 1, 1));
37         // 创建保存布局参数的对象
38         LayoutParams params = new LayoutParams(
39                 ViewGroup.LayoutParams.WRAP_CONTENT,
40                 ViewGroup.LayoutParams.WRAP_CONTENT);
41         // 设置居中显示
42         params.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
43         // 设置布局参数
44         text2.setLayoutParams(params);
45         frameLayout.addView(text2);
46     }
47 }

书本中的实例代码, 运行成功

posted @ 2019-04-02 16:57  HHZZHH  阅读(441)  评论(0编辑  收藏  举报