Created
December 2, 2025 10:33
-
-
Save sunmeat/50c61d2cb9d7232b87f6c34f82ef904a to your computer and use it in GitHub Desktop.
Spinner + adapter + custom item layout
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
| activity_main.xml: | |
| <?xml version="1.0" encoding="utf-8"?> | |
| <LinearLayout | |
| xmlns:android="http://schemas.android.com/apk/res/android" | |
| android:layout_width="match_parent" | |
| android:layout_height="match_parent" | |
| android:gravity="top" | |
| android:orientation="vertical"> | |
| <Spinner | |
| android:layout_width="match_parent" | |
| android:layout_height="wrap_content" | |
| android:id="@+id/spin1" /> | |
| </LinearLayout> | |
| ========================================================================================= | |
| MainActivity.java: | |
| package site.sunmeat.helloworld; | |
| import android.os.Bundle; | |
| import android.view.View; | |
| import android.widget.*; | |
| import androidx.appcompat.app.AppCompatActivity; | |
| import java.util.ArrayList; | |
| public class MainActivity extends AppCompatActivity { | |
| @Override | |
| protected void onCreate(Bundle savedInstanceState) { | |
| super.onCreate(savedInstanceState); | |
| setContentView(R.layout.activity_main); | |
| Spinner s = findViewById(R.id.spin1); | |
| var data = new ArrayList<String>(); | |
| data.add("apple"); | |
| data.add("banana"); | |
| data.add("coconut"); | |
| var adapter = new ArrayAdapter<>(this, | |
| // android.R.layout.simple_list_item_1, // стандартна страшна андроїдівська верстка | |
| R.layout.my_spinner_item, // кастомна верстка | |
| R.id.tv1, | |
| data); | |
| s.setAdapter(adapter); | |
| s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { | |
| public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) { | |
| Object item = parent.getItemAtPosition(pos); | |
| Toast.makeText(MainActivity.this, item + "", Toast.LENGTH_SHORT).show(); | |
| } | |
| public void onNothingSelected(AdapterView<?> parent) { | |
| } | |
| }); | |
| } | |
| } | |
| ========================================================================================= | |
| my_spinner_item.xml: | |
| <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" | |
| android:layout_width="match_parent" | |
| android:layout_height="match_parent"> | |
| <TextView | |
| android:id="@+id/tv1" | |
| android:fontFamily="casual" | |
| android:textSize="30sp" | |
| android:textColor="@color/orange" | |
| android:layout_width="match_parent" | |
| android:padding="10dp" | |
| android:layout_height="wrap_content"> | |
| </TextView> | |
| </LinearLayout> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment