密码日记

这篇博客详细介绍了如何开发一款密码保护的日记应用,涵盖了从界面设计到数据库操作的各个核心部分,包括AboutActivity、AddDiaryActivity的功能实现,DiaryAdapter和AutoTextViewAdapter的数据适配,以及DataBaseHelper和DiaryDao的数据库操作。此外,还涉及到文件操作和时间格式化工具类的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、运行效果图

 

 

二、核心代码

1.com.org.android.diary.activity包的代码:

AboutActivity:

public class AboutActivity extends Activity {
	private ImageView back = null;
	private SharedPreferences preferences = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.about);
		preferences = getSharedPreferences("image", MODE_PRIVATE);
		back = (ImageView)this.findViewById(R.id.back_about);
		back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
				overridePendingTransition(R.anim.push_below_in,R.anim.push_below_out);
			}
		});
		setBackground();
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		setBackground();
	}
	private void setBackground() {
		// 得到当前布局
		LinearLayout layout = (LinearLayout) this.findViewById(R.id.about_layout);
		// 得到id,此处id是在设置背景里面产生的,此处暂不解释
		int id = preferences.getInt("id", 0);
		if (id == 0) {// id=0说明是初始化时的背景
			// 设置背景方法
			layout.setBackgroundResource(R.drawable.diary_view_bg);
		} else if (id == 1) {// id=1说明用户选择了第一幅图片
			layout.setBackgroundResource(R.drawable.diary_view_bg);
		} else if (id == 2) {// id=2说明用户选择了第二幅图片
			layout.setBackgroundResource(R.drawable.spring);
		} else if (id == 3) {// id=3说明用户选择了第三幅图片
			layout.setBackgroundResource(R.drawable.summer);
		} else if (id == 4) {// id=4说明用户选择了第四幅图片
			layout.setBackgroundResource(R.drawable.autumn);
		} else if (id == 5) {// id=4说明用户选择了第四幅图片
			layout.setBackgroundResource(R.drawable.winter);
		}
	}
	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		overridePendingTransition(R.anim.push_below_in,R.anim.push_below_out);
	}
}

 

AccessActivity:

public class AccessActivity extends Activity {
	private Button access;
	private SharedPreferences sp=null;
	@SuppressLint("NewApi")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.access);
		access = (Button)this.findViewById(R.id.access);
		access.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				sp=getSharedPreferences("pass", Context.MODE_PRIVATE);
				String passWay=sp.getString("passway", null);
				Intent intent = null;
				if (passWay!=null) {
					if (passWay.equals("graphicpass")) {
						intent =new Intent(AccessActivity.this,CheckPassActivity.class);
						startActivity(intent);
						overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
						AccessActivity.this.finish();
					}
					else {
						intent = new Intent(AccessActivity.this, MainActivity.class);  
				        startActivity(intent);
				        overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
				        AccessActivity.this.finish();  
					}
				}
				else {
					intent = new Intent(AccessActivity.this, MainActivity.class);  
			        startActivity(intent);
			        overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out);
			        AccessActivity.this.finish();
				}
			}
		});
	}
}

 

AddDiaryActivity:

