通常、スピナークラスを使い、ドロップダウンリストを配置すると以下のような画面になる。
そうです、ドロップダウンリスト内の文字サイズが小さいのです。これは、Android標準のスピナーを使用すると文字サイズが固定されてしまうからです。スピナー内にtextsizeを指定しても、文字サイズは変更できません。今回は、このドロップダウンリスト内の文字サイズをどうやって変更するかについてふれたいと思います。
1.スピナーを配置
下記コードはドロップダウンリストのみを設置しています。ドロップダウンリスト内のアイテムについては別ファイルで追加します。
【main_activity.xml】
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="@dimen/activity_vertical_margin"
tools:context="com.example.User.spinnertest.MainActivity">
<Spinner
android:id="@+id/Spinner"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
</RelativeLayout>
2.独自のスピナーを作成
下記二つのコードはandroid標準のスピナーである「simple_spinner_item.xml」と「simple_spinner_dropdown_item.xml」の代わりに独自のスピナーを作成しました
【spinner_item.xml】
<?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" style="?android:attr/spinnerItemStyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="24sp" android:ellipsize="marquee"/>
【spinner_dropdown_item.xml】
<?xml version="1.0" encoding="utf-8"?> <CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android" style="?android:attr/spinnerItemStyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="24sp" />
3.スピナー内のアイテムを定義
下記コードはドロップダウンリスト内のアイテムを作成しています
【strings.xml】
<resources>
<string name="app_name">Spinner Test</string>
<string-array name="sample_array">
<item>Japanese</item>
<item>English</item>
</string-array>
</resources>
4.作成したスピナーを動的にセット
下記コードは上記1~3で作成したスピナーを動的にセットしています
【MainActivity.java】
package com.example.User.spinnertest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class MainActivity extends Activity {
private Spinner selectSpinner;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.title);
// android.R.Layout.simple_spinner_itemをR.layout.spinner_itemに変更
ArrayAdapter adapter = ArrayAdapter.createFromResource(this, R.array.sample_array, R.layout.spinner_item);
// android.R.Layout.simple_spinner_dropdown_itemをR.layout.spinner_dropdown_itemに変更
adapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
selectSpinner = (Spinner) findViewById(R.id.Spinner);
selectSpinner.setAdapter(adapter);
selectSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// ここにスピナー内のアイテムを選択した際の処理を書く
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// スピナーでは使用しないようですが、ないといけないのでこのまま放置
}
});
}
}
ドロップダウンリスト内の文字サイズを変更することができました。





