以下范例是取自《Google Android SDK开发范例大全》,列举了一些个人认为比较简单实用的范例片段。
若无特别说明,均写在onCreate方法里,相关资源文件不一一列举,如有需要请联系本人。
一、读取手机分辨率
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
final String str = "手机分辨率是:" + dm.widthPixels + "," + dm.heightPixels;
textView.setText(str);
二、按钮事件
button1.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
//编写相关触发事件
}
};
三、弹出用户UI交互对话框
//点击按钮弹出提示框
button1.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
new AlertDialog.Builder(MainActivity.this)
.setTitle(R.string.app_about) //对话框标题
.setMessage(R.string.app_msg) //对话框内容
.setPositiveButton(
R.string.hello_world, //对话框按钮
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//对话框按钮触发事件
}
}
)
.show();
}
});
四、拖动相片特效
GalleryActivity.java
((Gallery) findViewById(R.id.myGallery1)).setAdapter(new ImageAdapter(this));
private Context myContext;
/**
* 使用R.drawable里的图片作为图库源,类型为整数数组
* 如果是android.R.drawable 就是读取系统自带的图库源
* */
private int[] myImageIds =
{
R.drawable.one,
R.drawable.two,
R.drawable.three
};
/** 构造器只有一个参数,即要存储Context **/
public ImageAdapter(Context c){this.myContext = c;}
/** 返回所有已定义的图片总数量 **/
@Override
public int getCount() {
return this.myImageIds.length;
}
/** 利用getItem方法,取得目前容器中图像的数组 **/
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
/** 取得目前欲显示的图像View,传入数组ID值使之读取与成像 **/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(this.myContext);
i.setImageResource(this.myImageIds[position]);
i.setScaleType(ImageView.ScaleType.FIT_XY);
/** 设置这个ImageView对象的宽高,单位为dip **/
i.setLayoutParams(new Gallery.LayoutParams(400, 400));
return i;
}
/** 依据距离中央的位移量 利用getScale返回的大小(0.0f to 1.0f) **/
public float getScale(boolean focused,int offset){
return Math.max(0, 1.0f/(float)Math.pow(2, Math.abs(offset)));
}
五、Menu菜单
主要是onCreateOptionsMenu,onOptionsItemSelected这两个方法
/** 创建Menu菜单 **/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, 0, 0, R.string.about);
menu.add(0, 1, 1, R.string.exit);
return super.onCreateOptionsMenu(menu);
}
/** Menu菜单选项的后续事件 **/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case 0:
break;
case 1:
openOptionDialog();
break;
}
return true;
}
public void openOptionDialog(){
new AlertDialog.Builder(MainActivity.this)
//.setTitle(R.string.app_about) //对话框标题
.setMessage(R.string.exit_msg) //对话框内容
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//对话框按钮触发事件
}
})
.setPositiveButton(
R.string.sure, //对话框按钮
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
}
)
.show();
}
六、程序加载中,请稍后...ProgressDialog与线程整合
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress);
textView = (TextView)findViewById(R.id.progressView);
button = (Button)findViewById(R.id.progressBtn);
button.setOnClickListener(myShowProgressBar);
}
Button.OnClickListener myShowProgressBar = new Button.OnClickListener(){
@Override
public void onClick(View v) {
final CharSequence strDialogTitle = getString(R.string.about);
final CharSequence strDialogBody = getString(R.string.app_msg);
myDialog = ProgressDialog.show(
ProgressActivity.this, //当前activity
strDialogTitle, //ProgressDialog 标题
strDialogBody); //ProgressDialog 内容
textView.setText(strDialogBody);
new Thread(){
public void run(){
try{
//此处可添加后台执行代码片段
//加载3秒
sleep(3000);
}catch(Exception e){
e.printStackTrace();
}finally{
//卸载所创建的myDialog对象
myDialog.dismiss();
}
}
}.start(); //开始运行线程
}
};
七、具有选择功能的对话框
ItemActivity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item);
textView = (TextView)findViewById(R.id.itemView);
button = (Button)findViewById(R.id.itemBtn);
button.setOnClickListener(myItemClickListener);
}
Button.OnClickListener myItemClickListener =
new Button.OnClickListener(){
@Override
public void onClick(View v) {
new AlertDialog.Builder(ItemActivity.this)
.setTitle(R.string.about)
.setItems(R.array.item_list,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
CharSequence strDialogBody = getString(R.string.alert_body);
String[] arylist = getResources().getStringArray(R.array.item_list);
new AlertDialog.Builder(ItemActivity.this)
//值得注意的时候arylist[which] 就是int which,获取到用户点击哪一个
.setMessage(strDialogBody + arylist[which])
.setNegativeButton(R.string.sure, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//可后续处理点击itemlist的动作
}
})
.show();
}
})
.show();
}
};
八、文本框输入结束立即显示到TextView
showView = (TextView)findViewById(R.id.showEdit);
final EditText editText = (EditText)findViewById(R.id.editTextid);
editText.setOnKeyListener(new EditText.OnKeyListener(){
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
showView.setText(editText.getText());
return false;
}
});
九、Toast消息框的提示使用方法
以第八范例为基础,关键字:Toast
Editable str;
str = editText.getText();
Toast.makeText(ItemActivity.this, "重大消息:" + str, Toast.LENGTH_LONG).show();
十、自定义下拉菜单模式,Spinner 与 setDropDownViewResource
private Spinner spinner;
private static final String[] spinnerList = {"广东","北京","香港"};
private ArrayAdapter<String> adapter;
spinner = (Spinner)findViewById(R.id.spinnerid);
//使用android提供的resourceid
adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,spinnerList);
/**
* 使用setDropDownViewResource可为自定义样式
* adapter.setDropDownViewResource(resource);
*/
//把arrayAdapter添加到Spinner
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
showView.setText("选择的是:" + spinnerList[arg2]);
//将spinner显示
arg0.setVisibility(View.VISIBLE);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
添加spinner
addbtn.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
String newText = spinnerEdittext.getText().toString();
//判断添加的值是否与已有相等
for(int i=0;i<adapter.getCount();i++){
if(newText.equals(adapter.getItem(i))){
return;
}
}
if(newText != ""){
//添加到adapter
adapter.add(newText);
//adapter的position
int position = adapter.getPosition(newText);
//下拉框选中显示新添加的值
spinner.setSelection(position);
//清空
spinnerEdittext.setText("");
}
}
});
删除spinner
removebtn.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v) {
if(spinner.getSelectedItem() != null){
//删除当前选项
adapter.remove(spinner.getSelectedItem().toString());
}
}
});