一  android组件的用法举例

1.TextView   文本视图

  TextView中有好多属性,

1.跑马灯的属性,

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"
android:text="跑 马 灯 效 果" />

2.省略号、单行模式

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:singleLine="true"
android:text="末尾省略号效果 welcome to the android world!!!" />

3.字体颜色和大小

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="字体颜色和大小"
android:textColor="#FF6100"
android:textSize="20sp" />

4.邮箱、电话号码、网站、地图等的链接


<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:autoLink="email"
android:background="@android:color/white"
android:drawableRight="@drawable/right"
android:gravity="center_vertical"
android:linksClickable="true"
android:text=" TextView包含图片1150580768@qq.com"
android:textColor="@android:color/black" />

实现的效果图如下:



2.Button   按钮

  1.button中最常用的是按钮选择器,这样能够更好的和我们交互,具体实现如下,需在drawable文件夹下建立一个btn_selector.xml文件,代码如下:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<!-- 按下状态 -->
<item android:drawable="@drawable/btn_press" android:state_pressed="true"/>
<!-- 获取焦点 -->
<item android:drawable="@drawable/btn_foucus" android:state_focused="true"/>
<!-- 正常状态 -->
<item android:drawable="@drawable/btn_normal"/>

</selector>

在Button组件中引用的方法如下:

<Button
android:id="@+id/test_seleter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/btn_selector"
android:text="按下会改变图片的背景"/>

实现的效果如下:



2.Button还有一个最重要的是按钮的点击事件,同样需要一个Button组件


<Button
android:id="@+id/btn1"
android:drawableLeft="@drawable/btn_left"
android:drawableRight="@drawable/btn_right"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:background="@drawable/btn_bg"
android:text="好友空间动态"/>


实现监听事件的是OnClickListener事件


Button btn1=(Button)findViewById(R.id.btn1);
btn1.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(AndroidDemoActivity.this, "亲、你点击了Button按钮!!",Toast.LENGTH_LONG).show();
}
});

效果如图:



3.ImageView   图片视图

  1.ImageView有时候可以实现logo的欢迎界面比如

首先建立一个LogoActivity

package com.nysit.wj;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.ImageView;

public class LogoActivity extends Activity {

AlphaAnimation startAnimation;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// 全屏设置
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);

setContentView(R.layout.imageview);
ImageView logo = (ImageView) findViewById(R.id.logo);
// 设置启动的时候的透明度、持续的时间等
startAnimation = new AlphaAnimation(0.5f, 1.0f);
startAnimation.setDuration(3000);
logo.startAnimation(startAnimation);
startAnimation.setAnimationListener(new AnimationListener() {

@Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub

}

@Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub

}

@Override
public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub
// 动画效果结束的时候跳转
Intent intent = new Intent(LogoActivity.this,
AndroidDemoActivity.class);
startActivity(intent);
LogoActivity.this.finish();
}
});
}

}


布局就一个简单的ImageView组件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@android:color/white"
android:gravity="center"
android:orientation="vertical" >

<ImageView
android:id="@+id/logo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/splashscreen_logo" />

</LinearLayout>

效果呢就是我们常见的QQ空间的欢迎界面,分享生活,留住感动,有半透明0.5f到全透明1.0f



2.imageview也有监听事件,最常用的是OnClickListener 事件,这个时候它和button组件的用法很相似


ImageView logoimage=(ImageView)findViewById(R.id.logo);
logoimage.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(AndroidDemoActivity.this, "亲、你点击了ImageView 图片!!",Toast.LENGTH_LONG).show();

}
});

4.EditText    编辑框

   EditText是安卓中经常使用的输入框

1.以密文的形式显示

<!-- 以密文的形式显示 -->

<EditText
android:layout_width="fill_parent"
android:layout_height="40dip"
android:background="@drawable/btn_bg"
android:password="true" />


2.自动检测输入更正

<!-- 自动检测输入更正 -->

<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:autoText="true"
android:text="亲、给个评价呗!!!"
android:textColor="#FF6100" />


3.设置允许输入的字符

<!-- 设置允许输入的字符 -->

<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:digits="123456789.+-*/\n()" />

显示的效果如下:


5.Dialog   对话框


1.对话框我们用的非常多,下面看一个较为复杂点的Dialog的用法,可以再dialog中输入交互内容,进行交互。

这样需要在dialog中实现一个布局

<EditText
android:id="@+id/qq"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="请输入QQ:1150580768" />

<EditText
android:id="@+id/pingjia"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="亲、给个评价呗!!!" />


实现把这个布局添加到Dialog中的方法如下

LayoutInflater layoutInflater=LayoutInflater.from(AndroidDemoActivity.this);
final View dialogview=layoutInflater.inflate(R.layout.dialog, null);
new AlertDialog
.Builder(AndroidDemoActivity.this)
.setIcon(R.drawable.wawa)
.setTitle("亲、给个评价呗!!")
.setView(dialogview)
.setPositiveButton("提交评价", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub

EditText pingjia=(EditText)dialogview.findViewById(R.id.pingjia);
EditText qq=(EditText)dialogview.findViewById(R.id.qq);

String pingjiacontext=pingjia.getText().toString();
String qqcontext=qq.getText().toString();

SmsManager smsmanget=SmsManager.getDefault();
List<String> messages=smsmanget.divideMessage((pingjiacontext+"\n"+qqcontext));
for (String text : messages) {

smsmanget.sendTextMessage("15290336267", null, text, null, null);

}
Toast.makeText(AndroidDemoActivity.this, "亲、多谢你的评价,评价内容是\n"+messages, Toast.LENGTH_LONG).show();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(AndroidDemoActivity.this, "亲、你点击了取消按钮!!", Toast.LENGTH_LONG).show();
}
})
.create()
.show();

运行的效果如下:



2.下面介绍一个简单的对话框方法


TextView msg = new TextView(this);
msg.setText("Hello everyone ,Welcome to android world,follow the author wangjie please!!!");

new AlertDialog.Builder(AndroidDemoActivity.this)
.setIcon(R.drawable.wawa)
.setTitle("跟着王杰学android")
.setView(msg)
  //.setMessage("Hello everyone ,Welcome to android world,follow the author wangjie please!!!") .setPositiveButton("确定", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {
Toast.makeText(AndroidDemoActivity.this,
"亲、你点击了取消按钮!!", Toast.LENGTH_LONG).show();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(AndroidDemoActivity.this,
"亲、你点击了取消按钮!!", Toast.LENGTH_LONG).show();
}
}).create().show();

效果图如下




6. ProgressDialog   进度对话框

简单的进度对话框 使用方法如下:

ProgressDialog progressDialog;
Handler handler;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.button);

Button btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

showDialog(0);
}
});
handler = new Handler() {
public void handleMessage(Message msg) {

super.handleMessage(msg);
switch (msg.what) {
case 0:
// 每次增加1
progressDialog.incrementProgressBy(1);
if (progressDialog.getProgress() >= 100) {
progressDialog.dismiss();
}
break;

default:
break;
}
};
};

}

@Override
public Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
switch (id) {
case 0:
progressDialog = new ProgressDialog(this);
progressDialog.setMax(100);
progressDialog.setProgressStyle(progressDialog.STYLE_HORIZONTAL);
progressDialog.setTitle("进度对话框");
// 设置进度对话框不能用时候回退按钮关闭
progressDialog.setCancelable(false);

break;

default:
break;
}
return progressDialog;
}

@Override
public void onPrepareDialog(int id, Dialog dialog) {
// 每次弹出对话框时被回调以动态更新对话框内容的方法
// TODO Auto-generated method stub
super.onPrepareDialog(id, dialog);
switch (id) {
case 0:
progressDialog.incrementProgressBy(-progressDialog.getProgress());
new Thread() {

public void run() {
// TODO Auto-generated method stub
while (true) {

handler.sendEmptyMessage(0);
if (progressDialog.getProgress() >= 100) {
break;
}
try {
Thread.sleep(30);
} catch (Exception e) {
// TODO: handle exception
}
}
}
}.start();
break;

default:
break;
}
}

实现的效果如下:



7.列表对话框

简单的布局如下

<EditText
android:id="@+id/edit01"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

<Button
android:id="@+id/btn1"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:background="@drawable/btn_bg"
android:drawableLeft="@drawable/btn_left"
android:drawableRight="@drawable/btn_right"
android:text="好友空间动态" />

实现的代码如下:


String[] items = null;
EditText editText;

// String[] items={"南阳理工学院","软件学院","软件工程","10软工移动3班"};

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.button);
items = getResources().getStringArray(R.array.colledge);

Button btn1 = (Button) findViewById(R.id.btn1);
editText = (EditText) findViewById(R.id.edit01);
btn1.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

showDialog(0);
}
});

}

@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub

Dialog dialog = null;
Builder builder = new AlertDialog.Builder(this);
switch (id) {
case 0:

// builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.wawa)
.setTitle("列表对话框")
.setItems(R.array.colledge,
new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
editText.setText("你选择的是:"
+ getResources().getStringArray(
R.array.colledge)[which]);
}
})
.setPositiveButton("确定",
new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Toast.makeText(AndroidDemoActivity.this,
"你点击了确定按钮!!", Toast.LENGTH_SHORT)
.show();
}
})
.setNegativeButton("取消",
new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
editText.setText("你取消了选择");
}
}).create();

dialog = builder.create();
break;

}
return dialog;
}

实现的效果如下:




8.单选钮对话框

简单的布局如下

<EditText
android:id="@+id/edit01"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

<Button
android:id="@+id/btn1"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:background="@drawable/btn_bg"
android:drawableLeft="@drawable/btn_left"
android:drawableRight="@drawable/btn_right"
android:text="好友空间动态" />

实现的代码如下


String[] items = null;
EditText editText;

// String[] items={"南阳理工学院","软件学院","软件工程","10软工移动3班"};

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.button);
items = getResources().getStringArray(R.array.colledge);

Button btn1 = (Button) findViewById(R.id.btn1);
editText = (EditText) findViewById(R.id.edit01);
btn1.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

showDialog(0);
}
});

}

@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub

Dialog dialog = null;
Builder builder = new AlertDialog.Builder(this);
switch (id) {
case 0:

// builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.wawa)
.setTitle("单选按钮对话框")
.setSingleChoiceItems(R.array.colledge, 0,
new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
editText.setText("你选择的是:"
+ getResources().getStringArray(
R.array.colledge)[which]);
}
})
.setPositiveButton("确定",
new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Toast.makeText(AndroidDemoActivity.this,
"你点击了确定按钮!!", Toast.LENGTH_SHORT)
.show();
}
})
.setNegativeButton("取消",
new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
editText.setText("你取消了选择");
}
}).create();

dialog = builder.create();
break;

}
return dialog;
}

实现的效果如下




9.多选按钮对话框

简单的布局如下

<EditText
android:id="@+id/edit01"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

<Button
android:id="@+id/btn1"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:background="@drawable/btn_bg"
android:drawableLeft="@drawable/btn_left"
android:drawableRight="@drawable/btn_right"
android:text="好友空间动态" />

实现的代码如下


String[] items = null;
EditText editText;
// String[] items={"南阳理工学院","软件学院","软件工程","10软工移动3班"};
boolean[] mulFlags = new boolean[] { true, false, false, false };

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.button);
items = getResources().getStringArray(R.array.colledge);