public class AddDiaryActivity extends Activity {
	private TextView timeTextView = null;
	private TextView weekTextView = null;
	private Spinner weatherSpinner = null;
	private Calendar cal = Calendar.getInstance();
	private Date date = null;
	private SimpleDateFormat simpleDateFormat = null;
	public static final int WEEKDAYS = 7;
	private EditText diaryInfo = null;
	private EditText diaryTitle = null;
	public static String[] WEEK = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五",
			"星期六" };
	private ImageView back = null;
	private SharedPreferences preferences = null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		init();
	}
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		setBackground();
	}
	@SuppressLint("SimpleDateFormat")
	private void init() {
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.add_diary);
		preferences = getSharedPreferences("image", MODE_PRIVATE);
		date = cal.getTime();
		simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		timeTextView = (TextView) this.findViewById(R.id.time);
		timeTextView.setText(simpleDateFormat.format(date));
		weekTextView = (TextView) this.findViewById(R.id.week);
		weekTextView.setText(DateToWeek(date));
		weatherSpinner = (Spinner) this.findViewById(R.id.weather);
		diaryInfo = (EditText)this.findViewById(R.id.edit_diary_info);
		diaryTitle = (EditText)this.findViewById(R.id.edit_title);
		back = (ImageView)this.findViewById(R.id.back_add_diary);
		back.setOnClickListener(new BackListener());
		ArrayAdapter<CharSequence> adapter=ArrayAdapter.createFromResource(this, 
				R.array.weather, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
		weatherSpinner.setAdapter(adapter);
		weatherSpinner.setPrompt(getString(R.string.weather));
		setBackground();
	}
	
	private void setBackground() {
		// 得到当前布局
		LinearLayout layout = (LinearLayout) this.findViewById(R.id.add_diary_layout);
		// 得到id,此处id是在设置背景里面产生的,此处暂不解释
		int id = preferences.getInt("id", 0);
		if (id == 0) {// id=0说明是初始化时的背景
			// 设置背景方法
			layout.setBackgroundResource(R.drawable.diary_view_bg);
		} else if (id == 1) {// id=1说明用户选择了第一幅图片
			layout.setBackgroundResource(R.drawable.diary_view_bg);
		} else if (id == 2) {// id=2说明用户选择了第二幅图片
			layout.setBackgroundResource(R.drawable.spring);
		} else if (id == 3) {// id=3说明用户选择了第三幅图片
			layout.setBackgroundResource(R.drawable.summer);
		} else if (id == 4) {// id=4说明用户选择了第四幅图片
			layout.setBackgroundResource(R.drawable.autumn);
		} else if (id == 5) {// id=4说明用户选择了第四幅图片
			layout.setBackgroundResource(R.drawable.winter);
		}
	}
	public static String DateToWeek(Date date){
		Calendar calendar = Calendar.getInstance(); 
		calendar.setTime(date);
		int dayIndex = calendar.get(Calendar.DAY_OF_WEEK);
		if (dayIndex < 1 || dayIndex > WEEKDAYS) {  
	        return null;  
	    }  
	    return WEEK[dayIndex - 1];  
	}
	
	class BackListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			back();
		}
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			back();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	private void back(){
		if ((!diaryTitle.getText().toString().trim().equals("")) && 
				(!diaryInfo.getText().toString().trim().equals(""))) {
			DiaryDao diaryDao = new DiaryDao(AddDiaryActivity.this);
			Diary diary = new Diary();
			diary.setDate(timeTextView.getText().toString());
			diary.setWeek(weekTextView.getText().toString());
			diary.setWeather(weatherSpinner.getSelectedItem().toString());
			diary.setDiaryTitle(diaryTitle.getText().toString());
			diary.setDiaryInfo(diaryInfo.getText().toString());
			diaryDao.insert(diary);
			Intent intent = new Intent();
			intent.setClass(AddDiaryActivity.this, MainActivity.class);
			startActivity(intent);
			finish();
			overridePendingTransition(R.anim.push_below_in, R.anim.push_below_out);
			Toast.makeText(AddDiaryActivity.this, R.string.save_success, 0).show();
		}else {
			Toast.makeText(AddDiaryActivity.this, R.string.empty_info, 0).show();
			AddDiaryActivity.this.finish();
			overridePendingTransition(R.anim.push_below_in, R.anim.push_below_out);
		}
	}
}

 

2.com.org.android.diary.adapter包的代码:

AutoTextViewAdapter:

public class AutoTextViewAdapter extends BaseAdapter implements Filterable {  
	  
	public List<String> mList;  
    private Context mContext;  
    private MyFilter mFilter;  
      
    public AutoTextViewAdapter(Context context) {  
        mContext = context;  
        mList = new ArrayList<String>();  
    }  
      
    @Override  
    public int getCount() {  
        return mList == null ? 0 : mList.size();  
    }  

    @Override  
    public Object getItem(int position) {  
        return mList == null ? null : mList.get(position);  
    }  

