Giới thiệu
Ví dụ này minh họa cách thiết lập tiêu đề (title) và phụ đề (subtitle) cho Action Bar trong ứng dụng Android.
Các bước thực hiện
Bước 1: Tạo dự án mới
Mở Android Studio, chọn File → New Project.
Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:app="https://schemas.android.com/apk/res-auto"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/text"
android:textSize="30sp"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Bước 3: Viết logic (src/MainActivity.java)
package com.example.myapplication;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
// Đặt tiêu đề và phụ đề cho Action Bar
getSupportActionBar().setTitle("Home");
getSupportActionBar().setSubtitle("sairam");
textView.setText("Tiêu đề là: Home");
}
}
Sử dụng setTitle() để đặt tiêu đề chính, setSubtitle() để đặt phụ đề hiển thị ngay dưới tiêu đề.
Chạy ứng dụng
Chạy ứng dụng trên thiết bị thật. Action Bar sẽ hiển thị tiêu đề Home và phụ đề sairam.
