一、使用JAVA代码控制UI界面
在代码中控制UI界面可以分为以下三个步骤。
- 创建布局管理器,可以是帧布局、表格布局、线性布局,并且设置布局管理器的的属性,例如,为布局管理器设置背景图片等。
- 创建具体的组件,可以是TextView、ImageView、EditText和Button等任何Android提供的组件,并且设置组件的布局和各种属性。
- 将创建的具体组件添加到布局管理器中。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout frameLayout=new FrameLayout(this);//创建帧布局管理器
frameLayout.setBackground(this.getResources().getDrawable(R.mipmap.two));//设置背景
setContentView(frameLayout);//设置在Activity中显示的frameLayout
TextView text1=new TextView(this);
text1.setText("在JAVA代码中控制UI界面");//设置显示文字
text1.setTextSize(TypedValue.COMPLEX_UNIT_PX,40);//设置文字大小,单位为像素
text1.setTextColor(Color.rgb(100, 100, 100));//设置文字的颜色
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
//设置布局高度和布局宽度
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
);//创建保存布局参数的对象
params.gravity = Gravity.CENTER;//设置为居中
text1.setLayoutParams(params);//设置布局参数
frameLayout.addView(text1);//将text1添加到布局管理器中
}
}
二、使用XML和JAVA代码混合控制UI界面
xml文件
<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id = "@+id/layout"
android:orientation = "horizontal"
android:rowCount="3"
android:columnCount="4"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
</GridLayout>
java文件
public class MainActivity extends AppCompatActivity {
private ImageView[] img = new ImageView[12];//声明一个保存ImageView组件的数组
private int[] imagePath = new int[]{
R.mipmap.one,R.mipmap.two,R.mipmap.one,R.mipmap.two,
R.mipmap.one,R.mipmap.two,R.mipmap.one,R.mipmap.two,
R.mipmap.one,R.mipmap.two,R.mipmap.one,R.mipmap.two,
};//声明并初始化一个保存访问图片的数组
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//网格布局管理器
GridLayout layout = findViewById(R.id.layout);//获取XML文件中定义的线性布局管理器
for(int i = 0;i<imagePath.length;i++){
img[i] = new ImageView((MainActivity.this));//创建一个ImageView组件
img[i].setImageResource(imagePath[i]);//为imageView组件指定要显示的图片
img[i].setPadding(2,2,2,2);//设置imageView组件的内边框
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(116,68);//图片大小
img[i].setLayoutParams(params);
layout.addView(img[i]);//加入布局管理器中
}
}
}