Button btn1 = (Button) findViewById(R.id.btn1);
editText = (EditText) findViewById(R.id.edit01);
btn1.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

showDialog(0);
}
});

}

@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub

Dialog dialog = null;
Builder builder = new AlertDialog.Builder(this);
switch (id) {
case 0:
// builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.wawa)
.setTitle("多选按钮对话框")
.setMultiChoiceItems(R.array.colledge, mulFlags,
new DialogInterface.OnMultiChoiceClickListener() {

@Override
public void onClick(DialogInterface dialog,
int which, boolean isChecked) {
// TODO Auto-generated method stub

mulFlags[which] = isChecked;
String result = "你选择的是:";
for (int i = 0; i < mulFlags.length; i++) {
if (mulFlags[i]) {
result = result + items[i] + " ";
}
}

editText.setText(result.substring(0,
result.length() - 1));

}
})
.setPositiveButton("确定",
new DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Toast.makeText(AndroidDemoActivity.this,
"你点击了确定按钮!!", Toast.LENGTH_SHORT)
.show();
}
})
.setNegativeButton("取消",
new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
editText.setText("你取消了选择");
}
}).create();

dialog = builder.create();
break;

}
return dialog;
}


实现的效果如下




10.Spinner 下拉列表控件

下拉列表框在应用中也经常使用,下面就看看它的简单的实现方法

android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />

<Spinner
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="50dip" />

动态实现的方法


TextView textView;
Spinner spinner;
int[] images = { R.drawable.image1, R.drawable.image2, R.drawable.image3,
R.drawable.image4, R.drawable.wawa };
int[] course = { R.string.O_C, R.string.GDB, R.string.WP7, R.string.linux,
R.string.computer };

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.spinner);
textView = (TextView) findViewById(R.id.textview);
spinner = (Spinner) findViewById(R.id.spinner);

BaseAdapter myAdapter = new BaseAdapter() {

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub

LinearLayout layout = new LinearLayout(AndroidDemoActivity.this);
layout.setOrientation(LinearLayout.HORIZONTAL);
ImageView imageView = new ImageView(AndroidDemoActivity.this);
imageView.setImageDrawable(getResources().getDrawable(
images[position]));
imageView.setLayoutParams(new Gallery.LayoutParams(60, 60));
// 不按比例拉伸图片
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
layout.addView(imageView);

TextView text = new TextView(AndroidDemoActivity.this);
text.setText(getResources().getText(course[position]));
text.setTextSize(22);
// 设置字体的颜色
layout.addView(text);

return layout;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}

@Override
public int getCount() {
// TODO Auto-generated method stub

return course.length;
}
};

spinner.setAdapter(myAdapter);
// 设置下拉框的标题
spinner.setPrompt("请选择你想上的课程:");

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
LinearLayout layout = (LinearLayout) arg1;
TextView textcontent = (TextView) layout.getChildAt(1);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(getResources().getText(R.string.course));

stringBuilder.append(textcontent.getText());
textView.setText(stringBuilder.toString());

}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}
});
}

实现的效果图如下


 


11.DatePickerDialog     日期控件

日期控件也是安卓中经常用的控件,不过呢,在使用这个控件的时候要注意月的使用方法,

由于月是从0月开始的,所以呢,在显示月的时候要添加个1((calendar.get(Calendar.MONTH)) + 1)


Calendar calendar = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.button);
Button btn = (Button) findViewById(R.id.btn1);
btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(0);
}
});

}

@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
Dialog dialog = null;
switch (id) {
case 0:
calendar = Calendar.getInstance();
dialog = new DatePickerDialog(
this,
new OnDateSetListener() {

@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// TODO Auto-generated method stub
// calendar=calendar.getInstance();
calendar.set(year, monthOfYear, dayOfMonth);
Toast.makeText(
AndroidDemoActivity.this,
"设置的时间是"
+ calendar.get(Calendar.YEAR)
+ ":"
+ ((calendar.get(Calendar.MONTH)) + 1)
+ ":"
+ calendar
.get(Calendar.DAY_OF_MONTH),
Toast.LENGTH_LONG).show();
boolean b = SystemClock
.setCurrentTimeMillis(calendar
.getTimeInMillis());
}
}, calendar.get(Calendar.YEAR),
calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH));

break;

}
return dialog;
}

显示的效果如下




12.  TimePickerDialog   时间控件

 TimePickerDialog和DatePickerDialog 有很多的相似之处下面就看看TimePickerDialog的实现过程

Calendar calendar = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.button);
Button btn = (Button) findViewById(R.id.btn1);
btn.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(0);

}
});

}

@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
Dialog dialog = null;
switch (id) {
case 0:
calendar = Calendar.getInstance();
dialog = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {

@Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
// TODO Auto-generated method stub
calendar.set(calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(calendar.MINUTE, minute);
boolean b = SystemClock
.setCurrentTimeMillis(calendar
.getTimeInMillis());

Toast.makeText(
AndroidDemoActivity.this,
"你设置的时间是:"
+ calendar
.get(Calendar.HOUR_OF_DAY)
+ ":"
+ calendar.get(Calendar.MINUTE),
Toast.LENGTH_LONG).show();
}
}, calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE), true);

break;

}
return dialog;
}



13.AnalogClock 与  DigitalClock   时钟控件  

AnalogClock   表示的是模拟时钟控件  只显示时针和分针

DigitalClock  表示的是数字时钟控件   显示到秒

用法如下:


<DigitalClock
android:id="@+id/digitalclock"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/btn_bg"
android:gravity="center" />

