在Fragment中使用getIdentifier()方法,首先需要確保你在Activity或Fragment的上下文中調用它。以下是在Fragment中使用getIdentifier()方法的示例:
import android.content.Context;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
onCreate()方法中,你可以使用getActivity()方法獲取Activity的上下文,然后調用getIdentifier()方法:@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_example);
// 獲取Activity的上下文
Context context = getActivity();
// 使用getIdentifier()方法獲取資源ID
int resourceId = context.getResources().getIdentifier("your_resource_name", "string", context.getPackageName());
// 檢查資源ID是否有效
if (resourceId != 0) {
// 使用資源ID
} else {
// 資源ID無效,處理錯誤情況
}
}
請將"your_resource_name"替換為你想要獲取的資源名稱(例如,字符串、圖片等)。注意,getIdentifier()方法可能會返回0,表示資源未找到。在這種情況下,你需要處理這種情況。