    @Override  
    public long getItemId(int position) {  
        return position;  
    }  

    @Override  
    public View getView(int position, View convertView, ViewGroup parent) {  
        if (convertView == null) {  
            TextView tv = new TextView(mContext);  
            tv.setTextColor(Color.BLACK);  
            tv.setTextSize(20);  
            convertView = tv;  
        }  
        TextView txt = (TextView) convertView;  
        txt.setText(mList.get(position));  
        return txt;  
    }  

    public Filter getFilter() {  
        if (mFilter == null) {  
            mFilter = new MyFilter();  
        }  
        return mFilter;  
    }  
    
    private class MyFilter extends Filter {  
    	
    	@Override  
    	protected FilterResults performFiltering(CharSequence constraint) {  
    		FilterResults results = new FilterResults();  
    		if (mList == null) {  
    			mList = new ArrayList<String>();  
    		}  
    		results.values = mList;  
    		results.count = mList.size();  
    		return results;  
    	}  
    	
    	@Override  
    	protected void publishResults(CharSequence constraint, FilterResults results) {  
    		if (results.count > 0) {  
    			notifyDataSetChanged();  
    		} else {  
    			notifyDataSetInvalidated();  
    		}  
    	}  
    	
    }  
}


DiaryAdapter:

public class DiaryAdapter extends BaseAdapter{
	private Activity activity;
	private LayoutInflater inflater;
	private List<Diary> diaries;
	public DiaryAdapter(Activity activity, List<Diary> diaries) {
		super();
		this.activity = activity;
		this.diaries = diaries;
	}

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

	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return diaries.get(position);
	}

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

	public View getView(final int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		ViewHolder holder = null;
		if (convertView == null) {
			inflater = (LayoutInflater) activity.getLayoutInflater();
			convertView = inflater.inflate(R.layout.diary_info_view, null);
			holder = new ViewHolder();
			holder.diaryInfo = (TextView)convertView.findViewById(R.id.view_info);
			holder.diaryTitle = (TextView)convertView.findViewById(R.id.view_title);
			holder.date = (TextView)convertView.findViewById(R.id.view_date);
			convertView.setTag(holder);
		}else {
			holder = (ViewHolder) convertView.getTag();
		}
		holder.diaryTitle.setText(activity.getString(R.string.title)+":"+diaries.get(position).getDiaryTitle());
		holder.diaryInfo.setText(diaries.get(position).getDiaryInfo());
		holder.date.setText(diaries.get(position).getDate());
		return convertView;
	}
	class ViewHolder{
		TextView diaryTitle;
		TextView diaryInfo;
		TextView date;
	}
}


3.com.org.android.diary.constant包的代码:

Constant:

public class Constant {
	public final static String TABLE_INFO = "create table DIARY_INFO"
			+ "(date TEXT,week TEXT,weather TEXT,diarytitle TEXT,diaryinfo TEXT,id INTEGER PRIMARY KEY AUTOINCREMENT)";
}

 

4.com.org.android.diary.db包的代码:


DataBaseHelper:

public class DataBaseHelper extends SQLiteOpenHelper{
	private static final int VERSION=1;
	public static final String DBNAME = "diary.db";
	public DataBaseHelper (Context context){
		super(context,DBNAME,null,VERSION);
	}
	
	public DataBaseHelper (Context context,int version){
		super(context,DBNAME,null,version);
	}
	/**
	 * 该函数是子啊第一次创建数据库的时候执行,实际上是第一次
	 * 得到SQLiteDatabase对象的时候才会被调用
	 */
	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		db.execSQL(Constant.TABLE_INFO);
	}
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		
	}
}


DiaryDao:

public class DiaryDao {
	private DataBaseHelper helper = null;

	public DiaryDao(Context context) {
		// TODO Auto-generated constructor stub
		helper = new DataBaseHelper(context);
	}
	/**
	 * 插入数据
	 * @param diary
	 */
	public void insert(Diary diary){
		SQLiteDatabase db = helper.getWritableDatabase();
		ContentValues values = new ContentValues();
		values.put("date", diary.getDate());
		values.put("week", diary.getWeek());
		values.put("weather", diary.getWeather());
		values.put("diarytitle", diary.getDiaryTitle());
		values.put("diaryinfo", diary.getDiaryInfo());
		db.insert("DIARY_INFO", null, values);
		db.close();
	}
	