<AnalogClock
android:id="@+id/analogclock"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/btn_bg" />

这样就会自动获取系统的当前时间效果如下



14.ListView  列表视图

 列表视图是安卓中经常用到的一种显示方法,下面就看看这个显示方法的实现过程


<TextView
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />


<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#00000000"
android:choiceMode="singleChoice"/>


具体实现的过程如下:

int[] images = { R.drawable.image1, R.drawable.image2, R.drawable.image3,
R.drawable.image4, R.drawable.wawa };
int[] array = { R.string.WP7, R.string.computer, R.string.GDB,
R.string.O_C, R.string.linux };

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);

ListView listView = (ListView) findViewById(R.id.list);

BaseAdapter baseAdapter = new BaseAdapter() {

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub

LinearLayout layout = new LinearLayout(AndroidDemoActivity.this);
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setPadding(5, 5, 5, 5);
ImageView imageView = new ImageView(AndroidDemoActivity.this);
imageView.setImageDrawable(getResources().getDrawable(
images[position]));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setLayoutParams(new Gallery.LayoutParams(80, 80));
layout.addView(imageView);

TextView textView = new TextView(AndroidDemoActivity.this);
textView.setText(getResources().getText(array[position]));
textView.setTextSize(25);
textView.setPadding(5, 5, 5, 5);
textView.setGravity(Gravity.LEFT);
layout.addView(textView);

return layout;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return 5;
}
};
listView.setAdapter(baseAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
TextView text = (TextView) findViewById(R.id.textview);
LinearLayout layout = (LinearLayout) arg1;
TextView textitem = (TextView) layout.getChildAt(1);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("你选择的是:");
stringBuilder.append(textitem.getText());
String str = stringBuilder.toString();
text.setText(str);
text.setTextColor(Color.BLACK);
}
});
}


 实现的效果如下:



15.Gallery  画廊控件

画廊控件在android中也是经常使用的一个控件,下面就用画廊控件实现android手机中经常使用的图片浏览器

布局如下:

<ImageSwitcher
android:id="@+id/image1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>

<Gallery
android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="80dip"
android:layout_gravity="bottom"
android:layout_marginBottom="10dip"
android:animationDuration="3"
android:spacing="5dip" />

实现的代码如下

Gallery gallery;
ImageSwitcher imageSwitcher;
ArrayList<Integer> imagArrayList = new ArrayList<Integer>();
private int downX, upX;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery);
imageSwitcher = (ImageSwitcher) findViewById(R.id.image1);
gallery = (Gallery) findViewById(R.id.gallery);

// /利用反射机制来获取资源中的图片ID
Field[] fields = R.drawable.class.getDeclaredFields();
for (Field field : fields) {
if (!"icon".equals(field.getName())) {

int index = 0;
try {
index = field.getInt(R.drawable.class);

} catch (Exception e) {
// TODO: handle exception
}
imagArrayList.add(index);
}
}
imageSwitcher.setFactory(new ViewFactory() {

@Override
public View makeView() {
// TODO Auto-generated method stub

ImageView image = new ImageView(AndroidDemoActivity.this);
image.setBackgroundColor(0xFF000000);
image.setScaleType(ImageView.ScaleType.CENTER);
image.setLayoutParams(new ImageSwitcher.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));

return image;
}
});

imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_in));
imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_out));
imageSwitcher.setOnTouchListener(new OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {

if (event.getAction() == MotionEvent.ACTION_DOWN) {
// 获取按下的时候的坐标
downX = (int) event.getX();
return true;

} else if (event.getAction() == MotionEvent.ACTION_UP) {
// 获取松开的时候的坐标
upX = (int) event.getX();
int index = 0;
if (upX - downX > 100) {
// 第一张去尾部
if (gallery.getSelectedItemPosition() == 0) {
index = gallery.getCount() - 1;
} else {
index = gallery.getSelectedItemPosition() - 1;
}
} else if (downX - upX > 100) {
// 最后一张,去第一张
if (gallery.getSelectedItemPosition() == (gallery
.getCount() - 1)) {
index = 0;
} else {
index = gallery.getSelectedItemPosition() + 1;
}
}
gallery.setSelection(index, true);
return true;
}

return false;
}
});

//
gallery.setAdapter(new imageAdapter(this));
gallery.setOnItemSelectedListener(new OnItemSelectedListener() {

@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
imageSwitcher.setImageResource(imagArrayList.get(arg2));
Toast.makeText(AndroidDemoActivity.this,
"你点击了第" + arg2 + "张图片", Toast.LENGTH_LONG).show();
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

}
});
}

public class imageAdapter extends BaseAdapter {

Context myContext;

public imageAdapter(Context context) {
myContext = context;
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return imagArrayList.size();
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(myContext);
imageView.setImageResource(imagArrayList.get(position));
imageView.setAdjustViewBounds(true);
imageView.setLayoutParams(new Gallery.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

return imageView;
}

}



实现的效果如下:


