我需要创建一个只有三个值的下拉列表。我用spinner完成了这个。但是它看起来像This
但是我想创建这样的
所以当点击这个的时候它需要像普通的旋转器一样显示值。
我尝试了样式和设置选择器作为背景,但没有工作,我想到了自定义旋转器,但没有得到任何有用的。
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Spinner
android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/spinner_consigntype"
android:prompt="@string/spinner_consign" />
</LinearLayout>
Activity_Test.Java
package com.mkyong.android;
import android.app.Activity;
import android.os.Bundle;
public class Activity_Test extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity__test);
addListenerOnSpinnerItemSelection();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity__test, menu);
return true;
}
public void addListenerOnSpinnerItemSelection(){
Spinner spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
}
<<p> 侦听器/strong> public class CustomOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
在我的例子中,我得到的输出像第一个图像一样。但是对于下载的代码,它将输出显示为第二张图像。
make a selector_spinner.xml:
item android:state_pressed="true" android:drawable="@drawable/spinner_normal"
android:state_focused="true" android:drawable="@drawable/spinner_normal"
项目android:drawable="@drawable/spinner_normal"
在你的布局中使用这个选择器:
<Spinner
android:id="@+id/spinner_selection"
android:layout_width="0px"
android:layout_height="wrap_content"
android:layout_weight="1"
**android:background="@drawable/selector_spinner"**
android:entries="@array/contract_rate_type" />
然后在类文件中,
Spinner sp = (Spinner).findViewById(R.id.spinner_selection);