0x00 效果图

e46f5df0cce5

0x01 定义Spinner视图

在drawable包下, 新建一个xml文件spinner_background.xml, 自定义Spinner的背景:

android:endColor="@color/moccasin"

android:startColor="#E8EBEF"

android:type="linear" />

android:color="#000000" />

android:left="3dp"

android:right="3dp"

android:top="3dp" />

(渐变色效果)效果如下:

e46f5df0cce5

0x02 定义一个Theme

在res/values/styles.xml中添加一个style, 然后在Spinner添加这个Theme:

@drawable/spinner_background

10dp

10dp

10dp

0dp

3dp

5dp

@color/lemon_chiffon

0x03 添加Spinner控件

在想要添加Spinner控件的layout里添加Spinner控件:

android:id="@+id/spinner_service"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:layout_marginTop="20dp"

android:focusableInTouchMode="true"

android:scrollbars="vertical"

android:theme="@style/spinnerstyle">

0x04 添加Spinner里的选项字符串数组

这里我在res/values中添加了一个str_array_services.xml:

@string/str_select_service

@string/str_health_self

@string/str_hs_project

@string/str_com_care

@string/str_find_people

@string/str_dormitory

那些@string/xxx在strings.xml定义这些字符串.(这里为了更好的耦合性, 可以设置成多个语言版本)

0x05 在Activity或Fragment中实例化Spinner

public class LoginActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

private Spinner mSpinner;

@Override

protected void onCreate(@Nullable Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_login);

mSpinner = findViewById(R.id.spinner_service);

mSpinner.setOnItemSelectedListener(this);

ArrayAdapter adapter = ArrayAdapter.createFromResource(this,

R.array.services_array, android.R.layout.simple_spinner_item);

adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);

mSpinner.setAdapter(adapter);

}

@Override

public void onItemSelected(AdapterView> parent, View view, int position, long id) {

}

@Override

public void onNothingSelected(AdapterView> parent) {

// Another interface callback

}

}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