	/**
	 * 根据id删除
	 * 
	 * @param id
	 */
	public void delete(int id) {
		SQLiteDatabase db = helper.getWritableDatabase();
		db.execSQL("delete from DIARY_INFO where id = " + id);
		//System.out.println(db.delete("DIARY_INFO", "id=" + id, null));
		db.close();
	}
	/**
	 * 查询
	 * @param diaries
	 */
	public void query(List<Diary> diaries) {
		SQLiteDatabase db = helper.getReadableDatabase();
		Cursor cursor = db.query("DIARY_INFO", null, null,
				null, null, null, "id desc");
		diaries.clear();
		while(cursor.moveToNext()){
			Diary diary = new Diary();
			String title = cursor.getString(cursor.getColumnIndex("diarytitle"));
			String info = cursor.getString(cursor.getColumnIndex("diaryinfo"));
			String date = cursor.getString(cursor.getColumnIndex("date"));
			String week = cursor.getString(cursor.getColumnIndex("week"));
			String weather = cursor.getString(cursor.getColumnIndex("weather"));
			int id = cursor.getInt(cursor.getColumnIndex("id"));
			diary.setDate(date);
			diary.setWeek(week);
			diary.setWeather(weather);
			diary.setDiaryTitle(title);
			diary.setDiaryInfo(info);
			diary.setId(id);
			diaries.add(diary);
		}
		cursor.close();
		db.close();
	}
	
	public void deleteAll() {
		String delete_sql="delete from DIARY_INFO";
		SQLiteDatabase db=helper.getWritableDatabase();
		db.execSQL(delete_sql);
		db.close();
	}
	
	public void dimSearch(EditText editText,List<Diary> diaries){
		SQLiteDatabase db=helper.getReadableDatabase();
		Cursor cursor = db.query("DIARY_INFO", null, "diaryinfo like '%" + editText.getText().toString() + "%'", null, null, null, "id desc");
		diaries.clear();
		while(cursor.moveToNext()){
			Diary diary = new Diary();
			String date = cursor.getString(cursor.getColumnIndex("date"));
			String week=cursor.getString(cursor.getColumnIndex("week"));
			String weather = cursor.getString(cursor.getColumnIndex("weather"));
			String diaryInfo=cursor.getString(cursor.getColumnIndex("diaryinfo"));
			String diaryTitle=cursor.getString(cursor.getColumnIndex("diarytitle"));
			int id = cursor.getInt(cursor.getColumnIndex("id"));
			diary.setDate(date);
			diary.setWeek(week);
			diary.setWeather(weather);
			diary.setDiaryInfo(diaryInfo);
			diary.setDiaryTitle(diaryTitle);
			diary.setId(id);
			diaries.add(diary);
		}
		cursor.close();
		db.close();
	}
}


5.com.org.android.diary.model包的代码:

 

Diary:

public class Diary {
	private String date;
	private String week;
	private String weather;
	private String diaryInfo;
	private String diaryTitle;
	private int id;
	public String getDate() {
		return date;
	}
	public void setDate(String date) {
		this.date = date;
	}
	public String getWeek() {
		return week;
	}
	public void setWeek(String week) {
		this.week = week;
	}
	public String getWeather() {
		return weather;
	}
	public void setWeather(String weather) {
		this.weather = weather;
	}
	public String getDiaryInfo() {
		return diaryInfo;
	}
	public void setDiaryInfo(String diaryInfo) {
		this.diaryInfo = diaryInfo;
	}
	public String getDiaryTitle() {
		return diaryTitle;
	}
	public void setDiaryTitle(String diaryTitle) {
		this.diaryTitle = diaryTitle;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	@Override
	public String toString() {
		return "Diary [date=" + date + ", week=" + week + ", weather="
				+ weather + ", diaryInfo=" + diaryInfo + ", diaryTitle="
				+ diaryTitle + ", id=" + id + "]";
	}
}


6.com.org.android.diary.service包的代码:

 

MyService:

public class MyService extends Service {
	public static MyService service = null;

	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		Log.d("MyService", "-----MyService onCreate-----");
		service = this;
	}

