Screenshots :
activity_main.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.chantisandroid.spinnerexample.MainActivity">
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/spinner"
android:layout_above="@+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginBottom="82dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/textView"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
MainActivity.java :
package com.chantisandroid.spinnerexample;
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 implements AdapterView.OnItemSelectedListener {
Spinner spinner;
TextView textView;
String[] NAMES = { "Android","Java","Oracle",".Net","Sap","Php" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textView);
spinner = (Spinner)findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(this);
ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,NAMES);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(aa);
}
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String str = spinner.getSelectedItem().toString();
textView.setText(str);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
No comments:
Post a Comment