홍드로이드의 야매코딩

#20 안드로이드 스튜디오 스피너 (Spinner) 드롭다운 메뉴 예제 [ 홍드로이드 ] 본문

Android Java

#20 안드로이드 스튜디오 스피너 (Spinner) 드롭다운 메뉴 예제 [ 홍드로이드 ]

홍드로이드 2019. 6. 8. 00:29



<res/values/array.xml>

res폴더 - > values 폴더 -> array.xml을 만드시고 코딩해주세요 !

1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="test">
        <item>홍드</item>
        <item>귀요미</item>
        <item>존잘</item>
    </string-array>
</resources>
cs



<activity_main.xml>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <Spinner
        android:id="@+id/spinner"
        android:layout_width="150dp"
        android:layout_height="40dp"
        android:entries="@array/test">
    </Spinner>
 
    <TextView
        android:id="@+id/tv_result"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="드롭다운 결과"/>
 
</LinearLayout>
cs








<MainActivity.java>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.example.spinnerexample;
 
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.TextView;
 
public class MainActivity extends AppCompatActivity {
 
    private Spinner spinner;
    private TextView tv_result;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        spinner = (Spinner)findViewById(R.id.spinner);
        tv_result = (TextView)findViewById(R.id.tv_result);
 
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                tv_result.setText(parent.getItemAtPosition(position).toString());
            }
 
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
 
            }
        });
 
    }
}
 
cs


Comments