	@Override
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		super.onStart(intent, startId);
		Log.d("MyService", "-----MyService onStart-----");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		Log.d("MyService", "-----MyService onStartCommand-----");
		sendBroadcast(new Intent("com.android.set.remind.time"));
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				while (true) {
					try {
						Thread.sleep(60000);
						sendBroadcast(new Intent("com.android.system.time"));
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
			}
		}).start();
		return super.onStartCommand(intent, flags, startId);
	}
}

 

7.com.org.android.diary.utils包的代码:

 

FileOperate:

public class FileOperate {
	public static boolean wirteData(String fileName, String info) {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			try {
				FileOutputStream outStream = new FileOutputStream("/sdcard/"
						+ fileName + ".txt", true);
				OutputStreamWriter writer = new OutputStreamWriter(outStream,
						"gbk");
				writer.write(info);
				writer.write("\n");
				writer.flush();
				writer.close();// 记得关闭

				outStream.close();

			} catch (Exception e) {
				// TODO: handle exception
			}
			return true;
		} else {
			return false;
		}
	}
}


TimeFormatUtil:

public class TimeFormatUtil {
	public static String format(int x) {
		String s = "" + x;
		if (s.length() == 1)
			s = "0" + s;
		return s;
	}
}

 

8.com.org.android.diary.view包的代码:

 

LockPatternUtils:

public class LockPatternUtils {
	
	//private static final String TAG = "LockPatternUtils";
	private final static String KEY_LOCK_PWD = "lock_pwd";
	
	
	private static Context mContext;
	
	private static SharedPreferences preference;
	
	//private final ContentResolver mContentResolver;
	
	 public LockPatternUtils(Context context) {
	        mContext = context;
	        preference = PreferenceManager.getDefaultSharedPreferences(mContext);
	       // mContentResolver = context.getContentResolver();
	 }
	
	 /**
     * Deserialize a pattern.
     * @param string The pattern serialized with {@link #patternToString}
     * @return The pattern.
     */
    public static List<LockPatternView.Cell> stringToPattern(String string) {
        List<LockPatternView.Cell> result = new ArrayList<LockPatternView.Cell>();

        final byte[] bytes = string.getBytes();
        for (int i = 0; i < bytes.length; i++) {
            byte b = bytes[i];
            result.add(LockPatternView.Cell.of(b / 3, b % 3));
        }
        return result;
    }

    /**
     * Serialize a pattern.
     * @param pattern The pattern.
     * @return The pattern in string form.
     */
    public static String patternToString(List<LockPatternView.Cell> pattern) {
        if (pattern == null) {
            return "";
        }
        final int patternSize = pattern.size();

        byte[] res = new byte[patternSize];
        for (int i = 0; i < patternSize; i++) {
            LockPatternView.Cell cell = pattern.get(i);
            res[i] = (byte) (cell.getRow() * 3 + cell.getColumn());
        }
        return Arrays.toString(res);
    }
    
    public void saveLockPattern(List<LockPatternView.Cell> pattern){
    	Editor editor = preference.edit();
    	editor.putString(KEY_LOCK_PWD, patternToString(pattern));
    	editor.commit();
    }
    
    public String getLockPaternString(){
    	return preference.getString(KEY_LOCK_PWD, "");
    }
    
    public int checkPattern(List<LockPatternView.Cell> pattern) {
    	String stored = getLockPaternString();
    	if(!stored.isEmpty()){
    		return stored.equals(patternToString(pattern))?1:0;
    	}
    	return -1;
    }
    

    public void clearLock() {
    	saveLockPattern(null);
    }
  

}


MyWin8Button:

