Spinner下拉列表控件
程序员文章站
2022-05-15 09:54:29
...
布局代码:
这里写代码片
<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"
tools:context=".MainActivity" >
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<Spinner
android:id="@+id/sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</RelativeLayout>
布局图:
Java代码:
这里写代码片
package com.example.spinnerdemo;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
//创建数组
String[] names={"我的应用","我的小米","应用商店","游戏","小爱同学","全球上网","便签","文件管理","......",};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//导入布局文件
setContentView(R.layout.activity_main);
//获取控件,创建对象
Spinner sp=(Spinner) findViewById(R.id.sp);
final TextView tv=(TextView) findViewById(R.id.tv);
//指挥对象做事情
//创建适配器
sp.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_dropdown_item_1line, names));
//导包,重写方法
sp.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
String ss = arg0.getItemAtPosition(arg2).toString();
Toast.makeText(MainActivity.this, ss, 0).show();
tv.setText(ss);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
效果图: