285
No
SprinnerActivity
package com.example.choi.ex02;
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 SprinnerActivity extends AppCompatActivity {
//1.변수 선언
TextView txtResult;
Spinner spinner1;
String[] arr={"포도", "사과", "배", "귤", "딸기", "감", "대추"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sprinner);
//2.객체 생성
txtResult=(TextView)findViewById(R.id.txtResult);
spinner1=(Spinner)findViewById(R.id.spinner1);
//3. 아답터 생성
//new ArrayAdapter<자료형>(컨텍스트, 레이아웃, 데이터)
//Context(컨텍스트) : 문맥, 흐름, 현재 화면
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, arr);
//4. 스피너에 아답터를 연결시킴(데이터 뷰로 변환됨)
spinner1.setAdapter(adapter);
//5.스피너의 아이템 선택 이벤트
spinner1.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
//아이템을 선택했을 때
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//스피너의 선택한 아이템을 텍스트뷰에 출력
txtResult.setText(arr[position]);
}
//아이템을 선택하지 않았을 때
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
spinner.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/sprinner"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.choi.ex02.SprinnerActivity">
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/txtResult" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/spinner1"
android:layout_below="@+id/txtResult"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="18dp" />
</RelativeLayout>
댓글 ( 4)
댓글 남기기