読者です 読者をやめる 読者になる 読者になる

liguofeng29’s blog

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

AndroidのUI - Spinner

   

activity_main.xml
 
<?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">

<Spinner
android:id="@+id/spinner01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/programming"
android:prompt="@array/programming"/>
<!-- Activity内でentriesを設定する -->
<Spinner
android:id="@+id/spinner02"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:prompt="@string/tip"/>

<TextView
android:id="@+id/textView01"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="10pt"/>

<TextView
android:id="@+id/textView02"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="10pt"/>/>

</LinearLayout>
 
array.xml
 

<resources>
<string-array name="programming">
<item>java</item>
<item>C</item>
<item>C++</item>
<item>C#</item>
</string-array>
</resources>

 

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

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

Spinner spinner01;
Spinner spinner02;
TextView textView01;
TextView textView02;

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

textView01 = (TextView) findViewById(R.id.textView01);
textView02 = (TextView) findViewById(R.id.textView02);

// Spinner設定
spinner01 = (Spinner) findViewById(R.id.spinner01);
spinner02 = (Spinner) findViewById(R.id.spinner02);

final String[] OS = {"Windows", "Android", "IOS", "Linux"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, OS);

// apdater設定
spinner02.setAdapter(adapter);


spinner01.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

// arrayのリソースを利用する
String[] stringArray = getResources().getStringArray(R.array.programming);
textView01.setText(stringArray[position] + "が選択されました");
}

@Override
public void onNothingSelected(AdapterView<?> parent) {

}
});

spinner02.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
textView02.setText(OS[position] + "が選択されました");
}

@Override
public void onNothingSelected(AdapterView<?> parent) {

}
});
}
}