在图片当道的如下,还是有图更有说服力。
小子不才,所以这个demo是我东找西找然后自己凑的一个例子。内有失当之处,多包涵多指正!
等了三天才能发帖子,这点JAVAEYE真的应该改变一下了,要不然把我这样的孩子憋生啥样了。。。
1。首先定义xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#55000000"
>
<ImageSwitcher //此控件与Gallery会经常用的,切记
android:id="@+id/switcher"
android:layout_width="wrap_content"
android:layout_height="350dip"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
/>
<Gallery
android:id="@+id/mygallery"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:gravity="center_vertical"
android:spacing="16dp"
/>
</RelativeLayout>
2。Activity中要自定义显示
package com.ldci.second.mypnone;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Gallery.LayoutParams;
public class BgPictureShowActivity extends Activity implements
AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory {
private List<String> ImageList;
private String []list;
private ImageSwitcher mSwitcher;
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
// //去掉状态栏,且显示自己程序名称
// getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
// WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.pictureshow);
ImageList=getSD();
list = ImageList.toArray(new String[ImageList.size()]);
/*设定Switcher*/
mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
mSwitcher.setFactory(this);
/*设定载入Switcher的模式*/
mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_in));
/*设定输出Switcher的模式*/
mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
android.R.anim.fade_out));
mSwitcher.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
Toast.makeText(BgPictureShowActivity.this, "点击了", Toast.LENGTH_SHORT).show();
}
});
Gallery g = (Gallery) findViewById(R.id.mygallery);
/*新增几ImageAdapter并设定给Gallery对象*/
g.setAdapter(new ImageAdapter(this,getSD()));
g.setOnItemSelectedListener(this);
/*设定一个itemclickListener事件*/
g.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent,
View v, int position, long id)
{
Toast.makeText(BgPictureShowActivity.this, "dianjiale ", Toast.LENGTH_SHORT).show();
}
});
}
private List<String> getSD()
{
/* 设定目前所在路径 */
List<String> it=new ArrayList<String>();
File f=new File("/sdcard/");
File[] files=f.listFiles();
/* 将所有文件存入ArrayList中 */
for(int i=0;i<files.length;i++)
{
File file=files[i];
if(getImageFile(file.getPath()))
it.add(file.getPath());
}
return it;
}
private boolean getImageFile(String fName)
{
boolean re;
/* 取得扩展名 */
String end=fName.substring(fName.lastIndexOf(".")+1,
fName.length()).toLowerCase();
/* 按扩展名的类型决定MimeType */
if(end.equals("jpg")||end.equals("gif")||end.equals("png")
||end.equals("jpeg")||end.equals("bmp"))
{
re=true;
}
else
{
re=false;
}
return re;
}
/*改写BaseAdapter自定义一ImageAdapter class*/
public class ImageAdapter extends BaseAdapter
{
/*声明变量*/
int mGalleryItemBackground;
private Context mContext;
private List<String> lis;
/*ImageAdapter的构造符*/
public ImageAdapter(Context c,List<String> li)
{
mContext = c;
lis=li;
/* 使用res/values/attrs.xml中的<declare-styleable>定义
* 的Gallery属性.*/
TypedArray a = obtainStyledAttributes(R.styleable.Gallery);
/*取得Gallery属性的Index id*/
mGalleryItemBackground = a.getResourceId(
R.styleable.Gallery_android_galleryItemBackground, 0);
/*让对象的styleable属性能够反复使用*/
a.recycle();
}
/*几定要重写的方法getCount,传回图片数目*/
public int getCount()
{
return lis.size();
}
/*一定要重写的方法getItem,传回position*/
public Object getItem(int position)
{
return position;
}
/*一定要重写的方法getItemId,传并position*/
public long getItemId(int position)
{
return position;
}
/*几定要重写的方法getView,传并几View对象*/
public View getView(int position, View convertView,
ViewGroup parent)
{
/*产生ImageView对象*/
ImageView i = new ImageView(mContext);
/*设定图片给imageView对象*/
Bitmap bm = BitmapFactory.decodeFile(lis.
get(position).toString());
i.setImageBitmap(bm);
/*重新设定图片的宽高*/
i.setScaleType(ImageView.ScaleType.FIT_XY);
/*重新设定Layout的宽高*/
i.setLayoutParams(new Gallery.LayoutParams(136, 88));
/*设定Gallery背景图*/
i.setBackgroundResource(mGalleryItemBackground);
/*传回imageView对象*/
return i;
}
}
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
String photoURL=list[position];
Log.i("A",String.valueOf(position));
mSwitcher.setImageURI(Uri.parse(photoURL));
}
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
public View makeView() {
ImageView i = new ImageView(this);
i.setBackgroundColor(0xFF000000);
i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams(new ImageSwitcher.LayoutParams(
LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
return i;
}
}
这段代码很长,看的时候肯定会头疼加DAN疼,但是一定要挺住啊,MARS大神一再告诫咱们,这个行业的特点就是要有耐心。
3。对了,还有一个非常重要的事情,就是在values文件夹下面,新建一个xml,内书:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="Gallery">
<attr name="android:galleryItemBackground" />
</declare-styleable>
</resources>
最后就成功了。
上次说到了登录回调方法onPostExecute,此方法是AsyncTask的方法,当doInBackground方法执行完后调用此方法来处理返回结果.在onPostExecute中主要根据登录结果来做不同的事情,登录成功://发送登录广播
sendBroadcast(new Intent(Foursquared.INTENT_ACTION_LOGGED_IN));
此广播的订阅时在Foursquared类中实现的,首先看此类Foursquared extends Application,Application是android项目运行的一个全局的状态 "Base class for those who need to maintain global application state". 可以在Manifest.xml中指定你自定义的application. 在此类中有一个LoggedInOutBroadcastReceiver 来处理接收到的广播,然后广播发送一个message.此message对应有一个TaskHandler.在foursquare中他使用了
mTaskThread = new HandlerThread(TAG + "-AsyncThread"); mTaskThread.start(); mTaskHandler = new TaskHandler(mTaskThread.getLooper());
上面的方式来创建Handler. 是为了让handler运行在新的线程中. 接下来看handleMessage方法对msg的处理.第一个switch case语句是MESSAGE_UPDATE_USER, 更新一下用户的信息.同时保存在SharedPreferenses中.
接下来开始一个更新UI的Service foursquared.requestStartService(); 主要调用FoursquaredService类的updateWidgets方法来更新widget.也是在Foursquared类中来进行更新,看handleMessage():
case MESSAGE_START_SERVICE: //updateWidgets更新组件
Intent serviceIntent = new Intent(Foursquared.this, FoursquaredService.class);
serviceIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
startService(serviceIntent);
return;
启动一个FoursquaredService.
接下来返回到主界面
// Launch the main activity to let the user do anything.
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
如果登录失败:
sendBroadcast(new Intent(Foursquared.INTENT_ACTION_LOGGED_OUT));//发送登出广播. NotificationsUtil.ToastReasonForFailure(LoginActivity.this, mReason);//根据不同的exception来提示失败信息
最后关闭进度条dismissProgressDialog().
到这里登录就结束了.写的比较乱.呵呵.
下面的menu没有意义,仅仅是个练习而已,看图先:
布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/textViewName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/name"
android:textSize="20dp"
/>
<EditText
android:id="@+id/editTextName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="@+id/textViewAge"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/age"
android:textSize="20dp"
/>
<EditText
android:id="@+id/editTextAge"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
view:
package com.dc.app;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class AppActivity extends Activity {
private static final String TAG="AppActivity";
private TextView textViewName,textViewAge;
private EditText editTextName,editTextAge;
private final int menuIdRegiste=1;
private final int menuIdBack=2;
private final int menuIdLogin=3;
private final int menuIdDate=4;
private final int menuIdTime=5;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.v(TAG,"start");
textViewName=(TextView)this.findViewById(R.id.textViewName);
textViewName.setTextColor(Color.BLUE);
textViewName.setBackgroundColor(Color.WHITE);
editTextName=(EditText)this.findViewById(R.id.editTextName);
textViewAge=(TextView)this.findViewById(R.id.textViewAge);
textViewAge.setTextColor(Color.BLUE);
textViewAge.setBackgroundColor(Color.WHITE);
editTextAge=(EditText)this.findViewById(R.id.editTextAge);
}
public boolean onCreateOptionsMenu(Menu menu) {//初始化Menu菜单选择项
super.onCreateOptionsMenu(menu);
//添加菜单项,比如:
menu.add(0, menuIdRegiste, 0, R.string.registe).setShortcut('1', 'r');//设置快捷键
menu.add(0, menuIdBack, 0, R.string.back).setShortcut('2', 'b');//设置快捷键
menu.add(0, menuIdLogin, 0, R.string.login).setShortcut('3', 'l');//设置快捷键
menu.add(0, menuIdDate, 0, R.string.date).setShortcut('4', 'd');//设置快捷键
menu.add(0, menuIdTime, 0, R.string.time).setShortcut('5', 't');//设置快捷键
//添加其他菜单项。。。。。。
return true;
}
public boolean onPrepareOptionsMenu(Menu menu) {//
super.onPrepareOptionsMenu(menu);
//这里可以事先设置菜单的可见性,如果都可见,可以不设置
menu.findItem(menuIdRegiste).setVisible(true).setIcon(android.R.drawable.ic_menu_add);//设置菜单项可见性
menu.findItem(menuIdBack).setVisible(true).setIcon(android.R.drawable.ic_menu_save);//设置菜单项可见性
menu.findItem(menuIdLogin).setVisible(true).setIcon(android.R.drawable.ic_menu_camera);//设置菜单项可见性
menu.findItem(menuIdDate).setVisible(true).setIcon(android.R.drawable.ic_menu_compass);//设置菜单项可见性
menu.findItem(menuIdTime).setVisible(true).setIcon(R.drawable.icon);//设置菜单项可见性
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {//选择了一个菜单项的时候调用
//这里可以预先处理想要的变量
switch (item.getItemId()) {
case menuIdRegiste://一项一项的处理想要做的,不用我介绍了吧
Toast.makeText(this, R.string.menuIdRegisteContent, Toast.LENGTH_LONG).show();
showDialog(DIALOG_KEY);
return true;
case menuIdBack:
Toast.makeText(this, R.string.menuIdBackContent, Toast.LENGTH_LONG).show();
showNotify();
return true;
case menuIdLogin:
showDialog(DIALOG_LOGIN);
return true;
case menuIdDate:
showDialog(DIALOG_DATE);
return true;
case menuIdTime:
showDialog(DIALOG_TIME);
return true;
}
return super.onOptionsItemSelected(item);
}
private static final int DIALOG_KEY = 0;
private static final int DIALOG_LOGIN = 3;
private static final int DIALOG_DATE = 4;
private static final int DIALOG_TIME = 5;
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_KEY:
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("通讯录");
progressDialog.setMessage("获取通讯录中...请稍候");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);//不明确
progressDialog.setCancelable(true);//是否可以按退回按键取消
progressDialog.setButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
// removeDialog(DIALOG_KEY);
}
});
progressDialog.setCanceledOnTouchOutside(true);
return progressDialog;
case DIALOG_LOGIN:
View dialogview=LayoutInflater.from(this).inflate(R.layout.main, null);
Dialog loginDialog=new AlertDialog.Builder(this)
.setTitle("登录")
.setView(dialogview)//this.findViewById(R.layout.main),不可以,why?
.setCancelable(true)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
})
.create();
loginDialog.setCanceledOnTouchOutside(true);
return loginDialog;
case DIALOG_DATE:
Calendar c = Calendar.getInstance();
DatePickerDialog dateDialog=new DatePickerDialog(this,new DatePickerDialog.OnDateSetListener(){
@Override
public void onDateSet(DatePicker view, int year,
int monthOfYear, int dayOfMonth) {
// TODO Auto-generated method stub
showDialog(DIALOG_KEY);
}
},c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE));
return dateDialog;
case DIALOG_TIME:
Calendar c2 = Calendar.getInstance();
TimePickerDialog timeDialog=new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
showDialog(DIALOG_KEY);
}
}, c2.get(Calendar.HOUR), c2.get(Calendar.MINUTE), true);
return timeDialog;
}
return null;
}
private void showNotify(){
Notification notice=new Notification();
notice.icon=R.drawable.icon;
notice.tickerText="您有一条新的信息";
notice.defaults=Notification.DEFAULT_SOUND;
notice.when=10L;
// 100 毫秒延迟后,震动 250 毫秒,暂停 100 毫秒后,再震动 500 毫秒
// notice.vibrate = new long[] { 100, 250, 100, 500 };
notice.setLatestEventInfo(this, "通知", "开会啦", PendingIntent.getActivity(this, 0, null, 0));
NotificationManager manager=(NotificationManager)getSystemService(this.NOTIFICATION_SERVICE);
manager.notify(0,notice);
}
}