As the title says. Since it is a memo for myself, I will omit the explanation. There were many places where I got stuck, so I hope it will be useful and I will share it.
Development environment: Android Studio 3.1.3 (Mac) Language: java
MainActivity.java
package com.example.ktakeda.numberpicker;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.TextView;
import android.content.res.Resources;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;
import static com.example.ktakeda.numberpicker.R.array;
public class MainActivity extends Activity {
NumberPicker numPicker;
Button button1;
TextView textView1;
//Within initViews, strings.Change to read from xml
// final String[] pref = {"tokyo", "chiba", "kanagawa"};
//Generate view?
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViews();
initViews();
}
//Get element of v
private void findViews(){
numPicker = (NumberPicker)findViewById(R.id.numPicker);
button1 = (Button)findViewById(R.id.button1);
textView1 = (TextView)findViewById(R.id.textView1);
}
//processing
private void initViews(){
// getResources
Resources res = getResources();
final String[] pref = res.getStringArray(R.array.pref_array);
//Put null first, prevent the app from crashing
numPicker.setDisplayedValues(null);
//Setting
numPicker.setDisplayedValues(pref);
numPicker.setMinValue(1);
numPicker.setMaxValue(pref.length);
button1.setOnClickListener(new OnClickListener(){
//Are you there?
@Override
public void onClick(View v) {
int idx = numPicker.getValue();
textView1.setText(pref[idx - 1]);
}
});
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_gravity="center"
android:textSize="30dp"/>
<NumberPicker
android:id="@+id/numPicker"
android:layout_width="200sp"
android:layout_height="wrap_content"
android:layout_gravity="center"/>
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="OK"/>
</LinearLayout>
strings.xml
<resources>
<string name="app_name">numberPicker</string>
<string-array name="pref_array">
<item>Tokyo</item>
<item>Kanagawa</item>
<item>Chiba</item>
<item>Okinawa</item>
</string-array>
</resources>
Recommended Posts