We can also called as "drop down list".
- Add below code in activity_main.xml file.
activity.main.xml
<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" >
<Spinner
android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/channel_arrays" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go" />
</LinearLayout>
- Here we use the array to add text in spinner.
- Add below array code in res > values > strings.xml file.
<string-array name="channel_arrays">
<item>Food - Food</item>
<item>SAB</item>
<item>SONY</item>
<item>M tv</item>
<item>Colors</item>
<item>Star Plus</item>
<item>Discovery</item>
<item>Histroy</item>
</string-array>
- Add below code in MainActivity.java file.
MainActivity.java
public class MainActivity extends Activity {
Spinner sp;
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp = (Spinner)findViewById(R.id.spinner1);
b = (Button)findViewById(R.id.button1);
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
b.setOnClickListener(new OnClickListener() {public void onClick(View v) {
Toast.makeText(MainActivity.this,"OnClickListener : "+"\nSpinner 1 : "+ String.valueOf(sp.getSelectedItem()),
Toast.LENGTH_SHORT).show();
}
});
}
}
No comments:
Post a Comment