使用spinner 做下拉对话框
今天因为需要,要做一个对话框,android自带的列表框无法满足这种效果:
先看看运行的效果图:
点击后有向下显示的对话框:
一下是实现的代码:
public class MainActivity extends Activity {
Button button;
View view;
AlertDialog.Builder alertBuidler;
ArrayAdapter<String> adapter;
LayoutInflater inflate;
private List<String> list = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
inflate = LayoutInflater.from(this);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
view = inflate.inflate(R.layout.alert_dialog, null);
Spinner spin = (Spinner)view.findViewById(R.id.spinner_City);
Spinner spin1 = (Spinner)view.findViewById(R.id.spinner_City1);
Spinner spin2 = (Spinner)view.findViewById(R.id.spinner_City2);
Spinner spin3 = (Spinner)view.findViewById(R.id.spinner_City3);
list.add("北京");
list.add("上海");
list.add("深圳");
list.add("南京");
list.add("重庆");
adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item, list);
//第三步:为适配器设置下拉列表下拉时的菜单样式。
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//第四步:将适配器添加到下拉列表上
spin.setAdapter(adapter);
spin1.setAdapter(adapter);
spin2.setAdapter(adapter);
spin3.setAdapter(adapter);
new AlertDialog.Builder(MainActivity.this).setView(view).show();
view = null; //这句话不能少,否则会抛出异常
}
});
}
}
主布局文件:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="click" />
</RelativeLayout>
弹出对话框的布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id= "@+id/widget28"
android:layout_width= "fill_parent"
android:layout_height= "fill_parent"
android:orientation= "vertical" >
<Spinner
android:id= "@+id/spinner_City"
android:layout_width= "fill_parent"
android:layout_height= "wrap_content" >
</Spinner>
<Spinner
android:id= "@+id/spinner_City1"
android:layout_width= "fill_parent"
android:layout_height= "wrap_content" >
</Spinner>
<Spinner
android:id= "@+id/spinner_City2"
android:layout_width= "fill_parent"
android:layout_height= "wrap_content" >
</Spinner>
<Spinner
android:id= "@+id/spinner_City3"
android:layout_width= "fill_parent"
android:layout_height= "wrap_content" >
</Spinner>
</LinearLayout>
其中的样式,可更具需要自行修改
Demo下载地址:
http://download.csdn.net/download/lyhdream/5192993