 16.GridView  网格视图

1.网格显示例子一

网格视图是android经常用来显示图片的视图,下面就用一个简单的例子来实现简单的图片浏览器的功能,

简单的布局如下

<GridView
android:id="@+id/gridview01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dip"
android:gravity="center"
android:horizontalSpacing="5dip"
android:numColumns="3"
android:padding="10dip"
android:stretchMode="columnWidth"
android:verticalSpacing="5dip" />

还有一个显示大图片的布局如下

ps:Linerlayout 居中显示的时候会拉伸部分小的图片,导致图片失真

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<ImageView
android:id="@+id/imagegrid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />

</FrameLayout>


实现的代码如下:


int[] images = { R.drawable.image1, R.drawable.image2, R.drawable.image3,
R.drawable.image4, R.drawable.image5, R.drawable.image6,
R.drawable.image7, R.drawable.image8, R.drawable.image9,
R.drawable.wawa, R.drawable.splashscreen_logo, R.drawable.btn_left,
R.drawable.image5, R.drawable.image6, R.drawable.image7,
R.drawable.image8

};

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview);
GridView gridView1 = (GridView) findViewById(R.id.gridview01);
gridView1.setAdapter(new ImageAdapter(this));
gridView1.setOnItemClickListener(new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(AndroidDemoActivity.this,
"你点击了第" + arg2 + "张图片", Toast.LENGTH_SHORT).show();
// 实现跳转,并传递点击位置的图片
Intent intent = new Intent(AndroidDemoActivity.this,
GridViewImage.class);
Bundle bundle = new Bundle();
bundle.putInt("image", images[arg2 % images.length]);
intent.putExtras(bundle);
startActivity(intent);

}
});

}

public class ImageAdapter extends BaseAdapter {
Context myContext;

public ImageAdapter(Context myContext) {
super();
this.myContext = myContext;
}

@Override
public int getCount() {
// TODO Auto-generated method stub
return images.length;
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub

ImageView image;
if (convertView == null) {
image = new ImageView(myContext);
image.setLayoutParams(new GridView.LayoutParams(80, 80));
image.setScaleType(ImageView.ScaleType.FIT_CENTER);

} else {
image = (ImageView) convertView;
}
image.setImageResource(images[position]);

return image;
}

}

点击张图片后显示的大图片实现跳转的方法如下

public class GridViewImage extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.gridviewimage);
ImageView imageView = (ImageView) findViewById(R.id.imagegrid);

Bundle bundle = getIntent().getExtras();
imageView.setImageResource(bundle.getInt("image"));

}

}


ps: intent跳转实现传统图片资源的方法如下

第一个Activity中的传递方法是

Intent intent = new Intent(AndroidDemoActivity.this,
GridViewImage.class);
Bundle bundle = new Bundle();
bundle.putInt("image", images[arg2 % images.length]);
intent.putExtras(bundle);
startActivity(intent);

接受传递过来的图片资源的方法如下:

Bundle bundle = getIntent().getExtras();
imageView.setImageResource(bundle.getInt("image"));


最后呢实现的效果如下:


2.网格显示例子二

显示的效果如下:


 实现的布局如下:

gridview.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@android:color/white"
android:padding="10dp"

android:orientation="vertical" >
<GridView
android:gravity="center_horizontal"
android:id="@+id/gridview01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:columnWidth="90dip"
android:horizontalSpacing="5dip"
android:numColumns="3"
android:padding="10dip"
android:stretchMode="columnWidth"
android:verticalSpacing="5dip"
/>
</LinearLayout>

gridview_item.xml







<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"

android:orientation="vertical" >

<ImageView
android:id="@+id/grid_item_image"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

<TextView
android:id="@+id/grid_item_text"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ddd" />

</LinearLayout>

实现的方法如下:





package com.nyist.activity;

import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class GridViewDemoActivity extends Activity {
int[] images = { R.drawable.alarm_icon_birthday,
R.drawable.alarm_icon_count_back, R.drawable.alarm_icon_getup,
R.drawable.alarm_icon_tryst, R.drawable.alarm_icon_shift,
R.drawable.alarm_icon_memorial_day };
String[] array = { "生日提醒", "倒计时", "起床闹钟", "健身提醒", "晨读提醒", "猜你喜欢" };

protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.gridview);
GridView gridView = (GridView) findViewById(R.id.gridview01);

ArrayList<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();
for (int i = 0; i < array.length; i++) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("Imageitem", images[i]);
map.put("Textitem", array[i]);
list.add(map);
}

SimpleAdapter simpleAdapter = new SimpleAdapter(this, list,// 数据源
R.layout.gridview_item,// 显示布局
new String[] { "Imageitem", "Textitem" }, new int[] {
R.id.grid_item_image, R.id.grid_item_text });
gridView.setAdapter(simpleAdapter);
gridView.setOnItemClickListener(new ItemClickListener());
}

class ItemClickListener implements OnItemClickListener {
/**
* @param parent
* 发生点击动作的AdapterView
* @param view
* 在AdapterView中被点击的视图(它是由adapter提供的一个视图)。
* @param position
* 视图在adapter中的位置。
* @param rowid
* 被点击元素的行id。
*/
public void onItemClick(AdapterView<?> parent, View view, int position,
long rowid) {
HashMap<String, Object> item = (HashMap<String, Object>) parent
.getItemAtPosition(position);
// 获取数据源的属性值
String Textitem = (String) item.get("Textitem");
Object object = item.get("Imageitem");
Toast.makeText(GridViewDemoActivity.this, Textitem,
Toast.LENGTH_LONG).show();

// 根据图片进行相应的跳转
switch (images[position]) {
case R.drawable.alarm_icon_birthday:
startActivity(new Intent(GridViewDemoActivity.this,
birthday.class));// 启动另一个Activity
// finish();// 结束此Activity,可回收
break;
case R.drawable.alarm_icon_count_back:
startActivity(new Intent(GridViewDemoActivity.this,
count_back.class));
// finish();
break;
case R.drawable.alarm_icon_getup:
startActivity(new Intent(GridViewDemoActivity.this, getup.class));
// finish();
break;
case R.drawable.alarm_icon_memorial_day:
startActivity(new Intent(GridViewDemoActivity.this,
MemorialDay.class));// 启动另一个Activity
// finish();// 结束此Activity,可回收
break;
case R.drawable.alarm_icon_shift:
startActivity(new Intent(GridViewDemoActivity.this, Shift.class));
// finish();
break;
case R.drawable.alarm_icon_tryst:
startActivity(new Intent(GridViewDemoActivity.this, Tryst.class));
// finish();
break;

}

}
}
}


