Created
July 7, 2021 11:37
-
-
Save AkaashSaini/a3f6e3207273763161bb1c2562d189e5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Spinner | |
It is used to create the drop down list of options from which we can select the option. | |
1. Layout | |
<LinearLayout | |
android:orientation="vertical" | |
android:layout_width="match_parent" | |
android:layout_height="match_parent" | |
android:layout_alignParentTop="true" | |
android:layout_alignParentLeft="true" | |
android:layout_alignParentStart="true"> | |
<Spinner | |
android:layout_width="match_parent" | |
android:layout_height="wrap_content" | |
android:id="@+id/spinner" /> | |
<Button | |
android:text="Button" | |
android:layout_width="match_parent" | |
android:layout_height="wrap_content" | |
android:id="@+id/button" /> | |
<TextView | |
android:text="TextView" | |
android:layout_width="match_parent" | |
android:layout_height="wrap_content" | |
android:id="@+id/textView" | |
android:textAppearance="@style/TextAppearance.AppCompat.Large" /> | |
</LinearLayout> | |
2. Java Code | |
public class MainActivity extends AppCompatActivity { | |
TextView tv; | |
Spinner sp; | |
Button b1; | |
String selected_item=""; | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
tv= (TextView) findViewById(R.id.textView); | |
sp=(Spinner) findViewById(R.id.spinner); | |
b1=(Button) findViewById(R.id.button); | |
// Spinner Drop down elements | |
List<String> op = new ArrayList<String>(); | |
op.add("CS"); | |
op.add("IT"); | |
op.add("EC"); | |
op.add("ME"); | |
op.add("CE"); | |
op.add("EE"); | |
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, op); | |
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); | |
sp.setAdapter(adapter); | |
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { | |
@Override | |
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) { | |
selected_item=sp.getItemAtPosition(position).toString(); | |
} | |
@Override | |
public void onNothingSelected(AdapterView<?> adapterView) { | |
} | |
}); | |
b1.setOnClickListener(new View.OnClickListener() { | |
@Override | |
public void onClick(View view) { | |
tv.setText(selected_item); | |
} | |
}); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment