Don't Miss

Spinner / dropdown in android

By on January 11, 2018

Activity.java

 

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

public class ExampleActivity extends AppCompatActivity {

private Spinner spinner;
private Button btnview;
private String cityname;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

spinner = (Spinner)findViewById(R.id.cities) ;

btnview=(Button)findViewById(R.id.button2);

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l)
{
cityname = spinner.getItemAtPosition(i).toString();
Toast.makeText(ExampleActivity.this,cityname, Toast.LENGTH_SHORT).show();
}

@Override
public void onNothingSelected(AdapterView<?> adapterView) {

}
});

btnview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(ExampleActivity.this,cityname, Toast.LENGTH_SHORT).show();
}
});

}

}

 

activity_main.xml

 

add string array to res/values style.xml 

ISLAMABAD
KARACHI
PESHAWAR
Queeta


<Spinner
android:id=”@+id/cities”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_alignParentTop=”true”
android:entries=”@array/cities_name”
android:layout_marginTop=”22dp”
/>

<Button
android:id=”@+id/button2″
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_below=”@+id/cities”
android:layout_centerHorizontal=”true”
android:layout_marginTop=”38dp”
android:text=”View Selected” />

 

About CodingBazz

Leave a Reply

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