代码下载地址:



​GridViewDemo源码下载​



17.ScrollView  滚动视图

ScrollView 滚动视图可以实现解决屏幕空间小的问题,下面看看一个简单的例子

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@android:color/white"
android:orientation="vertical" >

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="5dp"
android:src="@drawable/image1" />

<ImageView
android:id="@+id/image02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="5dp"
android:src="@drawable/image2" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="5dp"
android:src="@drawable/image3" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="5dp"
android:src="@drawable/image4" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="5dp"
android:src="@drawable/wawa" />

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:padding="5dp"
android:src="@drawable/image5" />
</LinearLayout>

</ScrollView>

Activity中可以不用写任何代码就可以实现想要的功能

public class AndroidDemoActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.scroolview);
}

}

效果图如下;



18.TabHost

tabhost有两种实现方法,

1.第一种的实现方法(继承Activity)如下:

布局如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TabHost
android:id="@+id/tabhost01"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true" >
</TabWidget>

<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="bottom" >

<LinearLayout
android:id="@+id/tab1"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="选项卡1"
android:textColor="#FF6100"
android:textSize="25dp" />
</LinearLayout>

<LinearLayout
android:id="@+id/tab2"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="选项卡2"
android:textColor="#FF6100"
android:textSize="25dp" />
</LinearLayout>

<LinearLayout
android:id="@+id/tab3"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="选项卡3"
android:textColor="#FF6100"
android:textSize="25dp" />
</LinearLayout>

<LinearLayout
android:id="@+id/tab4"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="选项卡4"
android:textColor="#FF6100"
android:textSize="25dp" />
</LinearLayout>
</FrameLayout>
</RelativeLayout>
</TabHost>

</LinearLayout>

实现的方法如下:


public class AndroidDemoActivity extends Activity {
TabHost myHost;

protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.tabhost);
myHost = (TabHost) findViewById(R.id.tabhost01);
myHost.setup();
myHost.addTab(myHost
.newTabSpec("tab1")
.setContent(R.id.tab1)
.setIndicator("好友动态",
this.getResources().getDrawable(R.drawable.friend)));
myHost.addTab(myHost
.newTabSpec("tab2")
.setContent(R.id.tab2)
.setIndicator("与我相关",
this.getResources().getDrawable(R.drawable.a)));
myHost.addTab(myHost
.newTabSpec("tab3")
.setContent(R.id.tab3)
.setIndicator("我的空间",
this.getResources().getDrawable(R.drawable.myspace)));
myHost.addTab(myHost
.newTabSpec("tab4")
.setContent(R.id.tab4)
.setIndicator("更多",
this.getResources().getDrawable(R.drawable.more)));
myHost.setCurrentTab(1);
}

实现的效果如下:



2.第二种方法(继承TabActivity)如下:

这一种不需要布局,实现的代码如下

public class AndroidDemoActivity extends TabActivity implements
OnTabChangeListener, TabContentFactory {

TabHost myHost;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
myHost = getTabHost();

myHost.addTab(myHost
.newTabSpec("tab1")
.setIndicator("好友动态",
getResources().getDrawable(R.drawable.friend))
.setContent(this));
myHost.addTab(myHost.newTabSpec("tab2")
.setIndicator("与我相关", getResources().getDrawable(R.drawable.a))
.setContent(this));
myHost.addTab(myHost
.newTabSpec("tab3")
.setIndicator("我的空间",
getResources().getDrawable(R.drawable.myspace))
.setContent(this));
myHost.addTab(myHost
.newTabSpec("tab4")
.setIndicator("更多", getResources().getDrawable(R.drawable.more))
.setContent(this));
myHost.setOnTabChangedListener(this);
}

public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
if (tabId.equals("tab1")) {
myHost.setBackgroundResource(R.drawable.image6);
} else if (tabId.equals("tab2")) {
myHost.setBackgroundResource(R.drawable.image7);
} else if (tabId.equals("tab3")) {
myHost.setBackgroundResource(R.drawable.image8);
} else if (tabId.equals("tab4")) {
myHost.setBackgroundResource(R.drawable.image9);
}

}

public View createTabContent(String tag) {
// TODO Auto-generated method stub
final TextView textView = new TextView(this);
textView.setTextSize(20);
textView.setText("你选择了第" + tag + "个选项卡");

return textView;
}

}

实现的效果如下:




 19.ToggleButton 开关按钮

开关按钮也是经常使用的一个方法,不过呢在4.0之前的开关按钮不是那么的好看,4.0之后的开关按钮挺不错的

下面是一个简单的开关按钮实现更换图片的功能,简单的布局如下

<ToggleButton
android:id="@+id/togglebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="@string/hello"
android:textOff="未选中"
android:textOn="选中" />

<ImageView
android:id="@+id/image1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

简单的实现代码如下:

public class AndroidDemoActivity extends Activity {

ImageView imageView;

protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);

setContentView(R.layout.togglebutton);
ToggleButton toggleButton = (ToggleButton) findViewById(R.id.togglebtn);
imageView = (ImageView) findViewById(R.id.image1);

toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub

imageView.setImageResource(isChecked ? R.drawable.wawa
: R.drawable.image1);
}
});

}

}

实现的效果如下:


20.AutoCompleteTextView 自动完成文本

AutoCompleteTextView自动完成文本,使用的方法如下

布局如下:

<AutoCompleteTextView
android:id="@+id/auto"
android:layout_width="200dp"
android:layout_height="wrap_content"
/>

实现的代码如下

