android控件——Spinner(下拉框)
程序员文章站
2023-12-28 12:00:34
...
效果图:
实现代码:
xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/s_main_spinner"
></Spinner>
</LinearLayout>
java:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Administrator on 2017/6/8 0008.
*/
public class SpinnerActivity extends AppCompatActivity {
private Spinner s_main_spinner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
s_main_spinner = (Spinner) findViewById(R.id.s_main_spinner);
//给下拉列表设置适配器
final String provinces[]={"湖南省","河南省","海南省"};
int images[]={R.drawable.dog,R.drawable.elephant,R.drawable.fox};
List<Map<String,Object>> list=new ArrayList<>();
for (int i = 0; i < provinces.length; i++) {
Map<String,Object> map=new HashMap<>();
map.put("title",provinces[i]);
map.put("image",images[i]);
list.add(map);
}
//适配器
//SimpleAdapter
SimpleAdapter adapterSpinner=new SimpleAdapter(this,list,android.R.layout.activity_list_item,new String[]{"title","image"},new int[]{android.R.id.text1,android.R.id.icon});
s_main_spinner.setAdapter(adapterSpinner);
//给下列列表设置选择事件
s_main_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(SpinnerActivity.this, provinces[i], Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
}