5.13
UI 布局与事件处理
掌握了基础的项目搭建后,接下来要深入学习 UI 布局和事件处理。安卓提供了多种布局方式,如 LinearLayout(线性布局)、RelativeLayout(相对布局)、ConstraintLayout(约束布局)等。
以 LinearLayout 为例,它可以让子视图在水平或垂直方向上依次排列。下面是一个水平 LinearLayout 的代码示例,包含两个 Button:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2" />
在事件处理方面,比如我们要为 Button 添加点击事件。在 MainActivity.java 中:
package com.example.buttonclick;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Button 1 Clicked", Toast.LENGTH_SHORT).show();
}
});
Button button2 = findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Button 2 Clicked", Toast.LENGTH_SHORT).show();
}
});
}
}
这样,当用户点击按钮时,就会弹出相应的 Toast 提示。通过学习 UI 布局和事件处理,你可以打造出更具交互性的安卓应用界面。
浙公网安备 33010602011771号