一、使用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]);//加入布局管理器中
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/168295.html
標籤:其他
