Set textview inside spinner in android example tutorial

How to create custom spinner with TextView layout.

In this tutorial we are creating two layout files first one is activity_main.xml file which contain spinner widget and the second is textview_layout.xml file which holds TextView widget, After that we are defining string array and setting up string array inside TextView then setting up textview into spinner. So here is the complete step by step tutorial for Set textview inside spinner in android example tutorial.

android-project-download-code-button

How to Set textview inside spinner in android example tutorial.

Code for MainActivity.java file.

 package com.spinnerwithtextview_android_examples.com;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

public class MainActivity extends Activity {

 Spinner spinnerwithTextView;
 
 String[] Subject = new String[]{
 "Maths",
 "Hindi",
 "English",
 "Computer"
 };
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 spinnerwithTextView = (Spinner)findViewById(R.id.spinner1);
 
 ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
 this,R.layout.textview_layout,Subject );
 
 spinnerArrayAdapter.setDropDownViewResource(R.layout.textview_layout);
 
 spinnerwithTextView.setAdapter(spinnerArrayAdapter);
 }
}

Code for activity_main.xml layout file.

 <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"
 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.spinnerwithtextview_android_examples.com.MainActivity" >

 <Spinner
 android:id="@+id/spinner1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_centerVertical="true" />

 

</RelativeLayout>

Code for textview_layout.xml file.

 <?xml version="1.0" encoding="utf-8"?>
<TextView
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:padding="12dp"
 android:textColor="#000505"
 android:textAppearance="?android:attr/textAppearanceMedium"
 
 />

Screenshot :

Set textview inside spinner in android example tutorial

Click here to download Set textview inside spinner in android example tutorial project.

Leave a Reply

Your email address will not be published. Required fields are marked *