public class AndroidDemoActivity extends Activity {

String arrays[] = { "大学英语", "大学语文", "大学物理", "大学生心理教育", "大学体育", "大学计算机基础" };

protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);

setContentView(R.layout.autocompletetextview);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, arrays);
AutoCompleteTextView autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.auto);
autoCompleteTextView.setThreshold(1);
autoCompleteTextView.setDropDownAnchor(200);
autoCompleteTextView.setAdapter(adapter);

}

}

实现的效果如下:


21.notification 通知信息

notification 是android中经常使用的空间,下面一个简单的小例子实现notification的方法

布局很简单,就有两个按钮,实现的方法如下


protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.notification);

notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notification = new Notification(R.drawable.wawa,
"good good study day day up! ", System.currentTimeMillis());
// 点击通知栏的时候自动消失notification
notification.flags = Notification.FLAG_AUTO_CANCEL;

Intent intent = new Intent(this, LogoActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_NEW_TASK);

Bundle bundle = new Bundle();
bundle.putString("text", "这是从notification中跳转过来的");
intent.putExtras(bundle);

PendingIntent pendingIntent = PendingIntent.getActivity(
AndroidDemoActivity.this, R.string.notification, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
// 设置下拉notification时候,并点击notification时候的处理问题
notification.setLatestEventInfo(this, "媳妇", "今天媳妇感冒了,俺很担心她!!",
pendingIntent);
Button btnopen = (Button) findViewById(R.id.button1);
Button btnclose = (Button) findViewById(R.id.button2);
btnopen.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
notificationManager.notify(0, notification);
}
});
btnclose.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
notificationManager.cancelAll();

}
});

}

}

实现的效果如下:





 22.appwidget 窗口小部件

appwidget是桌面上经常用到是组件,下面的是实现仿课程格子的桌面组件

首先呢,要实现这个功能,需要创建的布局如下appwidget.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="80dp"
android:orientation="horizontal"
android:background="@drawable/share_bg">

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_centerInParent="true"
android:layout_alignParentLeft="true"
>

<TextView
android:id="@+id/widgetclasstime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="上课节次" />
</LinearLayout>

<LinearLayout
android:id="@+id/widgetlinear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_centerHorizontal="true" >

<TextView
android:id="@+id/widgetclassname"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="课程名称"
android:textSize="25dp" />

<TextView
android:id="@+id/widgetaddr"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:text="上课地点" />
</LinearLayout>

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignParentRight="true" >

<ImageView
android:id="@+id/widget_back_focus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="@drawable/widget_back_normal" />

<ImageView
android:id="@+id/widget_next_focus"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/widget_next_normal" />
</LinearLayout>

</RelativeLayout>

然后接着呢,需要把引入这个布局的信息

这个呢需要在res文件夹下在创建一个xml文件夹,在appwidgetprovider.xml引入appwidget.xml 的布局信息,代码如下

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
android:initialLayout="@layout/appwidget"
android:minHeight="80dp"
android:minWidth="300dp" >

</appwidget-provider>

实现桌面部件的方法如下


public class MyAppWidgetProvider extends AppWidgetProvider {
private static final String PRE_UPDATE_ACTION = "wangjie.pre_update_app_widget";
private static final String NEXT_UPDATE_ACTION = "wangjie.next_update_app_widget";

@Override
public void onDeleted(Context context, int[] appWidgetIds) {
// TODO Auto-generated method stub
super.onDeleted(context, appWidgetIds);
}

@Override
public void onDisabled(Context context) {
// TODO Auto-generated method stub
super.onDisabled(context);
}

@Override
public void onEnabled(Context context) {
// TODO Auto-generated method stub
super.onEnabled(context);
}

@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();

if (PRE_UPDATE_ACTION.equals(action)) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.appwidget);
remoteViews.setTextViewText(R.id.widgetclassname, "大学英语");
remoteViews.setTextViewText(R.id.widgetaddr, "14#206");
remoteViews.setTextViewText(R.id.widgetclasstime, "第一节");

AppWidgetManager appWidgetManager = AppWidgetManager
.getInstance(context);
ComponentName componentName = new ComponentName(context,
MyAppWidgetProvider.class);
appWidgetManager.updateAppWidget(componentName, remoteViews);
}
if (NEXT_UPDATE_ACTION.equals(action)) {

RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.appwidget);
remoteViews.setTextViewText(R.id.widgetclassname, "大学语文");
remoteViews.setTextViewText(R.id.widgetaddr, "15#310");
remoteViews.setTextViewText(R.id.widgetclasstime, "第四节");
AppWidgetManager appWidgetManager = AppWidgetManager
.getInstance(context);
ComponentName componentName = new ComponentName(context,
MyAppWidgetProvider.class);
appWidgetManager.updateAppWidget(componentName, remoteViews);
} else

super.onReceive(context, intent);

}

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
// TODO Auto-generated method stub
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.appwidget);
Intent preIntent = new Intent();
preIntent.setAction(PRE_UPDATE_ACTION);
PendingIntent prependingIntent = PendingIntent.getBroadcast(context,
-1, preIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.widget_back_focus,
prependingIntent);
remoteViews
.setOnClickPendingIntent(R.id.widgetlinear, prependingIntent);

Intent nextIntent = new Intent();
nextIntent.setAction(NEXT_UPDATE_ACTION);
PendingIntent nextPendingIntent = PendingIntent.getBroadcast(context,
-1, nextIntent, 0);

remoteViews.setOnClickPendingIntent(R.id.widget_next_focus,
nextPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.widgetlinear,
nextPendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);

}

}


最后呢,不要忘记在androidManifest.xm文件中注册receiver广播

