Android Spinner下拉框使用
Posted 彬sir哥
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android Spinner下拉框使用相关的知识,希望对你有一定的参考价值。
Spinner下拉框效果如下:
1.activity_main.xml,Spinner下拉框
<?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:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="黑色色块:" />
<Spinner
android:id="@+id/sp_color_black"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="@array/spinarr_color_black" />
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:text="666666"/>
</LinearLayout>
在res的values目录下创建array.xml文件
array.xml文件内容:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="spinarr_color_black">
<item>黑色</item>
<item>白色</item>
<item>蓝色</item>
<item>绿色</item>
<item>黄色</item>
<item>红色</item>
<item>紫色</item>
<item>粉红色</item>
<item>薄荷色</item>
</string-array>
</resources>
2.MainActivity.java,Spinner下拉框使用
public class MainActivity extends AppCompatActivity {
private Spinner sp_color_black;
private TextView mtextview;
private int color_black;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp_color_black = (Spinner) findViewById(R.id.sp_color_black);
mtextview = (TextView) findViewById(R.id.textview);
sp_color_black.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String str_color_black = getResources().getStringArray(R.array.spinarr_color_black)[position];
if (str_color_black.equals("黑色")) {
color_black = Color.BLACK;
} else if (str_color_black.equals("白色")) {
color_black = Color.WHITE;
} else if (str_color_black.equals("蓝色")) {
color_black = Color.BLUE;
} else if (str_color_black.equals("绿色")) {
color_black = Color.GREEN;
} else if (str_color_black.equals("黄色")) {
color_black = Color.YELLOW;
} else if (str_color_black.equals("红色")) {
color_black = Color.RED;
} else if (str_color_black.equals("紫色")) {
color_black = Color.parseColor("#9370DB");
} else if (str_color_black.equals("粉红色")) {
color_black = Color.parseColor("#ffc0cb");
} else if (str_color_black.equals("薄荷色")) {
color_black = Color.parseColor("#BDFCC9");
} else {
color_black = Color.BLACK;
}
mtextview.setTextColor(color_black);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
以上是关于Android Spinner下拉框使用的主要内容,如果未能解决你的问题,请参考以下文章