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

วิธีดึงชื่อ Activity ปัจจุบันใน Android

ภาพรวม

บทความนี้สาธิตวิธีดึงชื่อคลาส (Class Name) ของ Activity ปัจจุบัน โดยใช้ getClass().getName() หรือ getClass().getSimpleName()

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

Android Studio → File → New Project → Empty Activity

ขั้นตอนที่ 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"
    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: โค้ดหลัก (java/MainActivity.java)

package com.example.myapplication;

import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.text);

        // วิธีที่ 1: ชื่อเต็มรวม package
        String fullName = getClass().getName(); // com.example.myapplication.MainActivity

        // วิธีที่ 2: แค่ชื่อคลาส
        String simpleName = getClass().getSimpleName(); // MainActivity

        // วิธีที่ 3: จาก ComponentName (แม่นยำกว่าในบางกรณี)
        String componentName = getComponentName().getClassName();

        textView.setText("Full: " + fullName + "\n\nSimple: " + simpleName + "\n\nComponent: " + componentName);
    }
}

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

  • Logging/Debugging - รู้ว่าอยู่ Activity ไหน
  • Analytics - ส่งชื่อหน้าจอไป Analytics
  • Navigation - ตรวจสอบ Activity ปัจจุบันก่อน navigate
  • Testing - Espresso/UI Automator ตรวจสอบหน้าจอ

ดึงชื่อ Activity จาก Context อื่น

// ใน Fragment
String activityName = requireActivity().getClass().getSimpleName();

// ใน View (Custom View)
Context context = getContext();
if (context instanceof Activity) {
    String name = ((Activity) context).getClass().getSimpleName();
}

// จาก Intent
String callerActivity = getCallingActivity() != null ? getCallingActivity().getClassName() : "none";

ทดสอบ

รันแอป จะแสดงชื่อคลาสเต็มและชื่อสั้นของ MainActivity