Giới thiệu
Ví dụ này minh họa cách kiểm tra xem Action Bar có đang hiển thị trên màn hình hay không bằng phương thức isShowing().
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 và điền thông tin cần thiết.
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.view.MenuItem;
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);
// Cấu hình Action Bar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Home");
getSupportActionBar().setSubtitle("sairam");
// Kiểm tra Action Bar có đang hiển thị không
textView.setText("Action Bar hiển thị: " + getSupportActionBar().isShowing());
}
@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(menuItem);
}
}
Phương thức isShowing() trả về true nếu Action Bar đang hiển thị, ngược lại trả về false.
Chạy ứng dụng
Kết nối thiết bị thật, chạy ứng dụng. Màn hình sẽ hiển thị trạng thái hiển thị của Action Bar (true hoặc false).
