4.8 自定义下拉菜单模式--Spinner与setDropDownViewResource
先贴上代码.
package edu.cquptzx.Spinner;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
publicclass SpinnerActivity extends Activity {
privatestaticfinal String[] countriesStr = {"北京市","上海市","天津市","重庆市"};
private TextView myTextView;
private Spinner mySpinner;
private ArrayAdapter<String> madapter ;
Animation mAnimation;
/** Called when the activity is first created. */
@Override
publicvoid onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//根据Id获得对象;
myTextView = (TextView) findViewById(R.id.textView1);
mySpinner =(Spinner)findViewById(R.id.spinner1);
//新建适配器
madapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item,countriesStr);
//自定义下拉菜单样式定义在/layout下.
madapter.setDropDownViewResource(R.layout.layout_dropdown);
//ArrayAdapter添加到Spinner对象中.
mySpinner.setAdapter(madapter);
//将myspinner添加到OnItemSelectedListener
mySpinner.setOnItemSelectedListener
(new Spinner.OnItemSelectedListener()
{
@Override
publicvoid onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
//将所选mySpinner的值赋值给TextView
myTextView.setText("选择的是" + countriesStr[position]);
//显示Spinner
view.setVisibility(View.VISIBLE);
}
@Override
publicvoid onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
}
);
//取得Animation定义目录下文件
mAnimation = AnimationUtils.loadAnimation(this, R.anim.my_anim);
//为mySpinner添加OnTouchListener
mySpinner.setOnTouchListener(new Spinner.OnTouchListener()
{
publicboolean onTouch(View v, MotionEvent event)
{
//设置动画
v.startAnimation(mAnimation);
//隐藏mySpinner
//v.setVisibility(View.INVISIBLE);
returnfalse;
}
});
}
}