public class MyWin8Button extends ImageView{
	private Camera camera;   // 声明一个图像的摄像机
	private boolean newOne;  // 声明一个图像是否是第一次加载
	private int realWidth;       // 图片真实的宽度
	private int realHeight;       // 图片真实的高度
	private float x;    // 点击的x坐标
	private float y;    // 点击的y坐标
	private boolean isMiddle;  // 是否是在中间区域位置点击
	private boolean isMove;    // 是否在点击后移出该图像区域
	private final float SCALE_NUM = 0.95f;  // 缩放比例
	private final int ROTATE_NUM = 10;      // 倾斜程度
	private Matrix oldMatrix;   // 未添加任何效果的图像
	private boolean isFinish;   // 是否完成特效
	boolean xBigY = false;      // 判断x是否大于y
	float RolateX = 0;  // x偏移位置
	float RolateY = 0;  // y偏移位置

	public MyWin8Button(Context context) {
		super(context);
		camera = new Camera();   //  定义一个图像摄像机
		newOne = true;           //  定义是第一次加载
		oldMatrix = new Matrix();
		oldMatrix.set(getImageMatrix());  // 获取未添加任何效果的图像
		isFinish = true;  // 设置已完成特效
		isMiddle = false; // 设置不在中间区域
		isMove = false;   // 设置没有移开图像区域
	}
	
	public MyWin8Button(Context context, AttributeSet attributeSet) {
		super(context,attributeSet);
		camera = new Camera();   //  定义一个图像摄像机
		newOne = true;			 //  定义是第一次加载
		oldMatrix = new Matrix();
		oldMatrix.set(getImageMatrix());  // 获取未添加任何效果的图像
		isFinish = true;  // 设置已完成特效
		isMiddle = false; // 设置不在中间区域
		isMove = false;   // 设置没有移开图像区域
	}
	
	@SuppressLint("DrawAllocation")
	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		
		if (newOne){   // 如果是一个新的组件 进行初始化 并进行标识
			newOne = false;
			init();    // 进行初始化
		}
		
		canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG
				| Paint.FILTER_BITMAP_FLAG));
	}
	
	private void init(){
		// 获取真实的图像宽度
		realWidth = getWidth() - getPaddingLeft() - getPaddingRight();
		// 获取真实的图像高度
		realHeight = getHeight() - getPaddingTop() - getPaddingBottom();
		
		BitmapDrawable bd = (BitmapDrawable) getDrawable();  // 获取位图
		bd.setAntiAlias(true);   // 允许使用抗锯齿等功能
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {  // 触摸事件的响应
		super.onTouchEvent(event);
		
		// 判断事件  并且消除非触摸事件
		switch (event.getAction() & MotionEvent.ACTION_MASK) {
		// 响应按下的事件
		case MotionEvent.ACTION_DOWN:
			x = event.getX();  // 获取点击的x坐标
			y = event.getY();  // 获取点击的y坐标
			
			RolateX = realWidth / 2 - x;
			RolateY = realHeight / 2 - y;
			xBigY = Math.abs(RolateX) > Math.abs(RolateY) ? true : false;
			
			isMove = false;    // 设置未移出该区域
			
			// 判断是否在中间位置
			isMiddle = x > realWidth / 3 && x < realWidth * 2 / 3 && y > realHeight / 3 && y < realHeight * 2 / 3;
			if (isMiddle){
				scaleHandler.sendEmptyMessage(1);
			}
			else {
				rolateHandler.sendEmptyMessage(1);
			}
			
			break;
			
		// 响应移动的事件
		case MotionEvent.ACTION_MOVE:
			float x=event.getX();float y=event.getY();
			if(x > realWidth || y > realHeight || x < 0 || y < 0){
				isMove=true;
			}else{
				isMove=false;
			}
			break;
			
		// 响应抬起的事件
		case MotionEvent.ACTION_UP:
			if (isMiddle) {
				scaleHandler.sendEmptyMessage(6);
			} else {
				rolateHandler.sendEmptyMessage(6);
			}
			break;

		default:
			break;
		}
		return true;
	}
	
	private Handler scaleHandler = new Handler(){
		private Matrix matrix = new Matrix();  // 创建新的matrix
		private int count = 0;    // 调用限定
		private float s;  // 缩放保存值
		
		public void handleMessage(Message msg) {
			
			if (isFinish){  // 如果没完成   获取当前的矩阵
				matrix.set(getImageMatrix()); 
			}
			
			switch (msg.what) {  // 判断值
			case 1:
				if (!isFinish) {  // 没完成返回
					return;
				} else {
					isFinish = false;  // 设定未完成
					count = 0;         
					s = (float) Math.sqrt(Math.sqrt(SCALE_NUM));
					matrix.set(oldMatrix);
					BeginScale(matrix, s);
					scaleHandler.sendEmptyMessage(2);
				}
				break;
			case 2:
				BeginScale(matrix, s);
				if (count < 4) {
					scaleHandler.sendEmptyMessage(2);
				} else {
					isFinish = true;
				}
				count++;
				break;
			case 6:
				if (!isFinish) {
					scaleHandler.sendEmptyMessage(6);
				} else {
					isFinish = false;
					count = 0;
					s = (float) Math.sqrt(Math.sqrt(1.0f / SCALE_NUM));
					BeginScale(matrix, s);
					scaleHandler.sendEmptyMessage(2);
				}
				break;
			}
			
		};
	};
	
	//  开始进行缩放
	@SuppressWarnings("unused")
	@SuppressLint("HandlerLeak")
	private synchronized void BeginScale(Matrix matrix, float scale) {
		int scaleX = (int) (realWidth * 0.5f);
		int scaleY = (int) (realHeight * 0.5f);
		matrix.postScale(scale, scale, scaleX, scaleY);
		setImageMatrix(matrix);
	}
	
	
	private Handler rolateHandler = new Handler() {
		private Matrix matrix = new Matrix();
		private float count = 0;

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			matrix.set(getImageMatrix());
			switch (msg.what) {
			case 1:
				count = 0;
				BeginRolate(matrix, (xBigY ? count : 0), (xBigY ? 0 : count));
				rolateHandler.sendEmptyMessage(2);
				break;
			case 2:
				BeginRolate(matrix, (xBigY ? count : 0), (xBigY ? 0 : count));
				if (count < ROTATE_NUM) {
					rolateHandler.sendEmptyMessage(2);
				} else {
					isFinish = true;
				}
				count++;
				count++;
				break;
			case 3:
				BeginRolate(matrix, (xBigY ? count : 0), (xBigY ? 0 : count));
				if (count > 0) {
					rolateHandler.sendEmptyMessage(3);
				} else {
					isFinish = true;
				}
				count--;
				count--;
				break;
			case 6:
				count = ROTATE_NUM;
				BeginRolate(matrix, (xBigY ? count : 0), (xBigY ? 0 : count));
				rolateHandler.sendEmptyMessage(3);
				break;
			}
		}
	};

	private synchronized void BeginRolate(Matrix matrix, float rolateX,
			float rolateY) {
		// Bitmap bm = getImageBitmap();
		int scaleX = (int) (realWidth * 0.5f);
		int scaleY = (int) (realHeight * 0.5f);
		camera.save();
		camera.rotateX(RolateY > 0 ? rolateY : -rolateY);
		camera.rotateY(RolateX < 0 ? rolateX : -rolateX);
		camera.getMatrix(matrix);
		camera.restore();
		

		if (RolateX > 0 && rolateX != 0) {
			matrix.preTranslate(-realWidth, -scaleY);
			matrix.postTranslate(realWidth, scaleY);
		} else if (RolateY > 0 && rolateY != 0) {
			matrix.preTranslate(-scaleX, -realHeight);
			matrix.postTranslate(scaleX, realHeight);
		} else if (RolateX < 0 && rolateX != 0) {
			matrix.preTranslate(-0, -scaleY);
			matrix.postTranslate(0, scaleY);
		} else if (RolateY < 0 && rolateY != 0) {
			matrix.preTranslate(-scaleX, -0);
			matrix.postTranslate(scaleX, 0);
		}

		
		setImageMatrix(matrix);
	}

}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值