<receiver android:name=".MyAppWidgetProvider" >
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
</intent-filter>
<intent-filter>
<action android:name="wangjie.pre_update_app_widget" />
<action android:name="wangjie.next_update_app_widget" />
</intent-filter>

<meta-data
android:name="android.appwidget.provider"
android:resource="@xml/appwidgetprovider" />
</receiver>



最后呢实现的结果如下:点击上下按钮可以改变内容


 23.桌面快捷方式

桌面快捷方式是每个应用程序必要的组成部分,有人说得桌面者得天下,这个虽然有点夸张,但还是有一定的道理的,下面就看看你桌面快捷方式的实现方法

布局呢,就以按钮


<Button
android:id="@+id/kujie"
android:layout_width="fill_parent"
android:layout_height="50dip"
android:background="@drawable/btn_bg"
android:text="创建桌面快捷方式" />


其实现的方法也很简单没有几行代码,如下

public class AndroidDemoActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
Button kuaijie;

super.onCreate(savedInstanceState);
setContentView(R.layout.kuiaijie);
kuaijie = (Button) findViewById(R.id.kujie);
kuaijie.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// 跳转设置
Intent myintent = new Intent(AndroidDemoActivity.this,
LogoActivity.class);
startActivity(myintent);
// 创建intent的对象
Intent intent = new Intent(
"com.android.launcher.action.INSTALL_SHORTCUT");
// 得到桌面快捷方式 的图片
Parcelable deskicon = Intent.ShortcutIconResource.fromContext(
AndroidDemoActivity.this, R.drawable.wawa);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "快捷方式");
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, deskicon);
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, myintent);
// 发送广播创建快捷方式
sendBroadcast(intent);
Toast.makeText(AndroidDemoActivity.this, "创建桌面快捷方式已完成!!",
Toast.LENGTH_LONG).show();
}
});
}

}

完成上述步骤后,需要在Androidmanfiest.xml文件中添加创建快捷方式的权限

<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>

这样呢就可以实现创建桌面快捷方式了,效果图如下,中间那个娃娃头就是我们创建的快捷方式的图标




24.SliderDrawer抽屉组件的使用

效果图:


实现的代码如下:

布局如下

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/library_back"
android:orientation="vertical" >

<SlidingDrawer
android:id="@+id/slidingdrawer"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:animateOnClick="true"
android:content="@+id/content"
android:handle="@+id/handle"
android:orientation="vertical" >

<RelativeLayout
android:id="@id/handle"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >

<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:clickable="true"
android:src="@drawable/handle_selector" />
</RelativeLayout>

<LinearLayout
android:id="@id/content"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff" >

<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical|center_horizontal"
android:textColor="#000000"
android:textSize="18px"
android:textStyle="bold" >
</TextView>
</LinearLayout>
</SlidingDrawer>

</RelativeLayout>

实现布局的方法如下:


package com.nyist.Slider;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SlidingDrawer;
import android.widget.TextView;
import android.widget.Toast;

public class SliderDemoActivity extends Activity {
private SlidingDrawer mySlidingDrawer;
private ImageView handleimage;
private RelativeLayout handle;
private Boolean flag = false;
private TextView text;

protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sliderdrawer);

handleimage = (ImageView) findViewById(R.id.image);
handle = (RelativeLayout) findViewById(R.id.handle);
mySlidingDrawer = (SlidingDrawer) findViewById(R.id.slidingdrawer);
text = (TextView) findViewById(R.id.tv);

mySlidingDrawer
.setOnDrawerOpenListener(new SlidingDrawer.OnDrawerOpenListener() {
@Override
public void onDrawerOpened() {
flag = true;
handleimage
.setImageResource(R.drawable.handle_close_selector);
}

});

mySlidingDrawer
.setOnDrawerCloseListener(new SlidingDrawer.OnDrawerCloseListener() {

@Override
public void onDrawerClosed() {
flag = false;
handleimage
.setImageResource(R.drawable.handle_selector);

}

});

mySlidingDrawer
.setOnDrawerScrollListener(new SlidingDrawer.OnDrawerScrollListener() {

@Override
public void onScrollEnded() {
text.setText("SliderDrawer抽屉组件结束");
}

@Override
public void onScrollStarted() {
text.setText("SliderDrawer抽屉组件开始");
}

});

}
}

代码下载地址:

​SliderDemo源码下载​


 25.解决设置EditText不自动获取焦点弹软键盘,只有在选中的时候打开软键盘的问题

XML中设置EditTxet不获取焦点

<EditText
android:id="@+id/edit_alarm_notes"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:layout_marginLeft="5dp"
android:focusableInTouchMode="false"
android:background="@android:color/darker_gray"
android:text="懒虫起床啦" />

在Edit的点击事件中设置获取焦点v.requestFocus();   并打开软键盘,

case R.id.edit_alarm_notes:
Toast.makeText(AlarmClockDemoActivity.this, "你点击了", Toast.LENGTH_SHORT).show();
v.requestFocus();
//打开软键盘
InputMethodManager inputMethodManager = (InputMethodManager)this.getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

break;


备注:设置获取焦点的方法有两种

View.setFocusable(true),                                       对应xml : android:focusable="true".

View.setFocusableInTouchMode(true)               对应xml : android:focusableInTouchMode="true".

区别:

android:focusable="true".       执行false条件后,再执行true,还是不能获取焦点

focusableInTouchMode          执行false条件后,再执行true(activity中调用view的requestFocus()),可以获取焦点,然后在调用打开软键盘就可以解决一上来EditText就抢焦点弹软键盘的问题

android 学习总结_android

android 学习总结_ide_02

至此,本篇已结束,如有不对的地方,欢迎您的建议与指正。同时期待您的关注,感谢您的阅读,谢谢!