Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีตรวจสอบว่า Action Bar แสดงอยู่หรือไม่ใน Android

ภาพรวม

ตัวอย่างนี้สาธิตวิธีตรวจสอบสถานะการแสดงผลของ Action Bar โดยใช้เมธอด isShowing() ของ SupportActionBar

ขั้นตอนการสร้างโปรเจกต์

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

เลือก Theme ที่มี Action Bar (เช่น Theme.AppCompat.Light.DarkActionBar)

ขั้นตอนที่ 2: Layout (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:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="30sp"
        android:gravity="center" />

</LinearLayout>

ขั้นตอนที่ 3: โค้ดหลัก (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);

        // ตั้งค่า Action Bar
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setTitle("Home");
            getSupportActionBar().setSubtitle("sairam");
            
            // ตรวจสอบว่า Action Bar กำลังแสดงอยู่หรือไม่
            boolean isShowing = getSupportActionBar().isShowing();
            textView.setText("Action Bar แสดงอยู่: " + isShowing);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem menuItem) {
        if (menuItem.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(menuItem);
    }
}

จุดสำคัญ

  • getSupportActionBar() อาจคืนค่า null หากใช้ Theme ที่ไม่มี Action Bar (เช่น Theme.NoActionBar)
  • isShowing() คืนค่า true เมื่อ Action Bar มองเห็นได้ ไม่ได้ถูกซ่อนโดย hide()
  • ใช้ hide() และ show() เพื่อควบคุมการแสดงผลแบบไดนามิก

กรณีการใช้งานจริง

  • ซ่อน Action Bar เมื่อเล่นวิดีโอเต็มหน้าจอ
  • แสดง/ซ่อนตามการเลื่อนหน้าจอ (Scroll)
  • ตรวจสอบสถานะก่อนทำการเปลี่ยนแปลง UI