liguofeng29’s blog

個人勉強用ブログだっす。

Androidのイベント処理 - システム設定情報取得(Configurationクラス)

Configurationクラスはデバイスの設定(ユーザ毎の設定、システム設定を含む)情報を表している。

Activity内では、下記方法でシステムのConfigurationオブジェクトを取得できる。
Configuration config = getResource().getConfiguration();

 

 

サンプルコード

activity_main.java
 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/text01"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/text02"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<EditText
android:id="@+id/text03"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<EditText
android:id="@+id/text04"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="設定情報取得"
android:onClick="getConfiguration" />
</LinearLayout>

 

 
MainActivity.java
 
package com.example.liguofeng.getconfiguration;

import android.content.res.Configuration;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

EditText orientation;
EditText touch;
EditText locale;

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

orientation = (EditText) findViewById(R.id.text01);
touch = (EditText) findViewById(R.id.text02);
locale = (EditText) findViewById(R.id.text03);
}

// ボタンクリックで設定情報取得
public void getConfiguration(View view) {
Configuration config = getResources().getConfiguration();
String orientation = config.orientation == Configuration.ORIENTATION_LANDSCAPE
? "横Screen" : "縦Screen";

String country = config.locale.getCountry();

String touch = config.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH
? "タッチ支援なし" : "タッチ支援あり";

this.orientation.setText(orientation);
this.touch.setText(touch);
this.locale.setText(country);
}
}