Repository: linmp4/quickmark Branch: master Commit: b933e8aa9f63 Files: 278 Total size: 1.0 MB Directory structure: gitextract_1ebxno1h/ ├── LICENSE ├── MoneyCharge/ │ ├── .gitignore │ ├── app/ │ │ ├── build.gradle │ │ ├── libs/ │ │ │ ├── Android_Location_V1.3.2.jar │ │ │ ├── Baidu-SpeechRecognitionUI-SDK-Android-1.6.2.jar │ │ │ ├── VoiceRecognition-1.6.2.jar │ │ │ ├── achartengine-1.1.0.jar │ │ │ ├── androidpiechart.jar │ │ │ ├── com.umeng.fb.v5.0.0.jar │ │ │ ├── com.umeng.message.lib1.4.1.jar │ │ │ ├── galaxy.jar │ │ │ └── nineoldandroids-2.4.0.jar │ │ ├── lint.xml │ │ └── src/ │ │ └── main/ │ │ ├── AndroidManifest.xml │ │ ├── java/ │ │ │ ├── com/ │ │ │ │ ├── cwp/ │ │ │ │ │ ├── chart/ │ │ │ │ │ │ ├── BaseFoldingLayout.java │ │ │ │ │ │ ├── ChartProp.java │ │ │ │ │ │ ├── ChartPropChangeListener.java │ │ │ │ │ │ ├── CheckAdapter.java │ │ │ │ │ │ ├── CustomMultiChoiceDialog.java │ │ │ │ │ │ ├── FoldingLayout.java │ │ │ │ │ │ ├── MenuFragment.java │ │ │ │ │ │ ├── MyAdspter.java │ │ │ │ │ │ ├── MyButton.java │ │ │ │ │ │ ├── MyButtonClickListener.java │ │ │ │ │ │ ├── OnFoldListener.java │ │ │ │ │ │ ├── PieChart.java │ │ │ │ │ │ ├── PieView.java │ │ │ │ │ │ ├── PiewController.java │ │ │ │ │ │ ├── PullToRefreshView.java │ │ │ │ │ │ ├── RiseNumberBase.java │ │ │ │ │ │ ├── RiseNumberTextView.java │ │ │ │ │ │ ├── SystemBarTintManager.java │ │ │ │ │ │ └── Util.java │ │ │ │ │ ├── cmoneycharge/ │ │ │ │ │ │ ├── About.java │ │ │ │ │ │ ├── AddPay.java │ │ │ │ │ │ ├── Author.java │ │ │ │ │ │ ├── BaseEffects.java │ │ │ │ │ │ ├── BaseFrament.java │ │ │ │ │ │ ├── Config.java │ │ │ │ │ │ ├── Constants.java │ │ │ │ │ │ ├── CrashApplication.java │ │ │ │ │ │ ├── CrashHandler.java │ │ │ │ │ │ ├── Description.java │ │ │ │ │ │ ├── DialogShowUtil.java │ │ │ │ │ │ ├── DigitUtil.java │ │ │ │ │ │ ├── Effectstype.java │ │ │ │ │ │ ├── FragmentPage1.java │ │ │ │ │ │ ├── FragmentPage2.java │ │ │ │ │ │ ├── FragmentPage3.java │ │ │ │ │ │ ├── FragmentPage4.java │ │ │ │ │ │ ├── InPtypeManager.java │ │ │ │ │ │ ├── IncomeData.java │ │ │ │ │ │ ├── KeyboardUtil.java │ │ │ │ │ │ ├── MainActivity.java │ │ │ │ │ │ ├── ModifyInP.java │ │ │ │ │ │ ├── NiftyDialogBuilder.java │ │ │ │ │ │ ├── PayChart.java │ │ │ │ │ │ ├── PayData.java │ │ │ │ │ │ ├── RotateBottom.java │ │ │ │ │ │ ├── SearchActivity.java │ │ │ │ │ │ ├── SettingActivity.java │ │ │ │ │ │ ├── Shake.java │ │ │ │ │ │ ├── SlideTop.java │ │ │ │ │ │ └── SysApplication.java │ │ │ │ │ └── pattern/ │ │ │ │ │ ├── CreateGesturePasswordActivity.java │ │ │ │ │ ├── GuideGesturePasswordActivity.java │ │ │ │ │ ├── LockPatternUtils.java │ │ │ │ │ ├── LockPatternView.java │ │ │ │ │ ├── ParseXmlService.java │ │ │ │ │ ├── UnlockGesturePasswordActivity.java │ │ │ │ │ └── UpdateManager.java │ │ │ │ ├── example/ │ │ │ │ │ └── testpic/ │ │ │ │ │ ├── AlbumHelper.java │ │ │ │ │ ├── Bimp.java │ │ │ │ │ ├── BitmapCache.java │ │ │ │ │ ├── FileUtils.java │ │ │ │ │ ├── ImageBucket.java │ │ │ │ │ ├── ImageBucketAdapter.java │ │ │ │ │ ├── ImageGridActivity.java │ │ │ │ │ ├── ImageGridAdapter.java │ │ │ │ │ ├── ImageItem.java │ │ │ │ │ ├── NoScrollGridView.java │ │ │ │ │ ├── PhotoActivity.java │ │ │ │ │ ├── PublishedActivity.java │ │ │ │ │ └── TestPicActivity.java │ │ │ │ ├── slidingmenu/ │ │ │ │ │ └── lib/ │ │ │ │ │ ├── CanvasTransformerBuilder.java │ │ │ │ │ ├── CustomViewAbove.java │ │ │ │ │ ├── CustomViewBehind.java │ │ │ │ │ ├── MenuInterface.java │ │ │ │ │ ├── SlidingMenu.java │ │ │ │ │ └── app/ │ │ │ │ │ ├── SlidingActivity.java │ │ │ │ │ ├── SlidingActivityBase.java │ │ │ │ │ ├── SlidingActivityHelper.java │ │ │ │ │ ├── SlidingFragmentActivity.java │ │ │ │ │ ├── SlidingListActivity.java │ │ │ │ │ ├── SlidingMapActivity.java │ │ │ │ │ ├── SlidingPreferenceActivity.java │ │ │ │ │ └── SystemBarTintManager.java │ │ │ │ ├── umeng/ │ │ │ │ │ └── fb/ │ │ │ │ │ └── example/ │ │ │ │ │ ├── AppApplication.java │ │ │ │ │ ├── AppPush.java │ │ │ │ │ ├── CustomActivity.java │ │ │ │ │ └── MyPushIntentService.java │ │ │ │ └── zhy/ │ │ │ │ └── view/ │ │ │ │ ├── HorizontalProgressBarWithNumber.java │ │ │ │ └── RoundProgressBarWidthNumber.java │ │ │ └── cwp/ │ │ │ └── moneycharge/ │ │ │ ├── dao/ │ │ │ │ ├── AccountDAO.java │ │ │ │ ├── DBOpenHelper.java │ │ │ │ ├── IncomeDAO.java │ │ │ │ ├── ItypeDAO.java │ │ │ │ ├── NoteDAO.java │ │ │ │ ├── PayDAO.java │ │ │ │ └── PtypeDAO.java │ │ │ └── model/ │ │ │ ├── ActivityManager.java │ │ │ ├── CustomDialog.java │ │ │ ├── Datapicker.java │ │ │ ├── KindData.java │ │ │ ├── Tb_account.java │ │ │ ├── Tb_income.java │ │ │ ├── Tb_itype.java │ │ │ ├── Tb_note.java │ │ │ ├── Tb_pay.java │ │ │ └── Tb_ptype.java │ │ └── res/ │ │ ├── anim/ │ │ │ ├── animation_1.xml │ │ │ ├── animation_2.xml │ │ │ ├── fade_ins.xml │ │ │ ├── hold.xml │ │ │ ├── in_from_right.xml │ │ │ ├── interpolator_cycle.xml │ │ │ ├── out_to_left.xml │ │ │ ├── push_bottom_in.xml │ │ │ ├── push_bottom_in_2.xml │ │ │ ├── push_up_in.xml │ │ │ ├── push_up_out.xml │ │ │ ├── shake.xml │ │ │ ├── shake_x.xml │ │ │ └── shake_y.xml │ │ ├── color/ │ │ │ ├── cost_text.xml │ │ │ ├── tab_friendfeed_text.xml │ │ │ ├── tab_home_text.xml │ │ │ ├── tab_more_text.xml │ │ │ └── tab_myfeed_text.xml │ │ ├── drawable/ │ │ │ ├── addphoto_btn.xml │ │ │ ├── bg_border.xml │ │ │ ├── bgd_relatly_line.xml │ │ │ ├── bt_add_pic.xml │ │ │ ├── bt_nobgd.xml │ │ │ ├── bt_queding.xml │ │ │ ├── bt_quxiao.xml │ │ │ ├── bt_shanchu.xml │ │ │ ├── btn_cancel_selector.xml │ │ │ ├── btn_login_selector.xml │ │ │ ├── btn_press.xml │ │ │ ├── btn_selector.xml │ │ │ ├── btn_unpress.xml │ │ │ ├── chart_left_btn.xml │ │ │ ├── chart_right_btn.xml │ │ │ ├── chart_silding_btn.xml │ │ │ ├── checkbox.xml │ │ │ ├── common_btn_green.xml │ │ │ ├── common_btn_red.xml │ │ │ ├── corner_bdbdbd.xml │ │ │ ├── corner_e0e0e0.xml │ │ │ ├── corner_f2f2f2.xml │ │ │ ├── dialog_bg.xml │ │ │ ├── dialog_bottom_bg.xml │ │ │ ├── fb_send_btn_bg.xml │ │ │ ├── keyboard_key.xml │ │ │ ├── locate_btn.xml │ │ │ ├── search_button_type.xml │ │ │ ├── selector.xml │ │ │ ├── shadow.xml │ │ │ ├── skin_color_button.xml │ │ │ ├── tab_friendfeed_btn.xml │ │ │ ├── tab_home_btn.xml │ │ │ ├── tab_more_btn.xml │ │ │ ├── tab_myfeed_btn.xml │ │ │ ├── text_while.xml │ │ │ └── welcome_bg.xml │ │ ├── drawable-hdpi/ │ │ │ ├── common_lv_item_for_metadata_bg.xml │ │ │ ├── common_lv_item_higher_bg.xml │ │ │ ├── common_toolbar_btn.xml │ │ │ ├── common_toolbar_btn_small.xml │ │ │ ├── form_row_input_middle.xml │ │ │ ├── form_row_input_middle_short_left.xml │ │ │ ├── form_row_input_middle_short_right.xml │ │ │ ├── form_row_input_top.xml │ │ │ ├── income_tab_btn_radio.xml │ │ │ ├── main_add_expense_quickly.xml │ │ │ ├── main_row_stat.xml │ │ │ └── payout_tab_btn_radio.xml │ │ ├── layout/ │ │ │ ├── about.xml │ │ │ ├── account.xml │ │ │ ├── activity_custom.xml │ │ │ ├── activity_image_bucket.xml │ │ │ ├── activity_image_grid.xml │ │ │ ├── activity_index.xml │ │ │ ├── activity_main.xml │ │ │ ├── activity_photo.xml │ │ │ ├── activity_selectimg.xml │ │ │ ├── add.xml │ │ │ ├── addincome.xml │ │ │ ├── addnote.xml │ │ │ ├── addpay.xml │ │ │ ├── author.xml │ │ │ ├── changepwd.xml │ │ │ ├── child.xml │ │ │ ├── custom_fb_dev_reply.xml │ │ │ ├── custom_fb_user_reply.xml │ │ │ ├── custom_view.xml │ │ │ ├── data.xml │ │ │ ├── description.xml │ │ │ ├── dialog.xml │ │ │ ├── dialog_layout.xml │ │ │ ├── dialog_multichoice_item.xml │ │ │ ├── dialog_multichoice_layout.xml │ │ │ ├── fragment_1.xml │ │ │ ├── fragment_2.xml │ │ │ ├── fragment_3.xml │ │ │ ├── fragment_4.xml │ │ │ ├── fragment_5.xml │ │ │ ├── fragnew_3.xml │ │ │ ├── frame_menu.xml │ │ │ ├── gesturepassword_create.xml │ │ │ ├── gesturepassword_guide.xml │ │ │ ├── gesturepassword_unlock.xml │ │ │ ├── group.xml │ │ │ ├── gvitem.xml │ │ │ ├── income.xml │ │ │ ├── incomedata.xml │ │ │ ├── infomanage.xml │ │ │ ├── inptypemanager.xml │ │ │ ├── item_image_bucket.xml │ │ │ ├── item_image_grid.xml │ │ │ ├── item_popupwindows.xml │ │ │ ├── item_published_grida.xml │ │ │ ├── list.xml │ │ │ ├── login.xml │ │ │ ├── modifyinp.xml │ │ │ ├── modifynote.xml │ │ │ ├── note.xml │ │ │ ├── notification_item.xml │ │ │ ├── pay.xml │ │ │ ├── paychart.xml │ │ │ ├── paydata.xml │ │ │ ├── pidata.xml │ │ │ ├── popwindow_layout.xml │ │ │ ├── preview_layout.xml │ │ │ ├── refresh_footer.xml │ │ │ ├── refresh_header.xml │ │ │ ├── register.xml │ │ │ ├── search_activity.xml │ │ │ ├── setting.xml │ │ │ ├── showinfo.xml │ │ │ ├── slidingmenumain.xml │ │ │ ├── softupdate_progress.xml │ │ │ ├── spinner.xml │ │ │ └── voice_setting.xml │ │ ├── menu/ │ │ │ └── index.xml │ │ ├── values/ │ │ │ ├── attr_progress_bar.xml │ │ │ ├── attrs.xml │ │ │ ├── colors.xml │ │ │ ├── dimens.xml │ │ │ ├── ids.xml │ │ │ ├── moneychargetype.xml │ │ │ ├── strings.xml │ │ │ └── styles.xml │ │ ├── values-sw600dp/ │ │ │ └── dimens.xml │ │ ├── values-sw720dp-land/ │ │ │ └── dimens.xml │ │ ├── values-v11/ │ │ │ └── styles.xml │ │ ├── values-v14/ │ │ │ └── styles.xml │ │ └── xml/ │ │ ├── menu.xml │ │ └── symbols_num.xml │ ├── build.gradle │ ├── gradle/ │ │ └── wrapper/ │ │ ├── gradle-wrapper.jar │ │ └── gradle-wrapper.properties │ ├── gradlew │ ├── gradlew.bat │ ├── import-summary.txt │ └── settings.gradle └── README.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: LICENSE ================================================ The MIT License (MIT) Copyright (c) 2015 linmp4 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: MoneyCharge/.gitignore ================================================ ### Android ### .gradle /local.properties .DS_Store /captures .externalNativeBuild HELP.md target/ !.mvn/wrapper/maven-wrapper.jar !**/src/main/** !**/src/test/** ### STS ### .apt_generated .classpath .factorypath .project .settings .springBeans .sts4-cache ### IntelliJ IDEA ### .idea *.iws *.iml *.ipr ### NetBeans ### /nbproject/private/ /nbbuild/ /dist/ /nbdist/ /.nb-gradle/ build/ ### VS Code ### .vscode/ ### log ### *.log ### Java build package### src/main/java/META-INF/MANIFEST.MF ================================================ FILE: MoneyCharge/app/build.gradle ================================================ apply plugin: 'com.android.application' android { compileSdkVersion 22 buildToolsVersion "22.0.1" defaultConfig { applicationId "com.cwp.cmoneycharge" minSdkVersion 15 targetSdkVersion 18 compileOptions { sourceCompatibility JavaVersion.VERSION_1_7 targetCompatibility JavaVersion.VERSION_1_7 } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' } } } dependencies { compile 'com.android.support:support-v4:22.2.1' compile files('libs/achartengine-1.1.0.jar') compile files('libs/Android_Location_V1.3.2.jar') compile files('libs/androidpiechart.jar') compile files('libs/Baidu-SpeechRecognitionUI-SDK-Android-1.6.2.jar') compile files('libs/com.umeng.fb.v5.0.0.jar') compile files('libs/com.umeng.message.lib1.4.1.jar') compile files('libs/galaxy.jar') compile files('libs/nineoldandroids-2.4.0.jar') compile files('libs/VoiceRecognition-1.6.2.jar') } ================================================ FILE: MoneyCharge/app/lint.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/chart/BaseFoldingLayout.java ================================================ /* * Copyright (C) 2013 Priboi Tiberiu * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cwp.chart; import com.cwp.cmoneycharge.R; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Rect; import android.graphics.Shader.TileMode; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; /** * The folding layout where the number of folds, the anchor point and the * orientation of the fold can be specified. Each of these parameters can be * modified individually and updates and resets the fold to a default (unfolded) * state. The fold factor varies between 0 (completely unfolded flat image) to * 1.0 (completely folded, non-visible image). * * This layout throws an exception if there is more than one child added to the * view. For more complicated view hierarchy's inside the folding layout, the * views should all be nested inside 1 parent layout. * * This layout folds the contents of its child in real time. By applying matrix * transformations when drawing to canvas, the contents of the child may change * as the fold takes place. It is important to note that there are jagged edges * about the perimeter of the layout as a result of applying transformations to * a rectangle. This can be avoided by having the child of this layout wrap its * content inside a 1 pixel transparent border. This will cause an anti-aliasing * like effect and smoothen out the edges. * */ public class BaseFoldingLayout extends ViewGroup { /* * A bug was introduced in Android 4.3 that ignores changes to the Canvas * state between multiple calls to super.dispatchDraw() when running with * hardware acceleration. To account for this bug, a slightly different * approach was taken to fold a static image whereby a bitmap of the * original contents is captured and drawn in segments onto the canvas. * However, this method does not permit the folding of a TextureView hosting * a live camera feed which continuously updates. Furthermore, the sepia * effect was removed from the bitmap variation of the demo to simplify the * logic when running with this workaround." */ public static enum Orientation { VERTICAL, HORIZONTAL } private final String FOLDING_VIEW_EXCEPTION_MESSAGE = "Folding Layout can only 1 child at " + "most"; private final float SHADING_ALPHA = 0.8f; private final float SHADING_FACTOR = 0.5f; private final int DEPTH_CONSTANT = 1500; private final int NUM_OF_POLY_POINTS = 8; private Rect[] mFoldRectArray; private Matrix[] mMatrix; protected Orientation mOrientation = Orientation.VERTICAL; protected float mAnchorFactor = 0; private float mFoldFactor = 0; private int mNumberOfFolds = 2; private boolean mIsHorizontal = true; private int mOriginalWidth = 0; private int mOriginalHeight = 0; private float mFoldMaxWidth = 0; private float mFoldMaxHeight = 0; private float mFoldDrawWidth = 0; private float mFoldDrawHeight = 0; private boolean mIsFoldPrepared = false; private boolean mShouldDraw = true; private Paint mSolidShadow; private Paint mGradientShadow; private LinearGradient mShadowLinearGradient; private Matrix mShadowGradientMatrix; private float[] mSrc; private float[] mDst; private OnFoldListener mFoldListener; private float mPreviousFoldFactor = 0; private Bitmap mFullBitmap; private Rect mDstRect; public BaseFoldingLayout(Context context) { super(context); } public BaseFoldingLayout(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } public BaseFoldingLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context, attrs); } public void init(Context context, AttributeSet attrs) { // now style everything! TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.FoldingMenu); int mFoldNumber = ta.getInt(R.styleable.FoldingMenu_foldNumber, mNumberOfFolds); if (mFoldNumber > 0 && mFoldNumber < 7) { mNumberOfFolds = mFoldNumber; } else { mNumberOfFolds = 2; } ta.recycle(); } @Override protected boolean addViewInLayout(View child, int index, LayoutParams params, boolean preventRequestLayout) { throwCustomException(getChildCount()); boolean returnValue = super.addViewInLayout(child, index, params, preventRequestLayout); return returnValue; } @Override public void addView(View child, int index, LayoutParams params) { throwCustomException(getChildCount()); super.addView(child, index, params); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { View child = getChildAt(0); measureChild(child, widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(widthMeasureSpec, heightMeasureSpec); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { View child = getChildAt(0); child.layout(0, 0, child.getMeasuredWidth(), child.getMeasuredHeight()); updateFold(); } /** * The custom exception to be thrown so as to limit the number of views in * this layout to at most one. */ private class NumberOfFoldingLayoutChildrenException extends RuntimeException { /** * */ private static final long serialVersionUID = 1L; public NumberOfFoldingLayoutChildrenException(String message) { super(message); } } /** * Throws an exception if the number of views added to this layout exceeds * one. */ private void throwCustomException(int numOfChildViews) { if (numOfChildViews == 1) { throw new NumberOfFoldingLayoutChildrenException( FOLDING_VIEW_EXCEPTION_MESSAGE); } } public void setFoldListener(OnFoldListener foldListener) { mFoldListener = foldListener; } /** * Sets the fold factor of the folding view and updates all the * corresponding matrices and values to account for the new fold factor. * Once that is complete, it redraws itself with the new fold. */ public void setFoldFactor(float foldFactor) { if (foldFactor != mFoldFactor) { mFoldFactor = foldFactor; calculateMatrices(); invalidate(); } } public void setOrientation(Orientation orientation) { if (orientation != mOrientation) { mOrientation = orientation; updateFold(); } } public void setAnchorFactor(float anchorFactor) { if (anchorFactor != mAnchorFactor) { mAnchorFactor = anchorFactor; updateFold(); } } public void setNumberOfFolds(int numberOfFolds) { if (numberOfFolds != mNumberOfFolds) { mNumberOfFolds = numberOfFolds; updateFold(); } } public float getAnchorFactor() { return mAnchorFactor; } public Orientation getOrientation() { return mOrientation; } public float getFoldFactor() { return mFoldFactor; } public int getNumberOfFolds() { return mNumberOfFolds; } private void updateFold() { prepareFold(mOrientation, mAnchorFactor, mNumberOfFolds); calculateMatrices(); invalidate(); } /** * This method is called in order to update the fold's orientation, anchor * point and number of folds. This creates the necessary setup in order to * prepare the layout for a fold with the specified parameters. Some of the * dimensions required for the folding transformation are also acquired * here. * * After this method is called, it will be in a completely unfolded state by * default. */ private void prepareFold(Orientation orientation, float anchorFactor, int numberOfFolds) { mSrc = new float[NUM_OF_POLY_POINTS]; mDst = new float[NUM_OF_POLY_POINTS]; mDstRect = new Rect(); mFoldFactor = 0; mPreviousFoldFactor = 0; mIsFoldPrepared = false; mSolidShadow = new Paint(); mGradientShadow = new Paint(); mOrientation = orientation; mIsHorizontal = (orientation == Orientation.HORIZONTAL); if (mIsHorizontal) { mShadowLinearGradient = new LinearGradient(0, 0, SHADING_FACTOR, 0, Color.BLACK, Color.TRANSPARENT, TileMode.CLAMP); } else { mShadowLinearGradient = new LinearGradient(0, 0, 0, SHADING_FACTOR, Color.BLACK, Color.TRANSPARENT, TileMode.CLAMP); } mGradientShadow.setStyle(Style.FILL); mGradientShadow.setShader(mShadowLinearGradient); mShadowGradientMatrix = new Matrix(); mAnchorFactor = anchorFactor; mNumberOfFolds = numberOfFolds; mOriginalWidth = getMeasuredWidth(); mOriginalHeight = getMeasuredHeight(); mFoldRectArray = new Rect[mNumberOfFolds]; mMatrix = new Matrix[mNumberOfFolds]; for (int x = 0; x < mNumberOfFolds; x++) { mMatrix[x] = new Matrix(); } int h = mOriginalHeight; int w = mOriginalWidth; if (Util.IS_JBMR2 && h != 0 && w != 0) { mFullBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(mFullBitmap); getChildAt(0).draw(canvas); } int delta = Math.round(mIsHorizontal ? ((float) w) / ((float) mNumberOfFolds) : ((float) h) / ((float) mNumberOfFolds)); /* * Loops through the number of folds and segments the full layout into a * number of smaller equal components. If the number of folds is odd, * then one of the components will be smaller than all the rest. Note * that deltap below handles the calculation for an odd number of folds. */ for (int x = 0; x < mNumberOfFolds; x++) { if (mIsHorizontal) { int deltap = (x + 1) * delta > w ? w - x * delta : delta; mFoldRectArray[x] = new Rect(x * delta, 0, x * delta + deltap, h); } else { int deltap = (x + 1) * delta > h ? h - x * delta : delta; mFoldRectArray[x] = new Rect(0, x * delta, w, x * delta + deltap); } } if (mIsHorizontal) { mFoldMaxHeight = h; mFoldMaxWidth = delta; } else { mFoldMaxHeight = delta; mFoldMaxWidth = w; } mIsFoldPrepared = true; } /* * Calculates the transformation matrices used to draw each of the separate * folding segments from this view. */ private void calculateMatrices() { mShouldDraw = true; if (!mIsFoldPrepared) { return; } /** * If the fold factor is 1 than the folding view should not be seen and * the canvas can be left completely empty. */ if (mFoldFactor == 1) { mShouldDraw = false; return; } // if (mFoldFactor == 0 && mPreviousFoldFactor > 0 // && mFoldListener != null) { // // mFoldListener.onEndFold(mFoldFactor); // }else if (mPreviousFoldFactor == 0 && mFoldFactor > 0 // && mFoldListener != null) { // // mFoldListener.onStartFold(mFoldFactor); // } else if(mFoldListener != null) { // mFoldListener.onFoldingState(mFoldFactor); // } if (mFoldFactor > 0.9f && mFoldFactor > mPreviousFoldFactor && mFoldListener != null) { mFoldListener.onEndFold(mFoldFactor); } else if (mFoldFactor < 0.1f && mFoldFactor < mPreviousFoldFactor && mFoldListener != null) { mFoldListener.onStartFold(mFoldFactor); } else if (mFoldListener != null) { mFoldListener.onFoldingState(mFoldFactor, mFoldDrawHeight); } // if(mFoldFactor == 0 && mFoldListener != null) { // mFoldListener.onStartFold(mFoldFactor); // } else if(mFoldFactor == 1 && mFoldListener != null) { // mFoldListener.onEndFold(mFoldFactor); // } else { // mFoldListener.onFoldingState(mFoldFactor); // } mPreviousFoldFactor = mFoldFactor; /* * Reset all the transformation matrices back to identity before * computing the new transformation */ for (int x = 0; x < mNumberOfFolds; x++) { mMatrix[x].reset(); } float cTranslationFactor = 1 - mFoldFactor; float translatedDistance = mIsHorizontal ? mOriginalWidth * cTranslationFactor : mOriginalHeight * cTranslationFactor; float translatedDistancePerFold = Math.round(translatedDistance / mNumberOfFolds); /* * For an odd number of folds, the rounding error may cause the * translatedDistancePerFold to be grater than the max fold width or * height. */ mFoldDrawWidth = mFoldMaxWidth < translatedDistancePerFold ? translatedDistancePerFold : mFoldMaxWidth; mFoldDrawHeight = mFoldMaxHeight < translatedDistancePerFold ? translatedDistancePerFold : mFoldMaxHeight; float translatedDistanceFoldSquared = translatedDistancePerFold * translatedDistancePerFold; /* * Calculate the depth of the fold into the screen using pythagorean * theorem. */ float depth = mIsHorizontal ? (float) Math .sqrt((double) (mFoldDrawWidth * mFoldDrawWidth - translatedDistanceFoldSquared)) : (float) Math .sqrt((double) (mFoldDrawHeight * mFoldDrawHeight - translatedDistanceFoldSquared)); /* * The size of some object is always inversely proportional to the * distance it is away from the viewpoint. The constant can be varied to * to affect the amount of perspective. */ float scaleFactor = DEPTH_CONSTANT / (DEPTH_CONSTANT + depth); float scaledWidth, scaledHeight, bottomScaledPoint, topScaledPoint, rightScaledPoint, leftScaledPoint; if (mIsHorizontal) { scaledWidth = mFoldDrawWidth * cTranslationFactor; scaledHeight = mFoldDrawHeight * scaleFactor; } else { scaledWidth = mFoldDrawWidth * scaleFactor; scaledHeight = mFoldDrawHeight * cTranslationFactor; } topScaledPoint = (mFoldDrawHeight - scaledHeight) / 2.0f; bottomScaledPoint = topScaledPoint + scaledHeight; leftScaledPoint = (mFoldDrawWidth - scaledWidth) / 2.0f; rightScaledPoint = leftScaledPoint + scaledWidth; float anchorPoint = mIsHorizontal ? mAnchorFactor * mOriginalWidth : mAnchorFactor * mOriginalHeight; /* The fold along which the anchor point is located. */ float midFold = mIsHorizontal ? (anchorPoint / mFoldDrawWidth) : anchorPoint / mFoldDrawHeight; mSrc[0] = 0; mSrc[1] = 0; mSrc[2] = 0; mSrc[3] = mFoldDrawHeight; mSrc[4] = mFoldDrawWidth; mSrc[5] = 0; mSrc[6] = mFoldDrawWidth; mSrc[7] = mFoldDrawHeight; /* * Computes the transformation matrix for each fold using the values * calculated above. */ for (int x = 0; x < mNumberOfFolds; x++) { boolean isEven = (x % 2 == 0); if (mIsHorizontal) { mDst[0] = (anchorPoint > x * mFoldDrawWidth) ? anchorPoint + (x - midFold) * scaledWidth : anchorPoint - (midFold - x) * scaledWidth; mDst[1] = isEven ? 0 : topScaledPoint; mDst[2] = mDst[0]; mDst[3] = isEven ? mFoldDrawHeight : bottomScaledPoint; mDst[4] = (anchorPoint > (x + 1) * mFoldDrawWidth) ? anchorPoint + (x + 1 - midFold) * scaledWidth : anchorPoint - (midFold - x - 1) * scaledWidth; mDst[5] = isEven ? topScaledPoint : 0; mDst[6] = mDst[4]; mDst[7] = isEven ? bottomScaledPoint : mFoldDrawHeight; } else { mDst[0] = isEven ? 0 : leftScaledPoint; mDst[1] = (anchorPoint > x * mFoldDrawHeight) ? anchorPoint + (x - midFold) * scaledHeight : anchorPoint - (midFold - x) * scaledHeight; mDst[2] = isEven ? leftScaledPoint : 0; mDst[3] = (anchorPoint > (x + 1) * mFoldDrawHeight) ? anchorPoint + (x + 1 - midFold) * scaledHeight : anchorPoint - (midFold - x - 1) * scaledHeight; mDst[4] = isEven ? mFoldDrawWidth : rightScaledPoint; mDst[5] = mDst[1]; mDst[6] = isEven ? rightScaledPoint : mFoldDrawWidth; mDst[7] = mDst[3]; } /* * Pixel fractions are present for odd number of folds which need to * be rounded off here. */ for (int y = 0; y < 8; y++) { mDst[y] = Math.round(mDst[y]); } /* * If it so happens that any of the folds have reached a point where * the width or height of that fold is 0, then nothing needs to be * drawn onto the canvas because the view is essentially completely * folded. */ if (mIsHorizontal) { if (mDst[4] <= mDst[0] || mDst[6] <= mDst[2]) { mShouldDraw = false; return; } } else { if (mDst[3] <= mDst[1] || mDst[7] <= mDst[5]) { mShouldDraw = false; return; } } /* Sets the shadow and bitmap transformation matrices. */ mMatrix[x].setPolyToPoly(mSrc, 0, mDst, 0, NUM_OF_POLY_POINTS / 2); } /* * The shadows on the folds are split into two parts: Solid shadows and * gradients. Every other fold has a solid shadow which overlays the * whole fold. Similarly, the folds in between these alternating folds * also have an overlaying shadow. However, it is a gradient that takes * up part of the fold as opposed to a solid shadow overlaying the whole * fold. */ /* Solid shadow paint object. */ int alpha = (int) (mFoldFactor * 255 * SHADING_ALPHA); mSolidShadow.setColor(Color.argb(alpha, 0, 0, 0)); if (mIsHorizontal) { mShadowGradientMatrix.setScale(mFoldDrawWidth, 1); mShadowLinearGradient.setLocalMatrix(mShadowGradientMatrix); } else { mShadowGradientMatrix.setScale(1, mFoldDrawHeight); mShadowLinearGradient.setLocalMatrix(mShadowGradientMatrix); } mGradientShadow.setAlpha(alpha); } @Override protected void dispatchDraw(Canvas canvas) { /** * If prepareFold has not been called or if preparation has not * completed yet, then no custom drawing will take place so only need to * invoke super's onDraw and return. */ if (!mIsFoldPrepared || mFoldFactor == 0) { super.dispatchDraw(canvas); return; } if (!mShouldDraw) { return; } Rect src; /* * Draws the bitmaps and shadows on the canvas with the appropriate * transformations. */ for (int x = 0; x < mNumberOfFolds; x++) { src = mFoldRectArray[x]; /* The canvas is saved and restored for every individual fold */ canvas.save(); /* * Concatenates the canvas with the transformation matrix for the * the segment of the view corresponding to the actual image being * displayed. */ canvas.concat(mMatrix[x]); if (Util.IS_JBMR2) { mDstRect.set(0, 0, src.width(), src.height()); canvas.drawBitmap(mFullBitmap, src, mDstRect, null); } else { /* * The same transformation matrix is used for both the shadow * and the image segment. The canvas is clipped to account for * the size of each fold and is translated so they are drawn in * the right place. The shadow is then drawn on top of the * different folds using the sametransformation matrix. */ canvas.clipRect(0, 0, src.right - src.left, src.bottom - src.top); if (mIsHorizontal) { canvas.translate(-src.left, 0); } else { canvas.translate(0, -src.top); } super.dispatchDraw(canvas); if (mIsHorizontal) { canvas.translate(src.left, 0); } else { canvas.translate(0, src.top); } } /* Draws the shadows corresponding to this specific fold. */ if (x % 2 == 0) { canvas.drawRect(0, 0, mFoldDrawWidth, mFoldDrawHeight, mSolidShadow); } else { canvas.drawRect(0, 0, mFoldDrawWidth, mFoldDrawHeight, mGradientShadow); } canvas.restore(); } } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/chart/ChartProp.java ================================================ package com.cwp.chart; import android.graphics.Color; import android.util.Log; import android.view.View; public class ChartProp { private int mId = 0; private float mPercent = 1.0f; private View mParent = null; private int mColor = Color.WHITE; private float mSweepAngle = 0f; private String mName = ""; private String mName2 = ""; private float mStartAngle = 0f; private float mEndAngle = 0f; public ChartProp(View chartView) { mParent = chartView; } public void setId(int id) { mId = id; } public int getId() { return mId; } /** * the percent ,such as 0.5f,0.05f, NEIGHTER 50% NOR 50 * * @param percent */ public void setPercent(float percent) { // Log.e("caizh", "percent="+percent); mPercent = percent; mSweepAngle = percent * 360; // invalidate(); } public float getPercent() { return mPercent; } public float getSweepAngle() { return mSweepAngle; } public void setColor(int color) { mColor = color; // invalidate(); } public int getColor() { return mColor; } public String getName() { return mName; } public void setName(String name) { this.mName = name; // invalidate(); } public String getName2() { return mName2; } public void setName2(String name) { this.mName2 = name; // invalidate(); } private void invalidate() { if (mParent != null) { mParent.invalidate(); } } public float getStartAngle() { return mStartAngle; } public void setStartAngle(float startAngle) { this.mStartAngle = (startAngle); } public float getEndAngle() { return mEndAngle; } public void setEndAngle(float endAngle) { this.mEndAngle = (endAngle); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/chart/ChartPropChangeListener.java ================================================ package com.cwp.chart; public interface ChartPropChangeListener { public void getChartProp(ChartProp chartProp); } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/chart/CheckAdapter.java ================================================ package com.cwp.chart; import com.cwp.cmoneycharge.R; import android.content.Context; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.TextView; public class CheckAdapter extends BaseAdapter { private class ViewHolder { public TextView name; public CheckBox checkBox; } private String[] names; private LayoutInflater mInflater; private Context mContext; private boolean[] checkedItem; public CheckAdapter(Context context, String[] names, boolean[] checkedItem) { this.names = names; this.checkedItem = checkedItem; this.mContext = context; mInflater = (LayoutInflater) mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return names.length; } @Override public Object getItem(int position) { return names[position]; } @Override public long getItemId(int position) { return position; } public View getItemView(int position) { return lmap.get(position); } public boolean[] getCheckedItem() { for (int i = 0; i < getCount(); i++) { View view = this.getView(i, null, null); CheckBox box = (CheckBox)view.findViewById(R.id.chk_selectone); checkedItem[i] = box.isChecked(); } return checkedItem; } SparseArray lmap = new SparseArray(); public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; View view; if (lmap.get(position) == null) { view = mInflater.inflate(R.layout.dialog_multichoice_item, null); holder = new ViewHolder(); holder.name = (TextView) view.findViewById(R.id.contact_name); holder.checkBox = (CheckBox) view.findViewById(R.id.chk_selectone); lmap.put(position, view); if (names != null && names.length > 0) { String name = (String) names[position]; holder.name.setText(name); holder.checkBox.setChecked(checkedItem[position]); } view.setTag(holder); } else { view = lmap.get(position); holder = (ViewHolder) view.getTag(); } return view; } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/chart/CustomMultiChoiceDialog.java ================================================ package com.cwp.chart; import com.cwp.cmoneycharge.R; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; public class CustomMultiChoiceDialog extends Dialog { public CustomMultiChoiceDialog(Context context) { super(context); } public CustomMultiChoiceDialog(Context context, int theme) { super(context, theme); } public static class Builder { private Context context; private String title; private String message; private String positiveButtonText; private String negativeButtonText; private View contentView; private ListView listView; private DialogInterface.OnClickListener positiveButtonClickListener; private DialogInterface.OnClickListener negativeButtonClickListener; private OnItemClickListener onItemClickListener; private String[] items; private boolean[] checkedItems; private boolean showSelectAll; private static boolean isMultiChoice = false; public static String contact_name; public Builder(Context context) { this.context = context; } public Builder setMessage(String message) { this.message = message; return this; } public ListView getListView() { return listView; } public boolean[] getCheckedItems() { if (listView != null) { CheckAdapter adapter = (CheckAdapter) listView.getAdapter(); checkedItems = adapter.getCheckedItem(); } return checkedItems; } /** * Set the Dialog message from resource * * @param title * @return */ public Builder setMessage(int message) { this.message = (String) context.getText(message); return this; } /** * Set the Dialog title from resource * * @param title * @return */ public Builder setTitle(int title) { this.title = (String) context.getText(title); return this; } /** * Set the Dialog title from String * * @param title * @return */ public Builder setTitle(String title) { this.title = title; return this; } public Builder setContentView(View v) { this.contentView = v; return this; } /** * Set the positive button resource and it's listener * * @param positiveButtonText * @return */ public Builder setPositiveButton(int positiveButtonText, DialogInterface.OnClickListener listener) { this.positiveButtonText = (String) context .getText(positiveButtonText); this.positiveButtonClickListener = listener; return this; } public Builder setPositiveButton(String positiveButtonText, DialogInterface.OnClickListener listener) { this.positiveButtonText = positiveButtonText; this.positiveButtonClickListener = listener; return this; } public Builder setNegativeButton(int negativeButtonText, DialogInterface.OnClickListener listener) { this.negativeButtonText = (String) context .getText(negativeButtonText); this.negativeButtonClickListener = listener; return this; } public Builder setNegativeButton(String negativeButtonText, DialogInterface.OnClickListener listener) { this.negativeButtonText = negativeButtonText; this.negativeButtonClickListener = listener; return this; } /** * * * @param items * @param checkedItems * @param onItemClickListener * Listening the item click event. * @param showSelectAll * Whether to display the full checkbox. * @return */ public Builder setMultiChoiceItems(boolean isMultiChoice, String[] items, boolean[] checkedItems, OnItemClickListener onItemClickListener, boolean showSelectAll) { this.isMultiChoice = isMultiChoice; this.items = items; this.checkedItems = checkedItems; this.onItemClickListener = onItemClickListener; this.showSelectAll = showSelectAll; return this; } public CustomMultiChoiceDialog create() { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); // instantiate the dialog with the custom Theme final CustomMultiChoiceDialog dialog = new CustomMultiChoiceDialog( context, R.style.Dialog); View layout = inflater.inflate(R.layout.dialog_multichoice_layout, null); // set the dialog title TextView multichoicTitle = (TextView) layout .findViewById(R.id.multichoic_title); multichoicTitle.setText(title); ImageView checkAll = (ImageView) layout .findViewById(R.id.chk_selectall); LinearLayout dialog_bottom = (LinearLayout) layout .findViewById(R.id.dialog_bottom); Button positiveButton = (Button) layout .findViewById(R.id.positiveButton); Button negativeButton = (Button) layout .findViewById(R.id.negativeButton); listView = (ListView) layout.findViewById(R.id.multichoiceList); dialog.addContentView(layout, new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); // set the confirm button if (positiveButtonText != null) { positiveButton.setText(positiveButtonText); if (positiveButtonClickListener != null) { positiveButton .setOnClickListener(new View.OnClickListener() { public void onClick(View v) { positiveButtonClickListener.onClick(dialog, DialogInterface.BUTTON_POSITIVE); dialog.dismiss(); } }); } else { positiveButton .setOnClickListener(new View.OnClickListener() { public void onClick(View v) { dialog.dismiss(); } }); } } else { // if no confirm button just set the visibility to GONE positiveButton.setVisibility(View.GONE); dialog_bottom.setVisibility(View.GONE); } // set the cancel button if (negativeButtonText != null) { negativeButton.setText(negativeButtonText); if (negativeButtonClickListener != null) { negativeButton .setOnClickListener(new View.OnClickListener() { public void onClick(View v) { negativeButtonClickListener.onClick(dialog, DialogInterface.BUTTON_NEGATIVE); dialog.dismiss(); } }); } else { negativeButton .setOnClickListener(new View.OnClickListener() { public void onClick(View v) { dialog.dismiss(); } }); } } else { // if no confirm button just set the visibility to GONE negativeButton.setVisibility(View.GONE); } // is the Multichoice(澶氶?妗? if (isMultiChoice == true) { final CheckAdapter checkAdapter = new CheckAdapter(context, items, checkedItems); listView.setAdapter(checkAdapter); listView.setItemsCanFocus(true); if (onItemClickListener != null) { listView.setOnItemClickListener(onItemClickListener); } else { listView.setOnItemClickListener(new OnMultiItemClick()); } // show the all selectButton or not if (showSelectAll) { // checkAll.setVisibility( View.VISIBLE); // checkAll.setOnCheckedChangeListener(new // OnCheckedChangeListener() { // // @Override // public void onCheckedChanged(CompoundButton buttonView, // boolean isChecked) { // int count = listView.getAdapter().getCount(); // if (isChecked) { // // update the status of all checkbox to checked // if (count > 0) { // for (int i = 0; i < count; i++) { // CheckBox itemCheckBox = (CheckBox) listView // .getAdapter() // .getView(i, null, null) // .findViewById( // R.id.chk_selectone); // itemCheckBox.setChecked(true); // } // } // } else { // // update the status of checkbox to unchecked // if (count > 0) { // for (int i = 0; i < count; i++) { // CheckBox itemCheckBox = (CheckBox) listView // .getAdapter() // .getView(i, null, null) // .findViewById( // R.id.chk_selectone); // itemCheckBox.setChecked(false); // } // } // } // } // }); checkAll.setOnClickListener(new android.view.View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); } else { checkAll.setVisibility(View.GONE); } } else { // 如果是单选模式 final CheckAdapter checkAdapter = new CheckAdapter(context, items, checkedItems); listView.setAdapter(checkAdapter); listView.setItemsCanFocus(true); for (int i = 0; i < items.length; i++) { // 隐藏CheckBox CheckBox itemCheckBox = (CheckBox) listView.getAdapter() .getView(i, null, null) .findViewById(R.id.chk_selectone); itemCheckBox.setVisibility(View.GONE); } listView.setOnItemClickListener(onItemClickListener); // show the all selectButton or not if (showSelectAll) { checkAll.setOnClickListener(new android.view.View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); } else { checkAll.setVisibility(View.GONE); } } // set the content message if (message != null) { // ((TextView)layout.findViewById(R.id.message)).setText(message); } else if (contentView != null) { // if no message set add the contentView to the dialog body ((LinearLayout) layout.findViewById(R.id.content)) .removeAllViews(); ((LinearLayout) layout.findViewById(R.id.content)).addView( contentView, new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); } dialog.setContentView(layout); return dialog; } class OnMultiItemClick implements OnItemClickListener { @Override public void onItemClick(AdapterView parent, View view, int positon, long arg3) { CheckBox box = (CheckBox) view.findViewById(R.id.chk_selectone); if (box.isChecked()) { box.setChecked(false); } else { box.setChecked(true); } } } public static boolean getisMultiChoice() { return isMultiChoice; } public static String getcontact_name() { return contact_name; } } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/chart/FoldingLayout.java ================================================ /* * Copyright (C) 2013 Priboi Tiberiu * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cwp.chart; import android.content.Context; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; /** * The folding layout where the number of folds, the anchor point and the * orientation of the fold can be specified. Each of these parameters can be * modified individually and updates and resets the fold to a default (unfolded) * state. The fold factor varies between 0 (completely unfolded flat image) to * 1.0 (completely folded, non-visible image). * * This layout throws an exception if there is more than one child added to the * view. For more complicated view hierarchy's inside the folding layout, the * views should all be nested inside 1 parent layout. * * This layout folds the contents of its child in real time. By applying matrix * transformations when drawing to canvas, the contents of the child may change * as the fold takes place. It is important to note that there are jagged edges * about the perimeter of the layout as a result of applying transformations to * a rectangle. This can be avoided by having the child of this layout wrap its * content inside a 1 pixel transparent border. This will cause an anti-aliasing * like effect and smoothen out the edges. * */ public class FoldingLayout extends BaseFoldingLayout { private final String FOLDING_VIEW_EXCEPTION_MESSAGE = "Folding Layout can only 1 child at " + "most"; private GestureDetector mScrollGestureDetector; FoldingLayout that = null; private int mTranslation = 0; private int mParentPositionY = -1; private int mTouchSlop = -1; private boolean mDidNotStartScroll = true; public FoldingLayout(Context context) { super(context); init(context, null); that = this; } public FoldingLayout(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); that = this; } public FoldingLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context, attrs); that = this; } public void init(Context context, AttributeSet attrs) { mScrollGestureDetector = new GestureDetector(context, new ScrollGestureDetector()); mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); setAnchorFactor(0); super.init(context, attrs); } @Override protected boolean addViewInLayout(View child, int index, LayoutParams params, boolean preventRequestLayout) { throwCustomException(getChildCount()); boolean returnValue = super.addViewInLayout(child, index, params, preventRequestLayout); return returnValue; } /** * The custom exception to be thrown so as to limit the number of views in * this layout to at most one. */ private class NumberOfFoldingLayoutChildrenException extends RuntimeException { /** * */ private static final long serialVersionUID = 1L; public NumberOfFoldingLayoutChildrenException(String message) { super(message); } } /** * Throws an exception if the number of views added to this layout exceeds * one. */ private void throwCustomException(int numOfChildViews) { if (numOfChildViews == 1) { throw new NumberOfFoldingLayoutChildrenException( FOLDING_VIEW_EXCEPTION_MESSAGE); } } /** This class uses user touch events to fold and unfold the folding view. */ private class ScrollGestureDetector extends GestureDetector.SimpleOnGestureListener { @Override public boolean onDown(MotionEvent e) { mDidNotStartScroll = true; return true; } /** * All the logic here is used to determine by what factor the paper view * should be folded in response to the user's touch events. The logic * here uses vertical scrolling to fold a vertically oriented view and * horizontal scrolling to fold a horizontally oriented fold. Depending * on where the anchor point of the fold is, movements towards or away * from the anchor point will either fold or unfold the paper * respectively. * * The translation logic here also accounts for the touch slop when a * new user touch begins, but before a scroll event is first invoked. */ @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { int touchSlop = 0; float factor; if (mOrientation == Orientation.VERTICAL) { factor = Math.abs((float) (mTranslation) / (float) (that.getHeight())); if (e2.getY() - mParentPositionY <= that.getHeight() && e2.getY() - mParentPositionY >= 0) { if ((e2.getY() - mParentPositionY) > that.getHeight() * getAnchorFactor()) { mTranslation -= (int) distanceY; touchSlop = distanceY < 0 ? -mTouchSlop : mTouchSlop; } else { mTranslation += (int) distanceY; touchSlop = distanceY < 0 ? mTouchSlop : -mTouchSlop; } mTranslation = mDidNotStartScroll ? mTranslation + touchSlop : mTranslation; if (mTranslation < -that.getHeight()) { mTranslation = -that.getHeight(); } } } else { factor = Math.abs(((float) mTranslation) / ((float) that.getWidth())); if (e2.getRawX() > that.getWidth() * getAnchorFactor()) { mTranslation -= (int) distanceX; touchSlop = distanceX < 0 ? -mTouchSlop : mTouchSlop; } else { mTranslation += (int) distanceX; touchSlop = distanceX < 0 ? mTouchSlop : -mTouchSlop; } mTranslation = mDidNotStartScroll ? mTranslation + touchSlop : mTranslation; if (mTranslation < -that.getWidth()) { mTranslation = -that.getWidth(); } } mDidNotStartScroll = false; if (mTranslation > 0) { mTranslation = 0; } that.setFoldFactor(factor); return true; } } @Override public boolean onTouchEvent(MotionEvent me) { return mScrollGestureDetector.onTouchEvent(me); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/chart/MenuFragment.java ================================================ package com.cwp.chart; import com.cwp.cmoneycharge.PayChart; import com.cwp.cmoneycharge.PayData; import com.cwp.cmoneycharge.R; import android.annotation.TargetApi; import android.app.FragmentManager; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceFragment; import android.view.Window; import android.view.WindowManager; import android.widget.Toast; /** * menu fragment ,主要是用于显示menu菜单 * * @author Kris.lee * @since Mar 12, 2013 * @version 1.0.0 */ public class MenuFragment extends PreferenceFragment implements OnPreferenceClickListener { int index = -1; @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setRetainInstance(true); // set the preference xml to the content view addPreferencesFromResource(R.xml.menu); // add listener findPreference("mpaychart").setOnPreferenceClickListener(this); findPreference("mincomechart").setOnPreferenceClickListener(this); findPreference("dpaychart").setOnPreferenceClickListener(this); findPreference("dincomehart").setOnPreferenceClickListener(this); // findPreference("comparechart").setOnPreferenceClickListener(this); // findPreference("mincomechart").setOnPreferenceClickListener(this); SystemBarTintManager mTintManager; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { setTranslucentStatus(true); } mTintManager = new SystemBarTintManager(getActivity()); mTintManager.setStatusBarTintEnabled(true); mTintManager.setStatusBarTintResource(R.color.statusbar_bg); } @TargetApi(19) protected void setTranslucentStatus(boolean on) { Window win = getActivity().getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; if (on) { winParams.flags |= bits; } else { winParams.flags &= ~bits; } win.setAttributes(winParams); } @Override public boolean onPreferenceClick(Preference preference) { String key = preference.getKey(); if ("mpaychart".equals(key)) { Intent intentl = new Intent(getActivity(), PayChart.class); intentl.putExtra("datatype", "pay"); intentl.putExtra("type", 0); startActivity(intentl); } else if ("mincomechart".equals(key)) { Intent intentl = new Intent(getActivity(), PayChart.class); intentl.putExtra("datatype", "income"); intentl.putExtra("type", 0); startActivity(intentl); } else if ("dpaychart".equals(key)) { Intent intentp = new Intent(getActivity(), PayChart.class); intentp.putExtra("datatype", "pay"); intentp.putExtra("type", 1); startActivity(intentp); } else if ("dincomehart".equals(key)) { Intent intentp = new Intent(getActivity(), PayChart.class); intentp.putExtra("datatype", "income"); intentp.putExtra("type", 1); startActivity(intentp); } else if ("comparechart".equals(key)) { // Intent intentp = new Intent(getActivity(), PIData.class); // intent.putExtra("cwp.id", userid); // intentp.putExtra("datatype", "income"); // intentp.putExtra("type", 1); // startActivity(intentp); } // anyway , show the sliding menu // ((MainActivity) getActivity()).getSlidingMenu().toggle(); return false; } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/chart/MyAdspter.java ================================================ package com.cwp.chart; import java.util.List; import java.util.Map; import com.cwp.cmoneycharge.R; import android.R.bool; import android.content.Context; import android.graphics.Color; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; public class MyAdspter extends BaseAdapter { private List> data; private LayoutInflater layoutInflater; private Context context; private Boolean time; private String textaddress; public MyAdspter(Context context, List> data, Boolean time) { this.context = context; this.data = data; this.layoutInflater = LayoutInflater.from(context); this.time = time; } @Override public int getCount() { return data.size(); } /** * 获得某一位置的数据 */ @Override public Object getItem(int position) { return data.get(position); } /** * 获得唯一标识 */ @Override public long getItemId(int position) { return position; } /** * 组件集合,对应list.xml中的控件 * * @author Administrator */ public final class Zujian { public ImageView image; public TextView no; public TextView info; public TextView title; public TextView kind; public TextView money; public TextView address; public RelativeLayout titlebar; public TextView search_date; public TextView search_date2; public RelativeLayout search_img2; } @Override public View getView(int position, View convertView, ViewGroup parent) { Zujian zujian = null; if (convertView == null) { zujian = new Zujian(); // 获得组件,实例化组件 convertView = layoutInflater.inflate(R.layout.list, null); zujian.image = (ImageView) convertView .findViewById(R.id.search_img); zujian.no = (TextView) convertView.findViewById(R.id.no); zujian.info = (TextView) convertView.findViewById(R.id.info); zujian.title = (TextView) convertView.findViewById(R.id.title); zujian.kind = (TextView) convertView.findViewById(R.id.kind); zujian.money = (TextView) convertView.findViewById(R.id.money); zujian.address = (TextView) convertView.findViewById(R.id.address); zujian.search_date = (TextView) convertView .findViewById(R.id.search_date); zujian.search_date2 = (TextView) convertView .findViewById(R.id.search_date2); zujian.search_img2 = (RelativeLayout) convertView .findViewById(R.id.search_img2); zujian.titlebar = (RelativeLayout) convertView .findViewById(R.id.titlebar); convertView.setTag(zujian); } else { zujian = (Zujian) convertView.getTag(); } // 绑定数据 zujian.image.setBackgroundResource((Integer) data.get(position).get( "img")); zujian.no.setText((String) data.get(position).get("no")); zujian.title.setText((String) data.get(position).get("title")); zujian.kind.setText((String) data.get(position).get("kind")); zujian.money.setText((String) data.get(position).get("money")); if (data.get(position).get("date") != null) { zujian.search_img2.setVisibility(View.VISIBLE); zujian.search_date .setText(((String) data.get(position).get("info")) .substring(8, 10)); zujian.search_date2 .setText((String) data.get(position).get("date")); } if (data.get(position).get("kind").toString().equals("[收入]")) { zujian.money.setTextColor(Color.parseColor("#ffff0000")); } else { zujian.money.setTextColor(Color.parseColor("#5ea98d")); } if (time) { zujian.titlebar.setVisibility(View.VISIBLE); zujian.info.setText((String) data.get(position).get("info")); textaddress = (String) data.get(position).get("address"); if (textaddress.indexOf("[") > -1) { zujian.address.setText(textaddress.substring(0, textaddress.indexOf("["))); } else { zujian.address.setText(textaddress); } } else { zujian.titlebar.setVisibility(View.GONE); } return convertView; } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/chart/MyButton.java ================================================ package com.cwp.chart; import com.cwp.cmoneycharge.R; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Bitmap.Config; import android.graphics.Paint.FontMetrics; import android.text.style.BackgroundColorSpan; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; public class MyButton extends View implements View.OnTouchListener { private String text = ">"; private Paint backgroundPaint; private MyButtonClickListener listener; private Bitmap bitmap; private float width = 0; private float height = 0; public void setWidth(float width) { this.width = width; } public void setHeight(float height) { this.height = height; } public void setMyButtonClickListener(MyButtonClickListener listener) { this.listener = listener; } public void setBackgroundPaintColor(int color) { backgroundPaint.setColor(color); invalidate(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (width != 0) { width = (float) PiewController.measureWidth(widthMeasureSpec); } if (height != 0) { height = (float) PiewController.measureHeight(heightMeasureSpec); } setMeasuredDimension(100, 100); } @Override public void draw(Canvas canvas) { // TODO Auto-generated method stub super.draw(canvas); float Radius = getRadius(); bitmap = createBitmap(bitmap, Radius, Radius); Paint paint = new Paint(); paint.setColor(Color.WHITE); paint.setAntiAlias(true); canvas.drawCircle(Radius, Radius, Radius, paint); canvas.drawCircle(Radius, Radius, Radius * 4 / 5, backgroundPaint); paint.setTextAlign(Paint.Align.CENTER); paint.setTextSize(Radius * 5 / 3); canvas.drawText(text, (Radius+Radius * 1 / 10),(Radius+Radius * 1 / 2), paint); canvas.drawBitmap(bitmap, 0, 0, null); } public MyButton(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public MyButton(Context context, AttributeSet attrs) { super(context, attrs); init(); } public MyButton(Context context) { super(context); init(); } private void init() { this.setOnTouchListener(this); backgroundPaint = new Paint(); backgroundPaint.setAntiAlias(true); backgroundPaint.setColor(Color.RED); bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.common_btn_pressed); } private float getRadius() { int height = getHeight(); int width = getWidth(); if (height < width) { return height / 2; } return width / 2; } @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { // bitmap = BitmapFactory.decodeResource(getResources(), // R.drawable.common_shine_btn_bg); invalidate(); } if (event.getAction() == MotionEvent.ACTION_UP) { // bitmap = BitmapFactory.decodeResource(getResources(), // R.drawable.common_btn_pressed); invalidate(); if (listener != null) { listener.onclick(); } } return true; } public Bitmap createBitmap(Bitmap b, float x, float y) { int w = b.getWidth(); int h = b.getHeight(); float sx = (float) x / w; float sy = (float) y / h; Matrix matrix = new Matrix(); matrix.postScale(sx, sy); Bitmap resizeBmp = Bitmap.createBitmap(b, 0, 0, w, h, matrix, true); return resizeBmp; } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/chart/MyButtonClickListener.java ================================================ package com.cwp.chart; public interface MyButtonClickListener { public void onclick(); } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/chart/OnFoldListener.java ================================================ /* * Copyright (C) 2013 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cwp.chart; /** * This interface listens for when the folding layout begins folding (enters * a folded state from a completely unfolded state), or ends folding (enters a * completely unfolded state from a folded state). */ public interface OnFoldListener { public void onStartFold(float foldFactor); public void onFoldingState(float foldFactor, float foldDrawHeight); public void onEndFold(float foldFactor); } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/chart/PieChart.java ================================================ package com.cwp.chart; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.view.View.MeasureSpec; import android.view.ViewGroup; import android.widget.Button; import android.widget.FrameLayout; import android.widget.TextView; public class PieChart extends ViewGroup { public PieChart(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public PieChart(Context context, AttributeSet attrs) { super(context, attrs); init(); } public PieChart(Context context) { super(context); init(); } private void init() { } private int m_measureWidth = 0; private int m_measureHeight = 0; /** * 计算控件的大尿 */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); m_measureWidth = PiewController.measureWidth(widthMeasureSpec); Log.e("caizh", "m_measureWidth=" + m_measureWidth); m_measureHeight = PiewController.measureHeight(heightMeasureSpec); // 计算自定义的ViewGroup中所有子控件的大尿 measureChildren(widthMeasureSpec, heightMeasureSpec); // 设置自定义的控件MyViewGroup的大尿 setMeasuredDimension(m_measureWidth, m_measureHeight); } /** * 覆写onLayout,其目的是为了指定视图的显示位置,方法执行的前后顺序是在onMeasure之后,因为视图肯定是只有知道大小的情况下_ * 才能确定怎么摆放 */ @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { // 记录总高庿 Log.e("caizh", "l=" + l); // 遍历承?子视囿 int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View childView = getChildAt(i); // 获取在onMeasure中计算的视图尺寸 int measureHeight = childView.getMeasuredHeight(); int measuredWidth = childView.getMeasuredWidth(); if (childView.getTag().equals("pieButton")) { childView.layout( (m_measureWidth * 6 / 7 - m_measureWidth / 25), (int) ((m_measureWidth * 19 / 16)) - m_measureWidth / 25, (m_measureWidth * 6 / 7 + m_measureWidth / 25), (int) ((m_measureWidth * 19 / 16)) + m_measureWidth / 25); } else if (childView.getTag().equals("pieText")) { TextView textView = (TextView) childView; if (m_measureWidth == 680) { textView.setTextSize(m_measureWidth / 30); } else if (m_measureWidth == 1020) { textView.setTextSize(m_measureWidth / 40); } else { textView.setTextSize(m_measureWidth / 30); } childView.layout((int) ((m_measureWidth - measuredWidth) / 2), (int) ((m_measureWidth * 19 / 16)) - measureHeight / 2, (int) ((m_measureWidth + measuredWidth) / 2), (int) ((m_measureWidth * 19 / 16)) + measureHeight / 2); } else { // Log.e("caizh", "measuredWidth=" + measuredWidth); childView.layout(0, 0, measuredWidth, measureHeight); } } } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/chart/PieView.java ================================================ package com.cwp.chart; import java.util.ArrayList; import com.cwp.cmoneycharge.PayChart; import com.cwp.cmoneycharge.R; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Point; import android.graphics.RectF; import android.graphics.Paint; import android.graphics.Paint.FontMetrics; import android.os.Handler; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.View.MeasureSpec; public class PieView extends View implements View.OnTouchListener, Runnable { private float m_x = 0; private float m_y = 0; private static ArrayList mChartProps; private float screenHight, screenWidth;// 屏幕的宽和高 private float radius;// 绘制圆的半径 private float startAngle;// 弿?角度 private float sweepAngle = 0.0f; // 扫过的角庿 private int itemCount;// 选项个数 private float startSpeed = 0; private boolean firstEnter = true; // 程序是否已经逿? private boolean rotateEnabled = false; private boolean tounched = false; private boolean done = false; private Paint mPaint; private Paint textPaint; private Canvas mCanvas; private ChartPropChangeListener listener; private static ChartProp mChartProp = null; private static ChartProp tChartProp = null; private static float[] percents; private Point centerPoint; private Bitmap myBg; private String amount; private Thread myThread; public void setBackgroundPaintColor(int color) { invalidate(); } private void writeLog(String string) { Log.e("caizh", string); } public void destory() { // myBg.recycle(); done = true; } @Override public void draw(Canvas canvas) { // TODO Auto-generated method stub super.draw(canvas); if (firstEnter) { firstInit(); } else { if (!tounched) { float middleAngle = ((mChartProp.getEndAngle() + mChartProp .getStartAngle()) / 2); float distance = (middleAngle - getBorderAngle()); startAngle -= (distance / 2); // startAngle=() } } mCanvas = canvas; float f1 = centerPoint.x; float f2 = centerPoint.y; // 填充背景艿 /* * mCanvas.drawColor(0xff639EC3); mCanvas.save(); */ // *********************************确定参逥?域************************************* float f3 = f1 - radius;// X轿- 巿 float f4 = f2 - radius; // Y轿- 丿 float f5 = f1 + radius; // X轿- 叿 float f6 = f2 + radius; // Y轿- 丿 RectF rectF = new RectF(f3, f4, f5, f6); // *********************************画每个区域的颜色坿******************************** drawItem(rectF); // *********************************画边上渐变的圆环出来******************************* drawableCenterCircle(f1, f2); // 解锁Canvas,并渲染当前图像 if (!(mChartProp == tChartProp)) { listener.getChartProp(mChartProp); tChartProp = mChartProp; } } public PieView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public PieView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public PieView(Context context) { super(context); init(); } private void init() { myThread = new Thread(this); // 创建丿?新的SurfaceHolder_并分配这个类作为它的回调(callback) mChartProps = new ArrayList(); // 图像画笔 mPaint = new Paint(); mPaint.setAntiAlias(true); // 文字画笔 textPaint = new Paint(); textPaint.setTextSize(22); textPaint.setColor(Color.WHITE); textPaint.setAntiAlias(true); // 半径 startAngle = 90f; myBg = BitmapFactory.decodeResource(getResources(), R.drawable.mask_piechartformymoney); this.setOnTouchListener(this); } public void start() { myThread.start(); } @Override public void run() { while (!done) { try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (rotateEnabled) { postInvalidate(); } } } private Bitmap createBitmap(Bitmap b, float x, float y) { int w = b.getWidth(); int h = b.getHeight(); float sx = (float) x / w; float sy = (float) y / h; Matrix matrix = new Matrix(); matrix.postScale(sx, sy); Bitmap resizeBmp = Bitmap.createBitmap(b, 0, 0, w, h, matrix, true); return resizeBmp; } /** * create charts' property 创建饼状图的属濍 * * @param chartsNum * charts' number 饼状图的个数 * @return charts' property's list 饼状图属性的list */ public ArrayList createCharts(int itemCount) { this.itemCount = itemCount; percents = new float[itemCount]; mChartProps.clear(); createChartProp(itemCount); return mChartProps; } // 重新初始匿 public void reInit() { startAngle = 90f; firstEnter = true; // 程序是否已经逿? } // 第一次参数进行改变后的初始化调用 public void initPercents() { for (int i = 0; i < itemCount; i++) { percents[i] = mChartProps.get(i).getPercent(); mChartProps.get(i).setPercent(0.01f); } } public void setChartPropChangeListener(ChartPropChangeListener listener) { this.listener = listener; } /** * actually create chartProp objects. 真正创建扇形属瀧?方泿 * * @param chartsNum * charts' number 饼状图的个数 */ private void createChartProp(int chartsNum) { for (int i = 0; i < chartsNum; i++) { ChartProp chartProp = new ChartProp(this); chartProp.setId(i); mChartProps.add(chartProp); } } public ChartProp createNullChartProp() { mChartProps.clear(); ChartProp chartProp = new ChartProp(this); mChartProps.add(chartProp); return chartProp; } private void initResoure() { float y = myBg.getHeight(); float x = myBg.getWidth(); float r; if (screenHight > screenWidth) { r = screenWidth; myBg = createBitmap(myBg, screenWidth, (screenWidth * y) / x); } else { r = screenHight; myBg = createBitmap(myBg, screenHight, (screenHight * y) / x); } centerPoint = new Point(); centerPoint.x = (int) (r / 2); centerPoint.y = (int) ((r * 19) / 32); radius = (centerPoint.x * 0.8843f); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // 高度 screenHight = (float) PiewController.measureWidth(heightMeasureSpec); screenWidth = (float) PiewController.measureHeight(widthMeasureSpec); Log.e("caizh", "screenWidth01=" + screenWidth); initResoure(); setMeasuredDimension((int) screenWidth, (int) screenHight); } private int measureWidth(int pWidthMeasureSpec) { int result = 0; int widthMode = MeasureSpec.getMode(pWidthMeasureSpec);// 得到模式 int widthSize = MeasureSpec.getSize(pWidthMeasureSpec);// 得到尺寸 switch (widthMode) { /** * mode共有三种情况,取值分别为MeasureSpec.UNSPECIFIED, MeasureSpec.EXACTLY, * MeasureSpec.AT_MOST? * * * MeasureSpec.EXACTLY是精确尺寸, * 当我们将控件的layout_width或layout_height指定为具体数值时如andorid * :layout_width="50dip",或者为FILL_PARENT是,都是控件大小已经确定的情况,都是精确尺寸? * * * MeasureSpec.AT_MOST是最大尺寸, * 当控件的layout_width或layout_height指定为WRAP_CONTENT旿 * ,控件大小一般随睿Χ件的子空间或内容进行变化,此时控件尺寸只要不超过父控件允许的朿?尺寸即可 * 。因此,此时的mode是AT_MOST,size给出了父控件允许的最大尺寸? * * * MeasureSpec.UNSPECIFIED是未指定尺寸,这种情况不多,丿?都是父控件是AdapterView_ * 通过measure方法传入的模式? */ case MeasureSpec.AT_MOST: case MeasureSpec.EXACTLY: result = widthSize; break; } return result; } private int measureHeight(int pHeightMeasureSpec) { int result = 0; int heightMode = MeasureSpec.getMode(pHeightMeasureSpec); int heightSize = MeasureSpec.getSize(pHeightMeasureSpec); switch (heightMode) { case MeasureSpec.AT_MOST: case MeasureSpec.EXACTLY: result = heightSize; break; } return result; } private void firstInit() { startSpeed += 0.05f; if (startSpeed >= 1) { startSpeed = 0.9f; } float total = 0f; if (!mChartProps.isEmpty()) { for (int i = 0; i < itemCount; i++) { if (i < mChartProps.size()) { float percent = mChartProps.get(i).getPercent(); // writeLog("percent="+percent); float distancePercent = (percents[i] - percent); if (distancePercent < 0.0001) { mChartProps.get(i).setPercent(percents[i]); } else { mChartProps.get(i).setPercent( percent + (distancePercent * startSpeed)); } total = total + mChartProps.get(i).getPercent(); } } } if (total >= 1) { firstEnter = false; } } public void getCurrentChartProp(ChartProp chartProp, float f) { if ((chartProp.getStartAngle() <= f) && (chartProp.getEndAngle() > f)) { mChartProp = chartProp; } } public void drawableCenterCircle(float x, float y) { /* * Paint centerCirclePaint = new Paint(); * centerCirclePaint.setColor(Color.BLACK); * * centerCirclePaint.setAlpha(150); mCanvas.drawCircle(x, y, radius / 3, * centerCirclePaint); */ // Paint localPaint = new Paint(); // 设置取消锯齿效果 // localPaint.setAntiAlias(true); // 风格为圆玿 /* * localPaint.setStyle(Paint.Style.STROKE); // 圆环宽度 * localPaint.setStrokeWidth(circleRadius); */ // 圆环背景 mCanvas.drawBitmap(myBg, 0, 0, null); mCanvas.save(); textPaint.setColor(Color.WHITE); textPaint.setTextAlign(Paint.Align.CENTER); textPaint.setTextSize(x / 10); mCanvas.drawText("总计", x, y - x / 12, textPaint); mCanvas.drawText(PayChart.getamount(), x, y + x / 10, textPaint); // 总计 mCanvas.save(); } private float getBorderAngle() { float borderAngle; int circleCount = 0; if (startAngle >= 0) { circleCount = (int) (startAngle / 360); if ((startAngle % 360) > (90)) { borderAngle = (float) (90 + 360 * (circleCount + 1)); } else { borderAngle = (float) (90 + 360 * circleCount); } } else { circleCount = (int) (startAngle / 360); if ((startAngle % 360) < (-270)) { borderAngle = (float) (90 + 360 * (circleCount - 1)); } else { borderAngle = (float) (90 + 360 * circleCount); } } return borderAngle; } public ChartProp getCurrentChartProp() { if (mChartProp != null) { return mChartProp; } float temp = startAngle; float borderAngle = getBorderAngle(); for (int i = 0; i < itemCount; i++) { sweepAngle = mChartProps.get(i).getSweepAngle(); mChartProps.get(i).setStartAngle(temp); temp += sweepAngle; mChartProps.get(i).setEndAngle(temp); getCurrentChartProp(mChartProps.get(i), borderAngle); } return mChartProp; } // *********************************画每个扇彿******************************** public void drawItem(RectF localRectf) { float temp = startAngle; float borderAngle = getBorderAngle(); // System.out.println("itemCount" + itemCount); if (!mChartProps.isEmpty()) { if (itemCount > 0) { for (int i = 0; i < itemCount; i++) { if (i < mChartProps.size()) { mPaint.setColor(mChartProps.get(i).getColor()); // startAngle为每次移动的角度大小 sweepAngle = mChartProps.get(i).getSweepAngle(); mChartProps.get(i).setStartAngle(temp); /* * oval:圆弧所在的椭圆对象?startAngle:圆弧的起始角度。sweepAngle:圆弧的角度? * useCenter: * 是否显示半径连线,true表示显示圆弧与圆心的半径连线,false表示不显示?paint * :绘制时承?用的画笔 */ mCanvas.drawArc(localRectf, temp, sweepAngle, true, mPaint); // mCanvas.drawText(localRectf, temp, sweepAngle, // mChartProps.get(i).getName()); mCanvas.save(); temp += sweepAngle; mChartProps.get(i).setEndAngle(temp); getCurrentChartProp(mChartProps.get(i), borderAngle); } } } } } public boolean isRotateEnabled() { return rotateEnabled; } public void setRotateEnabled(boolean rotateEnabled) { this.rotateEnabled = rotateEnabled; } public void rotateEnable() { rotateEnabled = true; } public void rotateDisable() { rotateEnabled = false; } @Override public boolean onTouch(View v, MotionEvent event) { boolean enable = true; float x = centerPoint.x; float y = centerPoint.y; float y1 = event.getY(); float x1 = event.getX(); float x2 = v.getLeft(); float y2 = v.getTop(); float x3 = x1 - x2; float y3 = y1 - y2; if (event.getAction() == MotionEvent.ACTION_DOWN) { m_x = x3; m_y = y3; tounched = true; } if (event.getAction() == MotionEvent.ACTION_UP) { m_x = 0; m_y = 0; tounched = false; } float d = (float) Math.sqrt((Math.pow(Math.abs((x - x3)), 2) + Math .pow(Math.abs((y - y3)), 2))); if (d > radius) { m_x = 0; m_y = 0; enable = false; } if (event.getAction() == MotionEvent.ACTION_MOVE) { if ((m_x == 0) && (m_y == 0)) { enable = false; } if (enable) { float c = (float) Math .sqrt((Math.pow(Math.abs((m_x - x3)), 2) + Math.pow( Math.abs((m_y - y3)), 2))); float a = (float) Math .sqrt((Math.pow(Math.abs(m_x - x), 2) + Math.pow( Math.abs((m_y - y)), 2))); float b = (float) Math .sqrt((Math.pow(Math.abs(x3 - x), 2) + Math.pow( Math.abs((y3 - y)), 2))); float cosc = (float) (Math.pow(a, 2) + Math.pow(b, 2) - Math .pow(c, 2)) / (2 * a * b); float m_angle = getAngle((m_x - x), (m_y - y)); float angle3 = getAngle((x3 - x), (y3 - y)); if ((90 > m_angle) && (angle3 > 270)) { m_angle = m_angle + (float) 360; } if ((90 > angle3) && (m_angle > 270)) { angle3 = angle3 + (float) 360; } if (angle3 - m_angle > 0) { startAngle = (float) (startAngle + Math.acos(cosc) * 180 / Math.PI); } else { startAngle = (float) (startAngle - Math.acos(cosc) * 180 / Math.PI); } m_x = x3; m_y = y3; } } return true; } private float getAngle(float x, float y) { if ((x == 0) && (y == 0)) { return 0; } float angle = (float) (Math.atan(y / x) * 180 / Math.PI); if (x == 0) { if (y > 0) { return 90; } else { return 270; } } if (x > 0) { if (y < 0) { return (float) 360 + angle; } } if (x < 0) { if (y > 0) { return (float) 180 + angle; } else if (y == 0) { return 180; } else if (y < 0) { return (float) 180 + angle; } } return angle; } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/chart/PiewController.java ================================================ package com.cwp.chart; import android.view.View; import android.view.View.MeasureSpec; import android.view.ViewGroup.MarginLayoutParams; import android.widget.FrameLayout; import android.widget.RelativeLayout; public class PiewController { /* * 获取控件宿 */ public static int getWidth(View view) { int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); view.measure(w, h); return (view.getMeasuredWidth()); } /* * 获取控件髿 */ public static int getHeight(View view) { int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); int h = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); view.measure(w, h); return (view.getMeasuredHeight()); } /* * 设置控件承?的位置X,并且不改变宽高_X为绝对位置,此时Y可能彿 */ public static void setLayoutX(View view, int x) { MarginLayoutParams margin = new MarginLayoutParams( view.getLayoutParams()); margin.setMargins(x, margin.topMargin, x + margin.width, margin.bottomMargin); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams( margin); view.setLayoutParams(layoutParams); } /* * 设置控件承?的位置Y,并且不改变宽高_Y为绝对位置,此时X可能彿 */ public static void setLayoutY(View view, int y) { MarginLayoutParams margin = new MarginLayoutParams( view.getLayoutParams()); margin.setMargins(margin.leftMargin, y, margin.rightMargin, y + margin.height); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams( margin); view.setLayoutParams(layoutParams); } /* * 设置控件承?的位置YY,并且不改变宽高_XY为绝对位罿 */ public static void setLayout(View view, int x, int y) { MarginLayoutParams margin = new MarginLayoutParams( view.getLayoutParams()); margin.setMargins(x, y, x + margin.width, y + margin.height); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams( margin); view.setLayoutParams(layoutParams); } public static int measureWidth(int pWidthMeasureSpec) { int result = 0; int widthMode = MeasureSpec.getMode(pWidthMeasureSpec);// 得到模式 int widthSize = MeasureSpec.getSize(pWidthMeasureSpec);// 得到尺寸 switch (widthMode) { /** * mode共有三种情况,取值分别为MeasureSpec.UNSPECIFIED, MeasureSpec.EXACTLY, * MeasureSpec.AT_MOST? * * * MeasureSpec.EXACTLY是精确尺寸, * 当我们将控件的layout_width或layout_height指定为具体数值时如andorid * :layout_width="50dip",或者为FILL_PARENT是,都是控件大小已经确定的情况,都是精确尺寸? * * * MeasureSpec.AT_MOST是最大尺寸, * 当控件的layout_width或layout_height指定为WRAP_CONTENT旿 * ,控件大小一般随睿Χ件的子空间或内容进行变化,此时控件尺寸只要不超过父控件允许的朿?尺寸即可 * 。因此,此时的mode是AT_MOST,size给出了父控件允许的最大尺寸? * * * MeasureSpec.UNSPECIFIED是未指定尺寸,这种情况不多,丿?都是父控件是AdapterView_ * 通过measure方法传入的模式? */ case MeasureSpec.AT_MOST: case MeasureSpec.EXACTLY: result = widthSize; break; } return result; } public static int measureHeight(int pHeightMeasureSpec) { int result = 0; int heightMode = MeasureSpec.getMode(pHeightMeasureSpec); int heightSize = MeasureSpec.getSize(pHeightMeasureSpec); switch (heightMode) { case MeasureSpec.AT_MOST: case MeasureSpec.EXACTLY: result = heightSize; break; } return result; } public static void mySetMargins(View view, int left, int top, int right, int bottom) { FrameLayout.LayoutParams layoutParam = (FrameLayout.LayoutParams) view .getLayoutParams(); layoutParam.setMargins(left, top, right, bottom); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/chart/PullToRefreshView.java ================================================ package com.cwp.chart; import java.util.Date; import com.cwp.cmoneycharge.FragmentPage3; import com.cwp.cmoneycharge.R; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.ScrollView; import android.widget.TextView; /** * @description自定义容器,盛放listview,gridview,scrollview * @author 袁东卿 * @date 2014-7-21 下午5:56:00 */ public class PullToRefreshView extends LinearLayout { private static final String TAG = "PullToRefreshView"; // 刷新状濍 private static final int PULL_TO_REFRESH = 2; private static final int RELEASE_TO_REFRESH = 3; private static final int REFRESHING = 4; // 拉动状濍 private static final int PULL_UP_STATE = 0; private static final int PULL_DOWN_STATE = 1; private boolean enablePullTorefresh = true; private boolean enablePullLoadMoreDataStatus = true; private int mLastMotionY; private boolean mLock; /** * 头部view */ private View mHeaderView; /** * 底部view */ private View mFooterView; private AdapterView mAdapterView; private ScrollView mScrollView; /** * 头部view的高 */ private int mHeaderViewHeight; /** * 底部view的高 */ private int mFooterViewHeight; /** * 头部箭头 */ private ImageView mHeaderImageView; /** * 底部箭头 */ private ImageView mFooterImageView; /** * 头部文字 */ private TextView mHeaderTextView; /** * 底部文字 */ private TextView mFooterTextView; /** * 头部刷新时间 */ private TextView mHeaderUpdateTextView; /** * 底部刷新时间 */ private TextView mFooterUpdateTextView; /** * 头部进度板 */ private ProgressBar mHeaderProgressBar; /** * 底部进度板 */ private ProgressBar mFooterProgressBar; /** * layout inflater */ private LayoutInflater mInflater; /** * 头部view的当前状怿 */ private int mHeaderState; /** * 底部view的当前状怿 */ private int mFooterState; /** * 拉动状濍 */ private int mPullState; /** * 变为向下的箭夿改变箭头方向 */ private RotateAnimation mFlipAnimation; /** * 变为逆向的箭夿旋转 */ private RotateAnimation mReverseFlipAnimation; /** * 底部view的刷新监吿 */ private OnFooterRefreshListener mOnFooterRefreshListener; /** * 头部view的刷新监吿 */ private OnHeaderRefreshListener mOnHeaderRefreshListener; /** * 朿?更新时间 */ private String mLastUpdateTime; public PullToRefreshView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public PullToRefreshView(Context context) { super(context); init(); } private void init() { // Load all of the animations we need in code rather than through XML mFlipAnimation = new RotateAnimation(0, -180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); mFlipAnimation.setInterpolator(new LinearInterpolator()); mFlipAnimation.setDuration(250); mFlipAnimation.setFillAfter(true); mReverseFlipAnimation = new RotateAnimation(-180, 0, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); mReverseFlipAnimation.setInterpolator(new LinearInterpolator()); mReverseFlipAnimation.setDuration(250); mReverseFlipAnimation.setFillAfter(true); mInflater = LayoutInflater.from(getContext()); // header view 在此添加,保证是第丿?添加到linearlayout的最上端 addHeaderView(); } private void addHeaderView() { // header view mHeaderView = mInflater.inflate(R.layout.refresh_header, this, false); mHeaderImageView = (ImageView) mHeaderView .findViewById(R.id.pull_to_refresh_image); mHeaderTextView = (TextView) mHeaderView .findViewById(R.id.pull_to_refresh_text); mHeaderUpdateTextView = (TextView) mHeaderView .findViewById(R.id.pull_to_refresh_updated_at); // mHeaderProgressBar = (ProgressBar) mHeaderView // .findViewById(R.id.pull_to_refresh_progress); // header layout measureView(mHeaderView); mHeaderViewHeight = mHeaderView.getMeasuredHeight(); LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, mHeaderViewHeight); // 设置topMargin的怤?负的header View高度,即将其隐藏在朿?斿 params.topMargin = -(mHeaderViewHeight); // mHeaderView.setLayoutParams(params1); addView(mHeaderView, params); } private void addFooterView() { // footer view mFooterView = mInflater.inflate(R.layout.refresh_footer, this, false); mFooterImageView = (ImageView) mFooterView .findViewById(R.id.pull_to_load_image); mFooterTextView = (TextView) mFooterView .findViewById(R.id.pull_to_load_text); // mFooterProgressBar = (ProgressBar) mFooterView // .findViewById(R.id.pull_to_load_progress); // footer layout measureView(mFooterView); mFooterViewHeight = mFooterView.getMeasuredHeight(); LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, mFooterViewHeight); // int top = getHeight(); // params.topMargin // =getHeight();//在这里getHeight()==0,但在onInterceptTouchEvent()方法里getHeight()已经有怤?不再昿; // getHeight()仿?时怤?赋倿稍急?研究一丿 // 由于是线性布屿?以直接添势只要AdapterView的高度是MATCH_PARENT,那么footer view就会被添加到朿?,并隐藿 addView(mFooterView, params); } @Override protected void onFinishInflate() { super.onFinishInflate(); // footer view 在此添加保证添加到linearlayout中的朿? addFooterView(); initContentAdapterView(); } private void initContentAdapterView() { int count = getChildCount(); if (count < 3) { Log.e(TAG, "子view的个数小亿----------------"); } View view = null; for (int i = 0; i < count - 1; ++i) { view = getChildAt(i); if (view instanceof AdapterView) { mAdapterView = (AdapterView) view; } if (view instanceof ScrollView) { // finish later mScrollView = (ScrollView) view; } } if (mAdapterView == null && mScrollView == null) { Log.e(TAG, "view为空-------------------"); } } private void measureView(View child) { ViewGroup.LayoutParams p = child.getLayoutParams(); if (p == null) { p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width); int lpHeight = p.height; int childHeightSpec; if (lpHeight > 0) { childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); } else { childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } child.measure(childWidthSpec, childHeightSpec); } @Override public boolean onInterceptTouchEvent(MotionEvent e) { int y = (int) e.getRawY(); switch (e.getAction()) { case MotionEvent.ACTION_DOWN: // 首先拦截down事件,记录y坐标 mLastMotionY = y; break; case MotionEvent.ACTION_MOVE: // deltaY > 0 是向下运势< 0是向上运势 int deltaY = y - mLastMotionY; if (isRefreshViewScroll(deltaY)) { return true; } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: break; } return false; } /* * 如果在onInterceptTouchEvent()方法中没有拦房即onInterceptTouchEvent()方法丿return * false)则由PullToRefreshView 的子View来处琿否则由下面的方法来处琿即由PullToRefreshView自己来处琿 */ @Override public boolean onTouchEvent(MotionEvent event) { if (mLock) { return true; } int y = (int) event.getRawY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // onInterceptTouchEvent已经记录 // mLastMotionY = y; break; case MotionEvent.ACTION_MOVE: int deltaY = y - mLastMotionY; if (mPullState == PULL_DOWN_STATE) { // PullToRefreshView执行下拉 // Log.i(TAG, " pull down!parent view move!"); headerPrepareToRefresh(deltaY); // setHeaderPadding(-mHeaderViewHeight); } else if (mPullState == PULL_UP_STATE) { // PullToRefreshView执行上拉 // Log.i(TAG, "pull up!parent view move!"); footerPrepareToRefresh(deltaY); } mLastMotionY = y; break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: int topMargin = getHeaderTopMargin(); if (mPullState == PULL_DOWN_STATE) { if (topMargin >= 0) { // 弿?刷新 headerRefreshing(); } else { // 还没有执行刷新,重新隐藏 setHeaderTopMargin(-mHeaderViewHeight); } } else if (mPullState == PULL_UP_STATE) { if (Math.abs(topMargin) >= mHeaderViewHeight + mFooterViewHeight) { // 弿?执行footer 刷新 footerRefreshing(); } else { // 还没有执行刷新,重新隐藏 setHeaderTopMargin(-mHeaderViewHeight); } } break; } return super.onTouchEvent(event); } /** * 是否应该到了父View,即PullToRefreshView滑动 * * @param deltaY * , deltaY > 0 是向下运势< 0是向上运势 * @return */ private boolean isRefreshViewScroll(int deltaY) { if (mHeaderState == REFRESHING || mFooterState == REFRESHING) { return false; } // 对于ListView和GridView if (mAdapterView != null) { // 子view(ListView or GridView)滑动到最顶端 if (deltaY > 0) { // 判断是否禁用下拉刷新操作 if (!enablePullTorefresh) { return false; } View child = mAdapterView.getChildAt(0); if (child == null) { // 如果mAdapterView中没有数捿不拦房 return false; } if (mAdapterView.getFirstVisiblePosition() == 0 && child.getTop() == 0) { mPullState = PULL_DOWN_STATE; return true; } int top = child.getTop(); int padding = mAdapterView.getPaddingTop(); if (mAdapterView.getFirstVisiblePosition() == 0 && Math.abs(top - padding) <= 11) {// 这里之前甿可以判断,但现在不衿还没找到原因 mPullState = PULL_DOWN_STATE; return true; } } else if (deltaY < 0) { // 判断是否禁用上拉加载更多操作 if (!enablePullLoadMoreDataStatus) { return false; } View lastChild = mAdapterView.getChildAt(mAdapterView .getChildCount() - 1); if (lastChild == null) { // 如果mAdapterView中没有数捿不拦房 return false; } // 朿?丿?子view的Bottom小于父View的高度说明mAdapterView的数据没有填满父view, // 等于父View的高度说明mAdapterView已经滑动到最吿 if (lastChild.getBottom() <= getHeight() && mAdapterView.getLastVisiblePosition() == mAdapterView .getCount() - 1) { mPullState = PULL_UP_STATE; return true; } } } // 对于ScrollView if (mScrollView != null) { // 子scroll view滑动到最顶端 View child = mScrollView.getChildAt(0); if (deltaY > 0 && mScrollView.getScrollY() == 0) { mPullState = PULL_DOWN_STATE; return true; } else if (deltaY < 0 && child.getMeasuredHeight() <= getHeight() + mScrollView.getScrollY()) { mPullState = PULL_UP_STATE; return true; } } return false; } /** * header 准备刷新,手指移动过程,还没有释政 * * @param deltaY * ,手指滑动的距禿 */ private void headerPrepareToRefresh(int deltaY) { int newTopMargin = changingHeaderViewTopMargin(deltaY); // 当header view的topMargin>=0时,说明已经完全显示出来亿修改header view 的提示状怿 if (newTopMargin >= 0 && mHeaderState != RELEASE_TO_REFRESH) { mHeaderTextView.setText("放开切换到" + Integer.toString(FragmentPage3.getyear() + 1) + "年流水"); mHeaderUpdateTextView.setVisibility(View.VISIBLE); mHeaderImageView.clearAnimation(); mHeaderImageView.startAnimation(mFlipAnimation); mHeaderState = RELEASE_TO_REFRESH; } else if (newTopMargin < 0 && newTopMargin > -mHeaderViewHeight) {// 拖动时没有释政 mHeaderImageView.clearAnimation(); mHeaderImageView.startAnimation(mFlipAnimation); // mHeaderImageView. mHeaderTextView.setText("下拉切换到" + Integer.toString(FragmentPage3.getyear() + 1) + "年流水"); mHeaderState = PULL_TO_REFRESH; } } /** * footer 准备刷新,手指移动过程,还没有释政移动footer view高度同样和移动header view * 高度是一样,都是通过修改header view的topmargin的怦?达刿 * * @param deltaY * ,手指滑动的距禿 */ private void footerPrepareToRefresh(int deltaY) { int newTopMargin = changingHeaderViewTopMargin(deltaY); // 如果header view topMargin 的绝对急?于或等于header + footer 的高庿 // 说明footer view 完全显示出来了,修改footer view 的提示状怿 if (Math.abs(newTopMargin) >= (mHeaderViewHeight + mFooterViewHeight) && mFooterState != RELEASE_TO_REFRESH) { mFooterTextView.setText("放开切换到" + Integer.toString(FragmentPage3.getyear() - 1) + "年流水"); mFooterImageView.clearAnimation(); mFooterImageView.startAnimation(mFlipAnimation); mFooterState = RELEASE_TO_REFRESH; } else if (Math.abs(newTopMargin) < (mHeaderViewHeight + mFooterViewHeight)) { mFooterImageView.clearAnimation(); mFooterImageView.startAnimation(mFlipAnimation); mFooterTextView.setText("上拉切换到" + Integer.toString(FragmentPage3.getyear() - 1) + "年流水"); mFooterState = PULL_TO_REFRESH; } } private int changingHeaderViewTopMargin(int deltaY) { LayoutParams params = (LayoutParams) mHeaderView.getLayoutParams(); float newTopMargin = params.topMargin + deltaY * 0.3f; // 这里对上拉做丿?限制,因为当前上拉后然后不释放手指直接下拉,会把下拉刷新给触发了,感谢网友yufengzungzhe的指凿 // 表示如果是在上拉后一段距禿然后直接下拉 if (deltaY > 0 && mPullState == PULL_UP_STATE && Math.abs(params.topMargin) <= mHeaderViewHeight) { return params.topMargin; } // 同样圿对下拉做丿?限制,避免出现跟上拉操作时丿7的bug if (deltaY < 0 && mPullState == PULL_DOWN_STATE && Math.abs(params.topMargin) >= mHeaderViewHeight) { return params.topMargin; } params.topMargin = (int) newTopMargin; mHeaderView.setLayoutParams(params); invalidate(); return params.topMargin; } public void headerRefreshing() { mHeaderState = REFRESHING; setHeaderTopMargin(0); mHeaderImageView.setVisibility(View.GONE); mHeaderImageView.clearAnimation(); mHeaderImageView.setImageDrawable(null); // mHeaderProgressBar.setVisibility(View.VISIBLE); mHeaderTextView.setText(R.string.pull_to_refresh_refreshing_label); if (mOnHeaderRefreshListener != null) { mOnHeaderRefreshListener.onHeaderRefresh(this); } } private void footerRefreshing() { mFooterState = REFRESHING; int top = mHeaderViewHeight + mFooterViewHeight; setHeaderTopMargin(-top); mFooterImageView.setVisibility(View.GONE); mFooterImageView.clearAnimation(); mFooterImageView.setImageDrawable(null); // mFooterProgressBar.setVisibility(View.VISIBLE); mFooterTextView .setText(R.string.pull_to_refresh_footer_refreshing_label); if (mOnFooterRefreshListener != null) { mOnFooterRefreshListener.onFooterRefresh(this); } } /** * 设置header view 的topMargin的忍 */ private void setHeaderTopMargin(int topMargin) { LayoutParams params = (LayoutParams) mHeaderView.getLayoutParams(); params.topMargin = topMargin; mHeaderView.setLayoutParams(params); invalidate(); } /** * header view 完成更新后恢复初始状怿 * */ public void onHeaderRefreshComplete() { setHeaderTopMargin(-mHeaderViewHeight); mHeaderImageView.setVisibility(View.VISIBLE); mHeaderImageView.setImageResource(R.drawable.ic_pulltorefresh_arrow); mHeaderTextView.setText(R.string.pull_to_refresh_pull_label); // mHeaderProgressBar.setVisibility(View.GONE); mHeaderState = PULL_TO_REFRESH; setLastUpdated("朿?更新:" + new Date().toLocaleString()); } public void onHeaderRefreshComplete(CharSequence lastUpdated) { setLastUpdated(lastUpdated); onHeaderRefreshComplete(); } /** * footer view 完成更新后恢复初始状怿 */ public void onFooterRefreshComplete() { setHeaderTopMargin(-mHeaderViewHeight); mFooterImageView.setVisibility(View.VISIBLE); mFooterImageView.setImageResource(R.drawable.ic_pulltorefresh_arrow_up); mFooterTextView.setText(R.string.pull_to_refresh_footer_pull_label); // mFooterProgressBar.setVisibility(View.GONE); // mHeaderUpdateTextView.setText(""); mFooterState = PULL_TO_REFRESH; } /** * footer view 完成更新后恢复初始状怿 */ public void onFooterRefreshComplete(int size) { if (size > 0) { mFooterView.setVisibility(View.VISIBLE); } else { mFooterView.setVisibility(View.GONE); } setHeaderTopMargin(-mHeaderViewHeight); mFooterImageView.setVisibility(View.VISIBLE); mFooterImageView.setImageResource(R.drawable.ic_pulltorefresh_arrow_up); mFooterTextView.setText(R.string.pull_to_refresh_footer_pull_label); // mFooterProgressBar.setVisibility(View.GONE); // mHeaderUpdateTextView.setText(""); mFooterState = PULL_TO_REFRESH; } public void setLastUpdated(CharSequence lastUpdated) { if (lastUpdated != null) { mHeaderUpdateTextView.setVisibility(View.VISIBLE); mHeaderUpdateTextView.setText(lastUpdated); } else { mHeaderUpdateTextView.setVisibility(View.GONE); } } private int getHeaderTopMargin() { LayoutParams params = (LayoutParams) mHeaderView.getLayoutParams(); return params.topMargin; } // /** // * lock // */ // private void lock() { // mLock = true; // } // // /** // * unlock // * // private void unlock() { // mLock = false; // } /** * @description * @param headerRefreshListener */ public void setOnHeaderRefreshListener( OnHeaderRefreshListener headerRefreshListener) { mOnHeaderRefreshListener = headerRefreshListener; } public void setOnFooterRefreshListener( OnFooterRefreshListener footerRefreshListener) { mOnFooterRefreshListener = footerRefreshListener; } public interface OnFooterRefreshListener { public void onFooterRefresh(PullToRefreshView view); } public interface OnHeaderRefreshListener { public void onHeaderRefresh(PullToRefreshView view); } public boolean isEnablePullTorefresh() { return enablePullTorefresh; } public void setEnablePullTorefresh(boolean enablePullTorefresh) { this.enablePullTorefresh = enablePullTorefresh; } public boolean isEnablePullLoadMoreDataStatus() { return enablePullLoadMoreDataStatus; } public void setEnablePullLoadMoreDataStatus( boolean enablePullLoadMoreDataStatus) { this.enablePullLoadMoreDataStatus = enablePullLoadMoreDataStatus; } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/chart/RiseNumberBase.java ================================================ package com.cwp.chart; public interface RiseNumberBase { public void start(); public RiseNumberTextView withNumber(float number); public RiseNumberTextView withNumber(int number); public RiseNumberTextView setDuration(long duration); public void setOnEnd(RiseNumberTextView.EndListener callback); } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/chart/RiseNumberTextView.java ================================================ package com.cwp.chart; import android.content.Context; import android.util.AttributeSet; import android.widget.TextView; import com.nineoldandroids.animation.ValueAnimator; import java.text.DecimalFormat; public class RiseNumberTextView extends TextView implements RiseNumberBase { private static final int STOPPED = 0; private static final int RUNNING = 1; private int mPlayingState = STOPPED; private float number; private float fromNumber; private long duration = 1500; /** * 1.int 2.float */ private int numberType = 2; private DecimalFormat fnum; private EndListener mEndListener = null; final static int[] sizeTable = { 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, Integer.MAX_VALUE }; public RiseNumberTextView(Context context) { super(context); } public RiseNumberTextView(Context context, AttributeSet attr) { super(context, attr); } public RiseNumberTextView(Context context, AttributeSet attr, int defStyle) { super(context, attr, defStyle); } public interface EndListener { public void onEndFinish(); } public boolean isRunning() { return (mPlayingState == RUNNING); } private void runFloat() { ValueAnimator valueAnimator = ValueAnimator.ofFloat(fromNumber, number); valueAnimator.setDuration(duration); valueAnimator .addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { setText(fnum.format(Float.parseFloat(valueAnimator .getAnimatedValue().toString()))); if (valueAnimator.getAnimatedFraction() >= 1) { mPlayingState = STOPPED; if (mEndListener != null) mEndListener.onEndFinish(); } } }); valueAnimator.start(); } private void runInt() { ValueAnimator valueAnimator = ValueAnimator.ofInt((int) fromNumber, (int) number); valueAnimator.setDuration(duration); valueAnimator .addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { setText(valueAnimator.getAnimatedValue().toString()); if (valueAnimator.getAnimatedFraction() >= 1) { mPlayingState = STOPPED; if (mEndListener != null) mEndListener.onEndFinish(); } } }); valueAnimator.start(); } static int sizeOfInt(int x) { for (int i = 0;; i++) if (x <= sizeTable[i]) return i + 1; } @Override protected void onFinishInflate() { super.onFinishInflate(); fnum = new DecimalFormat("##0.00"); } @Override public void start() { if (!isRunning()) { mPlayingState = RUNNING; if (numberType == 1) runInt(); else runFloat(); } } @Override public RiseNumberTextView withNumber(float number) { this.number = number; numberType = 2; // if (number > 1000) { // fromNumber = number // - (float) Math.pow(10, sizeOfInt((int) number) - 2); // } else { // fromNumber = number / 2; // } fromNumber = 0; return this; } @Override public RiseNumberTextView withNumber(int number) { this.number = number; numberType = 1; // if (number>1000){ // fromNumber=number-(float)Math.pow(10,sizeOfInt((int)number)-2); // }else { // fromNumber=number/2; // } fromNumber = 0; return this; } @Override public RiseNumberTextView setDuration(long duration) { this.duration = duration; return this; } @Override public void setOnEnd(EndListener callback) { mEndListener = callback; } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/chart/SystemBarTintManager.java ================================================ /* * Copyright (C) 2013 readyState Software Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cwp.chart; import java.lang.reflect.Field; import java.lang.reflect.Method; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.FrameLayout.LayoutParams; /** * Class to manage status and navigation bar tint effects when using KitKat * translucent system UI modes. * */ public class SystemBarTintManager { /** * The default system bar tint color value. */ public static final int DEFAULT_TINT_COLOR = 0x99000000; private final SystemBarConfig mConfig; private boolean mStatusBarAvailable; private boolean mNavBarAvailable; private boolean mStatusBarTintEnabled; private boolean mNavBarTintEnabled; private View mStatusBarTintView; private View mNavBarTintView; private static boolean sIsMiuiV6; static { try { Class sysClass = Class.forName("android.os.SystemProperties"); Method getStringMethod = sysClass.getDeclaredMethod("get", String.class); sIsMiuiV6 = "V6".equals((String) getStringMethod.invoke(sysClass, "ro.miui.ui.version.name")); } catch (Exception e) { e.printStackTrace(); } } /** * Constructor. Call this in the host activity onCreate method after its * content view has been set. You should always create new instances when * the host activity is recreated. * * @param activity The host activity. */ @TargetApi(19) public SystemBarTintManager(Activity activity) { Window win = activity.getWindow(); ViewGroup decorViewGroup = (ViewGroup) win.getDecorView(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // check theme attrs int[] attrs = {android.R.attr.windowTranslucentStatus, android.R.attr.windowTranslucentNavigation}; TypedArray a = activity.obtainStyledAttributes(attrs); try { mStatusBarAvailable = a.getBoolean(0, false); mNavBarAvailable = a.getBoolean(1, false); } finally { a.recycle(); } // check window flags WindowManager.LayoutParams winParams = win.getAttributes(); int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; if ((winParams.flags & bits) != 0) { mStatusBarAvailable = true; } bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION; if ((winParams.flags & bits) != 0) { mNavBarAvailable = true; } } mConfig = new SystemBarConfig(activity, mStatusBarAvailable, mNavBarAvailable); // device might not have virtual navigation keys if (!mConfig.hasNavigtionBar()) { mNavBarAvailable = false; } if (mStatusBarAvailable) { setupStatusBarView(activity, decorViewGroup); } if (mNavBarAvailable) { setupNavBarView(activity, decorViewGroup); } } /** * Enable tinting of the system status bar. * * If the platform is running Jelly Bean or earlier, or translucent system * UI modes have not been enabled in either the theme or via window flags, * then this method does nothing. * * @param enabled True to enable tinting, false to disable it (default). */ public void setStatusBarTintEnabled(boolean enabled) { mStatusBarTintEnabled = enabled; if (mStatusBarAvailable) { mStatusBarTintView.setVisibility(enabled ? View.VISIBLE : View.GONE); } } /** * set status bar darkmode * @param darkmode * @param activity */ public void setStatusBarDarkMode(boolean darkmode, Activity activity) { if (sIsMiuiV6) { Class clazz = activity.getWindow().getClass(); try { int darkModeFlag = 0; Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams"); Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE"); darkModeFlag = field.getInt(layoutParams); Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class); extraFlagField.invoke(activity.getWindow(), darkmode ? darkModeFlag : 0, darkModeFlag); } catch (Exception e) { e.printStackTrace(); } } } /** * Enable tinting of the system navigation bar. * * If the platform does not have soft navigation keys, is running Jelly Bean * or earlier, or translucent system UI modes have not been enabled in either * the theme or via window flags, then this method does nothing. * * @param enabled True to enable tinting, false to disable it (default). */ public void setNavigationBarTintEnabled(boolean enabled) { mNavBarTintEnabled = enabled; if (mNavBarAvailable) { mNavBarTintView.setVisibility(enabled ? View.VISIBLE : View.GONE); } } /** * Apply the specified color tint to all system UI bars. * * @param color The color of the background tint. */ public void setTintColor(int color) { setStatusBarTintColor(color); setNavigationBarTintColor(color); } /** * Apply the specified drawable or color resource to all system UI bars. * * @param res The identifier of the resource. */ public void setTintResource(int res) { setStatusBarTintResource(res); setNavigationBarTintResource(res); } /** * Apply the specified drawable to all system UI bars. * * @param drawable The drawable to use as the background, or null to remove it. */ public void setTintDrawable(Drawable drawable) { setStatusBarTintDrawable(drawable); setNavigationBarTintDrawable(drawable); } /** * Apply the specified alpha to all system UI bars. * * @param alpha The alpha to use */ public void setTintAlpha(float alpha) { setStatusBarAlpha(alpha); setNavigationBarAlpha(alpha); } /** * Apply the specified color tint to the system status bar. * * @param color The color of the background tint. */ public void setStatusBarTintColor(int color) { if (mStatusBarAvailable) { mStatusBarTintView.setBackgroundColor(color); } } /** * Apply the specified drawable or color resource to the system status bar. * * @param res The identifier of the resource. */ public void setStatusBarTintResource(int res) { if (mStatusBarAvailable) { mStatusBarTintView.setBackgroundResource(res); } } /** * Apply the specified drawable to the system status bar. * * @param drawable The drawable to use as the background, or null to remove it. */ @SuppressWarnings("deprecation") public void setStatusBarTintDrawable(Drawable drawable) { if (mStatusBarAvailable) { mStatusBarTintView.setBackgroundDrawable(drawable); } } /** * Apply the specified alpha to the system status bar. * * @param alpha The alpha to use */ @TargetApi(11) public void setStatusBarAlpha(float alpha) { if (mStatusBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mStatusBarTintView.setAlpha(alpha); } } /** * Apply the specified color tint to the system navigation bar. * * @param color The color of the background tint. */ public void setNavigationBarTintColor(int color) { if (mNavBarAvailable) { mNavBarTintView.setBackgroundColor(color); } } /** * Apply the specified drawable or color resource to the system navigation bar. * * @param res The identifier of the resource. */ public void setNavigationBarTintResource(int res) { if (mNavBarAvailable) { mNavBarTintView.setBackgroundResource(res); } } /** * Apply the specified drawable to the system navigation bar. * * @param drawable The drawable to use as the background, or null to remove it. */ @SuppressWarnings("deprecation") public void setNavigationBarTintDrawable(Drawable drawable) { if (mNavBarAvailable) { mNavBarTintView.setBackgroundDrawable(drawable); } } /** * Apply the specified alpha to the system navigation bar. * * @param alpha The alpha to use */ @TargetApi(11) public void setNavigationBarAlpha(float alpha) { if (mNavBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mNavBarTintView.setAlpha(alpha); } } /** * Get the system bar configuration. * * @return The system bar configuration for the current device configuration. */ public SystemBarConfig getConfig() { return mConfig; } /** * Is tinting enabled for the system status bar? * * @return True if enabled, False otherwise. */ public boolean isStatusBarTintEnabled() { return mStatusBarTintEnabled; } /** * Is tinting enabled for the system navigation bar? * * @return True if enabled, False otherwise. */ public boolean isNavBarTintEnabled() { return mNavBarTintEnabled; } private void setupStatusBarView(Context context, ViewGroup decorViewGroup) { mStatusBarTintView = new View(context); LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, mConfig.getStatusBarHeight()); params.gravity = Gravity.TOP; if (mNavBarAvailable && !mConfig.isNavigationAtBottom()) { params.rightMargin = mConfig.getNavigationBarWidth(); } mStatusBarTintView.setLayoutParams(params); mStatusBarTintView.setBackgroundColor(DEFAULT_TINT_COLOR); mStatusBarTintView.setVisibility(View.GONE); decorViewGroup.addView(mStatusBarTintView); } private void setupNavBarView(Context context, ViewGroup decorViewGroup) { mNavBarTintView = new View(context); LayoutParams params; if (mConfig.isNavigationAtBottom()) { params = new LayoutParams(LayoutParams.MATCH_PARENT, mConfig.getNavigationBarHeight()); params.gravity = Gravity.BOTTOM; } else { params = new LayoutParams(mConfig.getNavigationBarWidth(), LayoutParams.MATCH_PARENT); params.gravity = Gravity.RIGHT; } mNavBarTintView.setLayoutParams(params); mNavBarTintView.setBackgroundColor(DEFAULT_TINT_COLOR); mNavBarTintView.setVisibility(View.GONE); decorViewGroup.addView(mNavBarTintView); } /** * Class which describes system bar sizing and other characteristics for the current * device configuration. * */ public static class SystemBarConfig { private static final String STATUS_BAR_HEIGHT_RES_NAME = "status_bar_height"; private static final String NAV_BAR_HEIGHT_RES_NAME = "navigation_bar_height"; private static final String NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME = "navigation_bar_height_landscape"; private static final String NAV_BAR_WIDTH_RES_NAME = "navigation_bar_width"; private final boolean mTranslucentStatusBar; private final boolean mTranslucentNavBar; private final int mStatusBarHeight; private final int mActionBarHeight; private final boolean mHasNavigationBar; private final int mNavigationBarHeight; private final int mNavigationBarWidth; private final boolean mInPortrait; private final float mSmallestWidthDp; private SystemBarConfig(Activity activity, boolean translucentStatusBar, boolean traslucentNavBar) { Resources res = activity.getResources(); mInPortrait = (res.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT); mSmallestWidthDp = getSmallestWidthDp(activity); mStatusBarHeight = getInternalDimensionSize(res, STATUS_BAR_HEIGHT_RES_NAME); mActionBarHeight = getActionBarHeight(activity); mNavigationBarHeight = getNavigationBarHeight(activity); mNavigationBarWidth = getNavigationBarWidth(activity); mHasNavigationBar = (mNavigationBarHeight > 0); mTranslucentStatusBar = translucentStatusBar; mTranslucentNavBar = traslucentNavBar; } @TargetApi(14) private int getActionBarHeight(Context context) { int result = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { TypedValue tv = new TypedValue(); context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true); result = context.getResources().getDimensionPixelSize(tv.resourceId); } return result; } @TargetApi(14) private int getNavigationBarHeight(Context context) { Resources res = context.getResources(); int result = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { if (!ViewConfiguration.get(context).hasPermanentMenuKey()) { String key; if (mInPortrait) { key = NAV_BAR_HEIGHT_RES_NAME; } else { key = NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME; } return getInternalDimensionSize(res, key); } } return result; } @TargetApi(14) private int getNavigationBarWidth(Context context) { Resources res = context.getResources(); int result = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { if (!ViewConfiguration.get(context).hasPermanentMenuKey()) { return getInternalDimensionSize(res, NAV_BAR_WIDTH_RES_NAME); } } return result; } private int getInternalDimensionSize(Resources res, String key) { int result = 0; int resourceId = res.getIdentifier(key, "dimen", "android"); if (resourceId > 0) { result = res.getDimensionPixelSize(resourceId); } return result; } @SuppressLint("NewApi") private float getSmallestWidthDp(Activity activity) { DisplayMetrics metrics = new DisplayMetrics(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { activity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics); } else { // TODO this is not correct, but we don't really care pre-kitkat activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); } float widthDp = metrics.widthPixels / metrics.density; float heightDp = metrics.heightPixels / metrics.density; return Math.min(widthDp, heightDp); } /** * Should a navigation bar appear at the bottom of the screen in the current * device configuration? A navigation bar may appear on the right side of * the screen in certain configurations. * * @return True if navigation should appear at the bottom of the screen, False otherwise. */ public boolean isNavigationAtBottom() { return (mSmallestWidthDp >= 600 || mInPortrait); } /** * Get the height of the system status bar. * * @return The height of the status bar (in pixels). */ public int getStatusBarHeight() { return mStatusBarHeight; } /** * Get the height of the action bar. * * @return The height of the action bar (in pixels). */ public int getActionBarHeight() { return mActionBarHeight; } /** * Does this device have a system navigation bar? * * @return True if this device uses soft key navigation, False otherwise. */ public boolean hasNavigtionBar() { return mHasNavigationBar; } /** * Get the height of the system navigation bar. * * @return The height of the navigation bar (in pixels). If the device does not have * soft navigation keys, this will always return 0. */ public int getNavigationBarHeight() { return mNavigationBarHeight; } /** * Get the width of the system navigation bar when it is placed vertically on the screen. * * @return The width of the navigation bar (in pixels). If the device does not have * soft navigation keys, this will always return 0. */ public int getNavigationBarWidth() { return mNavigationBarWidth; } /** * Get the layout inset for any system UI that appears at the top of the screen. * * @param withActionBar True to include the height of the action bar, False otherwise. * @return The layout inset (in pixels). */ public int getPixelInsetTop(boolean withActionBar) { return (mTranslucentStatusBar ? mStatusBarHeight : 0) + (withActionBar ? mActionBarHeight : 0); } /** * Get the layout inset for any system UI that appears at the bottom of the screen. * * @return The layout inset (in pixels). */ public int getPixelInsetBottom() { if (mTranslucentNavBar && isNavigationAtBottom()) { return mNavigationBarHeight; } else { return 0; } } /** * Get the layout inset for any system UI that appears at the right of the screen. * * @return The layout inset (in pixels). */ public int getPixelInsetRight() { if (mTranslucentNavBar && !isNavigationAtBottom()) { return mNavigationBarWidth; } else { return 0; } } } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/chart/Util.java ================================================ package com.cwp.chart; import android.os.Build; public class Util { static final boolean IS_JBMR2 = Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN_MR2; static final boolean IS_ISC = Build.VERSION.SDK_INT == Build.VERSION_CODES.ICE_CREAM_SANDWICH; static final boolean IS_GINGERBREAD_MR1 = Build.VERSION.SDK_INT == Build.VERSION_CODES.GINGERBREAD_MR1; } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/About.java ================================================ package com.cwp.cmoneycharge; import com.cwp.chart.SystemBarTintManager; import com.cwp.pattern.GuideGesturePasswordActivity; import com.cwp.pattern.UnlockGesturePasswordActivity; import com.cwp.pattern.UpdateManager; import com.umeng.fb.example.CustomActivity; import cwp.moneycharge.dao.AccountDAO; import cwp.moneycharge.dao.IncomeDAO; import cwp.moneycharge.dao.ItypeDAO; import cwp.moneycharge.dao.NoteDAO; import cwp.moneycharge.dao.PayDAO; import cwp.moneycharge.dao.PtypeDAO; import cwp.moneycharge.model.ActivityManager; import cwp.moneycharge.model.CustomDialog; import android.annotation.TargetApi; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Build; import android.os.Bundle; import android.os.StrictMode; import android.preference.PreferenceManager; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; public class About extends Activity { TextView usernow, countuser, countpay, countincome, sendlog, gesturepw, gesturepwmdtext, gesturepwcleartext; TableRow author, description, gesturepwmd; Intent intentr; int userid; AccountDAO accountDAO = new AccountDAO(About.this); PayDAO payDAO = new PayDAO(About.this); IncomeDAO incomeDAO = new IncomeDAO(About.this); NoteDAO noteDAO = new NoteDAO(About.this); static SharedPreferences sp; Editor edit; private final int REQUESTCODE = 1; // 返回的结果码 private TextView app_version; private TextView updateapp; private TextView feedback; public About() { } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.about); SysApplication.getInstance().addActivity(this); // 在销毁队列中添加this if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { setTranslucentStatus(true); findViewById(R.id.about_top).setVisibility(View.VISIBLE); } SystemBarTintManager mTintManager = new SystemBarTintManager(this); mTintManager.setStatusBarTintEnabled(true); mTintManager.setStatusBarTintResource(R.color.statusbar_bg); usernow = (TextView) findViewById(R.id.useracc); countpay = (TextView) findViewById(R.id.countpay); countuser = (TextView) findViewById(R.id.countuser); countincome = (TextView) findViewById(R.id.countincome); description = (TableRow) findViewById(R.id.description); sendlog = (TextView) findViewById(R.id.sendlog); gesturepw = (TextView) findViewById(R.id.gesturepw); gesturepwmd = (TableRow) findViewById(R.id.gesturepwmd); gesturepwmdtext = (TextView) findViewById(R.id.gesturepwmdtext); app_version = (TextView) findViewById(R.id.app_version); updateapp = (TextView) findViewById(R.id.updateapp); feedback = (TextView) findViewById(R.id.feedback); sp = this.getSharedPreferences("preferences", MODE_WORLD_READABLE); edit = sp.edit(); } @TargetApi(19) private void setTranslucentStatus(boolean on) { Window win = getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; if (on) { winParams.flags |= bits; } else { winParams.flags &= ~bits; } win.setAttributes(winParams); } @Override protected void onStart() { super.onStart(); intentr = getIntent(); userid = intentr.getIntExtra("cwp.id", 100000001); if (userid == 100000001) usernow.setText("默认用户"); else { usernow.setText(accountDAO.find(userid)); } app_version.setText(getVersion(this)); feedback.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(About.this, CustomActivity.class); // intent.putExtra("cwp.md", "md"); startActivity(intent); } }); updateapp.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { UpdateManager manager = new UpdateManager(About.this); // 检查软件更新 manager.checkUpdate("show"); } }); class OnClickListenermd implements OnClickListener { // 修改密码 @Override public void onClick(View v) { Intent intent = new Intent(About.this, UnlockGesturePasswordActivity.class); intent.putExtra("cwp.md", "md"); startActivity(intent); } } if (sp.getString("gesturepw", "").equals("关") || sp.getString("gesturepw", "").equals("")) { gesturepw.setText("关"); } else { gesturepw.setText("开"); gesturepwmd.setVisibility(View.VISIBLE); if (CrashApplication.getInstance().getLockPatternUtils() .savedPatternExists()) { gesturepwmd.setOnClickListener(new OnClickListenermd()); // 修改密码 } } if (sp.getString("sendlog", "").equals("关") || sp.getString("sendlog", "").equals("")) { sendlog.setText("关"); } else { sendlog.setText("开"); } countuser.setText(String.valueOf(accountDAO.getCount())); countpay.setText(String.valueOf(payDAO.getCount(userid))); countincome.setText(String.valueOf(incomeDAO.getCount(userid))); gesturepw.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { CustomDialog.Builder customBuilder = new CustomDialog.Builder( About.this); customBuilder.setTitle("提示"); // 创建标题 customBuilder .setMessage("是否开启/关闭手势密码?\n注意:关闭手势密码需输入原密码!") .setPositiveButton("开启", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (!sp.getString("gesturepw", "") .equals("开")) { Intent intent = new Intent( About.this, UnlockGesturePasswordActivity.class); intent.putExtra("cwp.pwenable", "enable"); startActivityForResult(intent, REQUESTCODE); // 表示可以返回结果 } } }) .setNegativeButton("关闭", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); Intent intent = new Intent( About.this, UnlockGesturePasswordActivity.class); intent.putExtra("cwp.pwclear", "clear"); startActivityForResult(intent, REQUESTCODE); // 表示可以返回结果 } }); Dialog dialog = customBuilder.create();// 创建对话框 dialog.show(); // 显示对话框 } }); sendlog.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { CustomDialog.Builder customBuilder = new CustomDialog.Builder( About.this); customBuilder.setTitle("提示"); // 创建标题 customBuilder .setMessage("是否开启/关闭发送错误日志功能?\n注意:需退出程序重新进入完成初始化!") .setPositiveButton("开启", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { edit.putString("sendlog", "开"); edit.commit(); sendlog.setText("开"); dialog.dismiss(); } }) .setNegativeButton("关闭", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { edit.putString("sendlog", "关"); edit.commit(); sendlog.setText("关"); dialog.dismiss(); } }); Dialog dialog = customBuilder.create();// 创建对话框 dialog.show(); // 显示对话框 } }); description.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Intent intent = new Intent(About.this, Description.class); intent.putExtra("cwp.id", userid); startActivity(intent); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUESTCODE) { if (resultCode == 2) { edit.putString("gesturepw", "关"); edit.commit(); gesturepw.setText("关"); gesturepwmd.setVisibility(View.GONE); } if (resultCode == 3) { edit.putString("gesturepw", "开"); edit.commit(); gesturepw.setText("开"); gesturepwmd.setVisibility(View.VISIBLE); } } else { Toast.makeText(About.this, "操作失败!", Toast.LENGTH_LONG).show(); } } public static String getVersion(Context context)// 获取版本号 { try { PackageInfo pi = context.getPackageManager().getPackageInfo( context.getPackageName(), 0); return pi.versionName; } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); return "beta 1.0"; } } public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键 Intent intent = new Intent(About.this, MainActivity.class); intent.putExtra("cwp.id", userid); intent.putExtra("cwp.Fragment", "4");// 设置传递数据 startActivity(intent); return true; } return super.onKeyDown(keyCode, event); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/AddPay.java ================================================ package com.cwp.cmoneycharge; import java.io.IOException; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Random; import com.amap.api.location.AMapLocation; import com.amap.api.location.AMapLocationListener; import com.amap.api.location.LocationManagerProxy; import com.amap.api.location.LocationProviderProxy; import com.baidu.voicerecognition.android.ui.BaiduASRDigitalDialog; import com.baidu.voicerecognition.android.ui.DialogRecognitionListener; import com.cwp.chart.SystemBarTintManager; import com.cwp.cmoneycharge.Config; import com.cwp.cmoneycharge.Constants; import com.cwp.cmoneycharge.DigitUtil; import com.cwp.cmoneycharge.Effectstype; import com.cwp.cmoneycharge.KeyboardUtil; import com.cwp.cmoneycharge.MainActivity; import com.cwp.cmoneycharge.NiftyDialogBuilder; import com.cwp.pattern.UnlockGesturePasswordActivity; import com.example.testpic.Bimp; import com.example.testpic.PublishedActivity; import cwp.moneycharge.dao.IncomeDAO; import cwp.moneycharge.dao.ItypeDAO; import cwp.moneycharge.dao.PayDAO; import cwp.moneycharge.dao.PtypeDAO; import cwp.moneycharge.model.Datapicker; import cwp.moneycharge.model.Tb_income; import cwp.moneycharge.model.Tb_pay; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.location.Location; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.View.OnClickListener; import android.view.View.OnFocusChangeListener; import android.view.View.OnTouchListener; import android.view.inputmethod.InputMethodManager; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.DatePicker; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RelativeLayout; import android.widget.RelativeLayout.LayoutParams; import android.widget.Spinner; import android.widget.Toast; public class AddPay extends Activity implements AMapLocationListener, OnClickListener { protected static final int DATE_DIALOG_ID = 0;// 创建日期对话框常量 static String type = "pay"; String VoiceDefault = ""; protected static String typemode = "add"; EditText txtMoney, txtTime, txtAddress, txtMark;// 创建EditText对象 Spinner spType;// 创建Spinner对象 Button btnSaveButton;// 创建Button对象“保存” Button btnCancelButton;// 创建Button对象“取消” Button btnVoice;// 创建Button对象“语音识别” int userid; int Selection = 0; Bundle bundle = null; String[] strInfos = null;// 定义字符串数组 String strno, strType;// 定义两个字符串变量,分别用来记录信息编号和管理类型 private FrameLayout corporation_fl, address_fl = null; private RadioButton rb1 = null; private RadioButton rb2 = null; ImageView left_back; private BaiduASRDigitalDialog mDialog = null; // 百度语音定义 private DialogRecognitionListener mRecognitionListener; private int mCurrentTheme = Config.DIALOG_THEME; private Effectstype effect; // 自定义Dialog NiftyDialogBuilder dialogBuilder = null; Boolean firstin = true; private int mYear;// 年 private int mMonth;// 月 private int mDay;// 日 private ArrayAdapter adapter; private String[] spdata; private LocationManagerProxy mLocationManagerProxy;// 高德地图api private Random mRandom = new Random(); String[] number = { "一", "二", "两", "三", "四", "五", "六", "七", "八", "九", "十" }; String[] money = { "元", "块", "钱" }; String[] money2 = { "十", "百", "千", "万", "亿" }; String[] voice_pay = { "买", "吃" }; String[] voice_income = { "卖", "获" }; String[] VoiceSave = new String[6]; static DialogShowUtil dialogShowUtil; PtypeDAO ptypeDAO = new PtypeDAO(AddPay.this); ItypeDAO itypeDAO = new ItypeDAO(AddPay.this); PayDAO payDAO = new PayDAO(AddPay.this);// 创建PayDAO对象 IncomeDAO incomeDAO = new IncomeDAO(AddPay.this);// 创建IncomeDAO对象 List spdatalist, spdatalist2; private SystemBarTintManager mTintManager; private ImageView btn_loacte; private ImageView addphoto; protected String textphoto = ""; private int incount = 0; private boolean keycount = true; private FrameLayout bottom_empty; private LinearLayout bottom_full; private KeyboardUtil keyBoard; public AddPay() { } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.add);// 设置布局文件 SysApplication.getInstance().addActivity(this); // 在销毁队列中添加this super.onStart();// 实现基类中的方法 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { setTranslucentStatus(true); findViewById(R.id.top).setVisibility(View.VISIBLE); } mTintManager = new SystemBarTintManager(this); mTintManager.setStatusBarTintEnabled(true); mTintManager.setStatusBarTintResource(R.color.statusbar_bg); txtMoney = (EditText) findViewById(R.id.txtMoney);// 获取金额文本框 txtTime = (EditText) findViewById(R.id.txtTime);// 获取时间文本框 txtAddress = (EditText) findViewById(R.id.txtAddress);// 获取地点文本框 txtMark = (EditText) findViewById(R.id.txtMark);// 获取备注文本框 spType = (Spinner) findViewById(R.id.spType);// 获取类别下拉列表 btnSaveButton = (Button) findViewById(R.id.btnSave);// 获取保存按钮 btnCancelButton = (Button) findViewById(R.id.btnCancel);// 获取取消按钮 btnVoice = (Button) findViewById(R.id.btnVoice);// 获取语音识别按钮 rb1 = (RadioButton) findViewById(R.id.payout_tab_rb); rb2 = (RadioButton) findViewById(R.id.income_tab_rb); left_back = (ImageView) findViewById(R.id.example_left3); btn_loacte = (ImageView) findViewById(R.id.btn_loacte); addphoto = (ImageView) findViewById(R.id.addphoto); bottom_empty = (FrameLayout) findViewById(R.id.bottom_empty); bottom_full = (LinearLayout) findViewById(R.id.bottom_full); dialogShowUtil = new DialogShowUtil(this, this, VoiceSave, type, // 初始化dialog VoiceDefault); btn_loacte.setOnClickListener(this); // 定位 // 隐藏菜单 bottom_empty.setOnClickListener(new OnClickListener() { public void onClick(View v) { keyBoard.hideKeyboard(); bottom_empty.setVisibility(View.GONE); bottom_full.setVisibility(View.VISIBLE); } }); // 添加图片 addphoto.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(AddPay.this, PublishedActivity.class); intent.putExtra("cwp.id", userid); startActivityForResult(intent, 102); } }); // 初始化定位,只采用网络定位 mLocationManagerProxy = LocationManagerProxy.getInstance(this); mLocationManagerProxy.setGpsEnable(false); // 此方法为每隔固定时间会发起一次定位请求,为了减少电量消耗或网络流量消耗, // 注意设置合适的定位时间的间隔(最小间隔支持为2000ms),并且在合适时间调用removeUpdates()方法来取消定位请求 // 在定位结束后,在合适的生命周期调用destroy()方法 // 其中如果间隔时间为-1,则定位只定一次, // 在单次定位情况下,定位无论成功与否,都无需调用removeUpdates()方法移除请求,定位sdk内部会移除 left_back.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent = null; type = "pay"; typemode = "add"; if (bundle.containsKey("cwp.frament3")) { intent = new Intent(AddPay.this, MainActivity.class); intent.putExtra("cwp.Fragment", "3");// 设置传递数据 } else { intent = new Intent(AddPay.this, MainActivity.class); } intent.putExtra("cwp.id", userid); startActivity(intent); finish();// 这个是关键 } }); mRecognitionListener = new DialogRecognitionListener() { // 百度识别返回数据 @Override public void onResults(Bundle results) { ArrayList rs = results != null ? results .getStringArrayList(RESULTS_RECOGNITION) : null; if (rs != null && rs.size() > 0) { Recognition(rs.get(0)); // 把识别数据传入识别方法 // Toast.makeText(AddPay.this, rs.get(0), // Toast.LENGTH_SHORT).show(); } } }; corporation_fl = (FrameLayout) findViewById(R.id.corporation_fl); address_fl = (FrameLayout) findViewById(R.id.address_fl); rb1.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (rb1.isChecked()) { // 支出 type = "pay"; } else // 收入 { type = "income"; } updatetype(); } }); final Calendar c = Calendar.getInstance();// 获取当前系统日期 mYear = c.get(Calendar.YEAR);// 获取年份 mMonth = c.get(Calendar.MONTH);// 获取月份 mDay = c.get(Calendar.DAY_OF_MONTH);// 获取天数 } @TargetApi(19) private void setTranslucentStatus(boolean on) { Window win = getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; if (on) { winParams.flags |= bits; } else { winParams.flags &= ~bits; } win.setAttributes(winParams); } private void initData(int userid) { // 初始化数据 if (typemode == "add") { // 添加模式 if (type == "pay") { // 支出 rb1.setChecked(true); spdatalist = ptypeDAO.getPtypeName(userid); txtMoney.setTextColor(Color.parseColor("#5ea98d")); } else { // 收入 rb2.setChecked(true); spdatalist = itypeDAO.getItypeName(userid); txtMoney.setTextColor(Color.parseColor("#ffff0000")); } } else { // 修改模式 bottom_empty.setVisibility(View.GONE); bottom_full.setVisibility(View.VISIBLE); rb1.setOnCheckedChangeListener(null); btnSaveButton.setText("修改"); // 替换修改按钮 btnCancelButton.setText("删除"); // 替换删除按钮 CharSequence textreAddres; String textreMark; if (type == "pay") { // 支出 rb1.setChecked(true); rb1.setClickable(false); rb2.setClickable(false); // 选择列表初始化 spdatalist = ptypeDAO.getPtypeName(userid); // 根据编号查找支出信息,并存储到Tb_pay对象中 Tb_pay tb_pay = payDAO.find(userid, Integer.parseInt(strno)); txtMoney.setText(tb_pay.getMoney2());// 显示金额 txtMoney.setTextColor(Color.parseColor("#5ea98d")); txtTime.setText(tb_pay.getTime());// 显示时间 Selection = tb_pay.getType() - 1; initphotodata(tb_pay.getPhoto()); textreAddres = tb_pay.getAddress(); textreMark = tb_pay.getMark(); txtAddress.setText(textreAddres);// 显示地点 txtMark.setText(textreMark);// 显示备注 } else { // 收入 // 选择列表初始化 rb2.setChecked(true); rb1.setClickable(false); rb2.setClickable(false); spdatalist = itypeDAO.getItypeName(userid); // 根据编号查找收入信息,并存储到Tb_pay对象中 Tb_income tb_income = incomeDAO.find(userid, Integer.parseInt(strno)); txtMoney.setText(tb_income.getMoney2());// 显示金额 txtMoney.setTextColor(Color.parseColor("#ffff0000")); txtTime.setText(tb_income.getTime());// 显示时间 Selection = tb_income.getType() - 1; // 显示类别 initphotodata(tb_income.getPhoto()); textreAddres = tb_income.getHandler(); textreMark = tb_income.getMark(); txtAddress.setText(textreAddres);// 显示地点 txtMark.setText(textreMark);// 显示备注 } } } private void initphotodata(String photo) { // 初始化图片数据 if ((incount == 0) && (!photo.equals(""))) { String[] photoall = photo.split(","); for (int i = 0; i < photoall.length / 2; i++) { if (Bimp.drr.size() < 9) { Bimp.drr.add(photoall[i]); } } for (int i = photoall.length / 2; i < photoall.length; i++) { if (Bimp.smdrr.size() < 9) { Bimp.smdrr.add(photoall[i]); } } textphoto = photo; initphoto(); incount++; } } @SuppressWarnings("deprecation") private void initphoto() {// 初始化图片 try { if (textphoto.equals("")) { addphoto.setImageResource(R.drawable.addphoto_btn); } else if (Bimp.getbitmap(Bimp.smdrr.get(0)) == null) { Toast.makeText(AddPay.this, "图片不存在", Toast.LENGTH_SHORT).show(); } else { addphoto.setImageBitmap(Bimp.getbitmap(Bimp.smdrr.get(0))); } } catch (IOException e) { e.printStackTrace(); } } private void updatetype() { // 更新类别 initData(userid); spdata = spdatalist.toArray(new String[spdatalist.size()]);// 在tb_itype中按用户id读取 adapter = new ArrayAdapter(AddPay.this, R.layout.spinner, spdata); // 动态生成收入类型列表 spType.setAdapter(adapter); if (Selection > 0) { spType.setSelection(Selection);// 显示类别 } } @Override protected void onStart() { // 复写onstart super.onStart();// 实现基类中的方法 updateDisplay();// 显示当前系统时间 Intent intentr = getIntent(); userid = intentr.getIntExtra("cwp.id", 100000001); bundle = intentr.getExtras();// 获取传入的数据,并使用Bundle记录 if (bundle.containsKey("cwp.message")) { strInfos = bundle.getStringArray("cwp.message");// 获取Bundle中记录的信息 strno = strInfos[0];// 记录id strType = strInfos[1];// 记录类型 typemode = "ModifyInP"; if (strType.equals("btnininfo")) { // 收入 type = "income"; } else { type = "pay"; } } keyBoard = new KeyboardUtil(this, this, txtMoney, typemode); // 数字软键盘 if (bundle.containsKey("cwp.voice")) { // 进来调用语音记账 if (firstin) { bottom_empty.setVisibility(View.GONE); bottom_full.setVisibility(View.VISIBLE); dialogShowUtil.dialogShow("rotatebottom", "first", "", ""); firstin = false; } } if (bundle.containsKey("cwp.photo")) {// 进来调用拍照 if (firstin) { bottom_empty.setVisibility(View.GONE); bottom_full.setVisibility(View.VISIBLE); Intent intent = new Intent(AddPay.this, PublishedActivity.class); intent.putExtra("cwp.id", userid); intent.putExtra("cwp.photo", "photo"); startActivityForResult(intent, 102); firstin = false; } } if (bundle.containsKey("keyboard")) { // 进来显示键盘 if (keycount) { InputMethodManager imm = (InputMethodManager) getSystemService(AddPay.this.INPUT_METHOD_SERVICE); // 显示键盘 imm.hideSoftInputFromWindow(txtMoney.getWindowToken(), 0); // 隐藏键盘  keyBoard.showKeyboard(); keycount = false; } } updatetype(); txtTime.setOnTouchListener(new OnTouchListener() { // 为时间文本框设置单击监听事件 @Override public boolean onTouch(View v, MotionEvent event) { showDialog(DATE_DIALOG_ID);// 显示日期选择对话框 return false; } }); txtMoney.setOnTouchListener(new OnTouchListener() { // 数字软键盘监听 @Override public boolean onTouch(View v, MotionEvent event) { InputMethodManager imm = (InputMethodManager) getSystemService(AddPay.this.INPUT_METHOD_SERVICE); // 显示键盘 imm.hideSoftInputFromWindow(txtMoney.getWindowToken(), 0); // 隐藏键盘  keyBoard.showKeyboard(); return false; } }); btnVoice.setOnClickListener(new OnClickListener() {// 语音识别监听 @Override public void onClick(View v) { dialogShowUtil.dialogShow("rotatebottom", "first", "", ""); } }); btnSaveButton.setOnClickListener(new OnClickListener() {// 为保存按钮设置监听事件 private String textreAddres; private String textreMark; @SuppressLint("NewApi") @Override public void onClick(View arg0) { textreAddres = txtAddress.getText().toString(); textreMark = txtMark.getText().toString(); if (textphoto == null) { textphoto = ""; } if (typemode == "add") { // 添加模式 String strMoney = txtMoney.getText().toString();// 获取金额文本框的值 if (type == "pay") { // 支出 if (!strMoney.isEmpty()) {// 判断金额不为空 // 创建InaccountDAO对象 PayDAO payDAO = new PayDAO(AddPay.this); // 创建Tb_inaccount对象 Tb_pay tb_pay = new Tb_pay( userid, payDAO.getMaxNo(userid) + 1, get2Double(strMoney), setTimeFormat(null), (spType.getSelectedItemPosition() + 1), textreAddres, textreMark, textphoto); payDAO.add(tb_pay);// 添加收入信息 Toast.makeText(AddPay.this, "〖新增收入〗数据添加成功!", Toast.LENGTH_SHORT) .show(); gotoback(); } else { Toast.makeText(AddPay.this, "请输入收入金额!", Toast.LENGTH_SHORT).show(); } } else { // 收入 if (!strMoney.isEmpty()) {// 判断金额不为空 // 创建InaccountDAO对象 IncomeDAO incomeDAO = new IncomeDAO( AddPay.this); // 创建Tb_inaccount对象 Tb_income tb_income = new Tb_income( userid, payDAO.getMaxNo(userid) + 1, get2Double(strMoney), setTimeFormat(null), (spType.getSelectedItemPosition() + 1), // txtInhandler.getText().toString(), textreAddres, textreMark, textphoto, "支出"); incomeDAO.add(tb_income);// 添加收入信息 // 弹出信息提示 Toast.makeText(AddPay.this, "〖新增收入〗数据添加成功!", Toast.LENGTH_SHORT) .show(); gotoback(); } else { Toast.makeText(AddPay.this, "请输入收入金额!", Toast.LENGTH_SHORT).show(); } } } else { // 修改模式 if (type == "pay") { // 支出 if (!txtMoney.getText().toString().isEmpty()) {// 判断金额不为空 Tb_pay tb_pay = new Tb_pay(); // 创建Tb_pay对象 tb_pay.set_id(userid); // 设置userid tb_pay.setNo(Integer.parseInt(strno)); // 设置编号 tb_pay.setMoney(get2Double(txtMoney .getText().toString()));// 设置金额 tb_pay.setTime(setTimeFormat(txtTime .getText().toString()));// 设置时间 tb_pay.setType(spType .getSelectedItemPosition() + 1);// 设置类别 tb_pay.setAddress(textreAddres);// 设置地点 tb_pay.setMark(textreMark);// 设置备注 tb_pay.setPhoto(textphoto);// 设置备注 payDAO.update(tb_pay);// 更新支出信息 Toast.makeText(AddPay.this, "〖数据〗修改成功!", Toast.LENGTH_SHORT).show(); gotoback(); } else { Toast.makeText(AddPay.this, "请输入收入金额!", Toast.LENGTH_SHORT).show(); } } else { // 收入 if (!txtMoney.getText().toString().isEmpty()) {// 判断金额不为空 Tb_income tb_income = new Tb_income();// 创建Tb_income对象 tb_income.set_id(userid);// 设置编号 tb_income.setNo(Integer.parseInt(strno));// 设置编号 tb_income.setMoney(get2Double(txtMoney .getText().toString()));// 设置金额 tb_income.setTime(setTimeFormat(txtTime .getText().toString()));// 设置时间 tb_income.setType(spType .getSelectedItemPosition() + 1);// 设置类别 tb_income.setHandler(textreAddres);// 设置付款方 tb_income.setMark(textreMark);// 设置备注 tb_income.setPhoto(textphoto);// 设置备注 incomeDAO.update(tb_income);// 更新收入信息 Toast.makeText(AddPay.this, "〖数据〗修改成功!", Toast.LENGTH_SHORT).show(); gotoback(); } else { Toast.makeText(AddPay.this, "请输入收入金额!", Toast.LENGTH_SHORT).show(); } } } } }); btnCancelButton.setOnClickListener(new OnClickListener() {// 为取消按钮设置单击监听事件 @Override public void onClick(View arg0) { if (typemode == "add") { // 添加模式执行返回 txtMoney.setText("");// 设置金额文本框为空 txtMoney.setHint("0.00");// 为金额文本框设置提示 txtTime.setText("");// 设置时间文本框为空 txtAddress.setText("");// 设置地址文本框为空 txtMark.setText("");// 设置备注文本框为空 // txtInhandler.setText("");// 设置备注文本框为空 spType.setSelection(0);// 设置类别下拉列表默认选择第一项 gotoback(); } else { // 修改模式执行删除 if (type == "pay") { // 支出 payDAO.detele(userid, Integer.parseInt(strno));// 根据编号删除支出信息 gotoback(); } else { // 收入 incomeDAO.detele(userid, Integer.parseInt(strno));// 根据编号删除收入信息 gotoback(); } Toast.makeText(AddPay.this, "〖数据〗删除成功!", Toast.LENGTH_SHORT).show(); } } }); } // 保留2位小数 public static double get2Double(String strMoney) { // 处理小数点 Double a = Double.parseDouble(strMoney); DecimalFormat df = new DecimalFormat("0.00"); return new Double(df.format(a)); } @Override protected Dialog onCreateDialog(int id)// 重写onCreateDialog方法 { switch (id) { case DATE_DIALOG_ID:// 弹出日期选择对话框 return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay); } return null; } private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { mYear = year;// 为年份赋值 mMonth = monthOfYear;// 为月份赋值 mDay = dayOfMonth;// 为天赋值 updateDisplay();// 显示设置的日期 } }; private void updateDisplay() { // 显示设置的时间 txtTime.setText(new StringBuilder().append(mYear).append("-") .append(mMonth + 1).append("-").append(mDay)); } private String setTimeFormat(String newtxtTime) { // 设置日期格式 String date; if (typemode == "add") { date = txtTime.getText().toString(); } else { date = newtxtTime; } int y, m, d; String sm, sd; int i = 0, j = 0, k = 0; for (i = 0; i < date.length(); i++) { if (date.substring(i, i + 1).equals("-") && j == 0) j = i; else if (date.substring(i, i + 1).equals("-")) k = i; } y = Integer.valueOf(date.substring(0, j)); m = Integer.valueOf(date.substring(j + 1, k)); d = Integer.valueOf(date.substring(k + 1)); if (m < 10) { sm = "0" + String.valueOf(m); } else sm = String.valueOf(m); if (d < 10) { sd = "0" + String.valueOf(d); } else sd = String.valueOf(d); return String.valueOf(y) + "-" + sm + "-" + sd; } void VoiceRecognition() { // 调用百度语音识别 // mResult.setText(null); mCurrentTheme = Config.DIALOG_THEME; if (mDialog != null) { mDialog.dismiss(); } Bundle params = new Bundle(); params.putString(BaiduASRDigitalDialog.PARAM_API_KEY, Constants.API_KEY); // 百度语音api_key params.putString(BaiduASRDigitalDialog.PARAM_SECRET_KEY, Constants.SECRET_KEY); params.putInt(BaiduASRDigitalDialog.PARAM_DIALOG_THEME, // 百度语音主题 Config.DIALOG_THEME); mDialog = new BaiduASRDigitalDialog(this, params); mDialog.setDialogRecognitionListener(mRecognitionListener); mDialog.getParams().putInt(BaiduASRDigitalDialog.PARAM_PROP, // 百度识别类别 Config.CURRENT_PROP); mDialog.getParams().putString(BaiduASRDigitalDialog.PARAM_LANGUAGE, // 百度识别语言 Config.getCurrentLanguage()); mDialog.getParams().putBoolean( // 百度识别音效相关 BaiduASRDigitalDialog.PARAM_START_TONE_ENABLE, Config.PLAY_START_SOUND); mDialog.getParams().putBoolean( BaiduASRDigitalDialog.PARAM_END_TONE_ENABLE, Config.PLAY_END_SOUND); mDialog.getParams().putBoolean( BaiduASRDigitalDialog.PARAM_TIPS_TONE_ENABLE, Config.DIALOG_TIPS_SOUND); mDialog.show(); } void VoiceSuccess() { // 识别成功录入数据 if (DialogShowUtil.dialoggettype() != null) { type = DialogShowUtil.dialoggettype(); } VoiceDefault = DialogShowUtil.dialogVoiceDefault(); String textreMark = txtMark.getText().toString(); if (typemode == "add") { // 添加模式 if (type == "pay") { // 支出 rb1.setChecked(true); // corporation_fl.setVisibility(View.GONE); // address_fl.setVisibility(View.VISIBLE); spdatalist = ptypeDAO.getPtypeName(userid); txtMoney.setText(VoiceSave[1]);// 显示金额 txtMoney.setTextColor(Color.parseColor("#5ea98d")); if (VoiceDefault == "notype") { // 如果没有默认类别 spType.setSelection(Integer.parseInt(VoiceSave[5]));// 显示语音识别类别 } else { spType.setSelection(Integer.parseInt(VoiceSave[0]));// 显示类别 } txtMark.setText(textreMark + " " + VoiceSave[2]);// 显示备注 } else { // 收入 rb2.setChecked(true); // corporation_fl.setVisibility(View.VISIBLE); // address_fl.setVisibility(View.GONE); spdatalist = ptypeDAO.getPtypeName(userid); txtMoney.setText(VoiceSave[1]);// 显示金额 txtMoney.setTextColor(Color.parseColor("#ffff0000")); if (VoiceDefault == "notype") { // 如果没有默认类别 spType.setSelection(Integer.parseInt(VoiceSave[5]));// 显示类别 } else { spType.setSelection(Integer.parseInt(VoiceSave[4]));// 显示类别 } txtMark.setText(textreMark + " " + VoiceSave[2]);// 显示备注 } } else { // 修改模式 if (type == "pay") { // 支出 rb1.setChecked(true); // 选择列表初始化 spdatalist = ptypeDAO.getPtypeName(userid); spdata = spdatalist.toArray(new String[spdatalist.size()]);// 在tb_itype中按用户id读取 adapter = new ArrayAdapter(AddPay.this, R.layout.spinner, spdata); // 动态生成收入类型列表 spType.setAdapter(adapter); txtMoney.setText(VoiceSave[1]);// 显示金额 txtMoney.setTextColor(Color.parseColor("#5ea98d")); if (VoiceDefault == "notype") { // 如果没有默认类别 spType.setSelection(Integer.parseInt(VoiceSave[5]));// 显示语音识别类别 } else { spType.setSelection(Integer.parseInt(VoiceSave[0]));// 显示类别 } txtMark.setText(textreMark + " " + VoiceSave[2]);// 显示备注 } else { // 收入 // 选择列表初始化 rb2.setChecked(true); spdatalist = itypeDAO.getItypeName(userid); spdata = spdatalist.toArray(new String[spdatalist.size()]);// 在tb_itype中按用户id读取 adapter = new ArrayAdapter(AddPay.this, R.layout.spinner, spdata); // 动态生成收入类型列表 spType.setAdapter(adapter); txtMoney.setText(VoiceSave[1]);// 显示金额 txtMoney.setTextColor(Color.parseColor("#ffff0000")); if (VoiceDefault == "notype") { // 如果没有默认类别 spType.setSelection(Integer.parseInt(VoiceSave[5]));// 显示类别 } else { spType.setSelection(Integer.parseInt(VoiceSave[4]));// 显示类别 } txtMark.setText(textreMark + " " + VoiceSave[2]);// 显示备注 } } } /* * 识别结果处理函数 * * @param VoiceSave[0] 收入类别的值 * * @param VoiceSave[1] 金额的值 * * @param VoiceSave[3] 重复类别的值,仅用于显示提醒 * * @param VoiceSave[4] 支出类别的值 * * @param VoiceSave[5] "语音识别"类别的值 */ private void Recognition(String t) { int mfirst = 100, mend = 0, temp = 0; Boolean ismoney = false, intype = false, outtype = false; Boolean voice_ptype = false, voice_intype = false; String w = "", strmoney = "", inname = "1", outname = "2"; spdatalist = ptypeDAO.getPtypeName(userid); spdatalist2 = itypeDAO.getItypeName(userid); VoiceSave[2] = t; for (int i = 0; i < spdatalist.size(); i++) { // 判断是否包含支出 if (t.indexOf(spdatalist.get(i).toString()) > -1) { type = "pay"; intype = true; inname = spdatalist.get(i).toString(); VoiceSave[0] = Integer.toString(i); // VoiceSave[0]为收入类别的值 } } for (int i = 0; i < voice_pay.length; i++) { // 判断是否包含支出的动词 if (t.indexOf(voice_pay[i]) > -1) { voice_ptype = true; } } for (int i = 0; i < voice_income.length; i++) { // 判断是否包含支出的动词 if (t.indexOf(voice_income[i]) > -1) { voice_intype = true; } } for (int i = 0; i < spdatalist2.size(); i++) { // 判断是否包含收入 if (t.indexOf(spdatalist2.get(i).toString()) > -1) { type = "income"; outtype = true; outname = spdatalist2.get(i).toString(); VoiceSave[4] = Integer.toString(i); // VoiceSave[4]为支出类别的值 } } for (int i = 0; i < number.length; i++) { // 判断是否包含金额,获得开头 if (t.indexOf(number[i]) > -1) { temp = t.indexOf(number[i]); if (temp < mfirst) { mfirst = temp; } } } for (int i = 0; i < money.length; i++) { // 判断是否包含金额,获得结尾 if (t.indexOf(money[i]) > -1) { temp = t.indexOf(money[i]); if (temp > -1 && temp >= mend) { mend = temp; } } } for (int i = 0; i < money2.length; i++) { // 判断是否包含金额,获得结尾 if (t.indexOf(money2[i]) > -1) { temp = t.indexOf(money2[i]); if (temp > -1 && temp >= mend) { mend = temp; } mend = mend + 1; } } if (!(mfirst == 100 || mend == 0)) { // 转换为阿拉伯数字 ismoney = true; strmoney = t.substring(mfirst, mend); // 判断语句是否包含非数字 char[] chs = strmoney.toCharArray(); List num = Arrays.asList(number); List mon = Arrays.asList(money); List mon2 = Arrays.asList(money2); for (int l = 0; l < chs.length; l++) if (!num.contains(String.valueOf(chs[l]))) if (!mon.contains(String.valueOf(chs[l]))) if (!mon2.contains(String.valueOf(chs[l]))) ismoney = false; if (ismoney) { DigitUtil Util = new DigitUtil(); VoiceSave[1] = Integer.toString(Util.parse(strmoney)); // 调用工具类处理汉字的金额 } } if (intype && outtype) { // 如果同时含有收入/支出的类别 if (outname.equals(inname)) { if (ismoney) { if (voice_intype) { type = "income"; dialogShowUtil.dialogShow("rotatebottom", "OK", t, w); } else if (voice_ptype) { type = "pay"; dialogShowUtil.dialogShow("rotatebottom", "OK", t, w); } else { VoiceSave[3] = outname; // VoiceSave[3]为重复类别的值,仅用于显示提醒 dialogShowUtil.dialogShow("shake", "judge", t, w); // 如果含有金额 } } else { w = "提示:\n你的话中没有包含消费或开支的<金额>\n"; dialogShowUtil.dialogShow("shake", "wrong", t, w); } } else { w = "**提示:\n一次只能记录一条记录哦\n"; // 如果含有收入并且支出的类别 dialogShowUtil.dialogShow("shake", "wrong", t, w); } } else { if (!((intype || outtype) || ismoney)) { // 如果不含金额 w = "**提示:\n你的话中没有包含<类别>(" + listToString(spdatalist, ',') + "," + listToString(spdatalist2, ',') + ")\n\n**提示:\n你的话中没有包含消费或开支的<金额>"; dialogShowUtil.dialogShow("shake", "wrong", t, w); } else if ((intype || outtype) && (!ismoney)) { w = "提示:\n你的话中没有包含消费或开支的<金额>\n或者出现多次金额"; dialogShowUtil.dialogShow("shake", "wrong", t, w); } else if ((!(intype || outtype)) && ismoney) { for (int i = 0; i < spdatalist.size(); i++) { // 判断是否包含支出 if ("语音识别".indexOf(spdatalist.get(i).toString()) > -1) { VoiceSave[5] = Integer.toString(i); VoiceSave[3] = "语音识别"; } } w = "**提示:\n你的话中没有包含<(默认)类别>(" + listToString(spdatalist, ',') + ")\n\n\n将会记录为<语音识别>类别,是否依然记录?\n"; dialogShowUtil.dialogShow("shake", "notype", t, w); } else { dialogShowUtil.dialogShow("rotatebottom", "OK", t, w); } } } public String listToString(List list, char separator) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < list.size(); i++) { sb.append(list.get(i)); if (i < list.size() - 1) { sb.append(separator); } } return sb.toString(); } private boolean gotoback() { // 返回 Intent intent = null; type = "pay"; typemode = "add"; Bimp.drr = new ArrayList(); Bimp.smdrr = new ArrayList(); Bimp.bmp = new ArrayList(); Bimp.max = 0; Bimp.flag = 0; if (bundle.containsKey("cwp.frament3")) { intent = new Intent(AddPay.this, MainActivity.class); intent.putExtra("cwp.Fragment", "3");// 设置传递数据 } else if (bundle.containsKey("cwp.search")) { this.setResult(3); this.finish(); return true; } else { intent = new Intent(AddPay.this, MainActivity.class); intent.putExtra("cwp.Fragment", "1"); } intent.putExtra("cwp.id", userid); startActivity(intent); finish(); return true; } public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键 gotoback(); } return super.onKeyDown(keyCode, event); } @Override protected void onDestroy() { if (mDialog != null) { mDialog.dismiss(); } if (dialogBuilder != null) { dialogBuilder.dismiss(); } super.onDestroy(); } @Override protected void onPause() { super.onPause(); // 移除定位请求 mLocationManagerProxy.removeUpdates(this); // 销毁定位 mLocationManagerProxy.destroy(); } protected void onResume() { super.onResume(); SharedPreferences sp = this.getSharedPreferences("preferences", MODE_WORLD_READABLE); CrashApplication myApplaction = (CrashApplication) getApplication(); if ((myApplaction.isLocked) && (sp.getString("gesturepw", "").equals("开"))) {// 判断是否需要跳转到密码界面 Intent intent = new Intent(this, UnlockGesturePasswordActivity.class); startActivity(intent); } } @Override public void onLocationChanged(Location location) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public void onLocationChanged(AMapLocation amapLocation) { if (amapLocation != null && amapLocation.getAMapException().getErrorCode() == 0) { // 定位成功回调信息,设置相关消息 txtAddress.setText(amapLocation.getPoiName() + " [ " + amapLocation.getAddress() + " 区号:" + amapLocation.getCityCode() + " ]"); } else { Log.e("AmapErr", "Location ERR:" + amapLocation.getAMapException().getErrorCode()); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_loacte: // 注意更换定位时间后,需要先将定位请求删除,再进行定位请求 mLocationManagerProxy.removeUpdates(this); int randomTime = mRandom.nextInt(1000); mLocationManagerProxy.requestLocationData( LocationProviderProxy.AMapNetwork, 60 * 1000 + randomTime, 15, this); mLocationManagerProxy.setGpsEnable(false); break; } } protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case 102: if (resultCode == 3 || resultCode == 0) { // for (int i = 0; i < Bimp.drr.size(); i++) { // System.out.println("Bimp.drr" + i + " " + Bimp.drr.get(i)); // System.out.println("list" + i + " " + Bimp.smdrr.get(i)); // } if ((Bimp.drr.size() != 0) && (Bimp.smdrr.size() != 0)) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < Bimp.drr.size(); i++) { sb.append(Bimp.drr.get(i) + ","); } for (int i = 0; i < Bimp.drr.size(); i++) { sb.append(Bimp.smdrr.get(i) + ","); } textphoto = sb.toString().substring(0, sb.length() - 1); initphoto(); } else { textphoto = ""; initphoto(); } break; } } } public static void showVoiveDialog() { dialogShowUtil.dialogShow("rotatebottom", "first", "", ""); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/Author.java ================================================ package com.cwp.cmoneycharge; import cwp.moneycharge.model.ActivityManager; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.KeyEvent; import android.widget.ArrayAdapter; import android.widget.ListView; public class Author extends Activity { Intent intentr; int userid; public Author() { // TODO Auto-generated constructor stub } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.author); ActivityManager.getInstance().addActivity(this); } @Override protected void onStart() { // TODO Auto-generated method stub super.onStart();// 实现基类中的方法// 调用自定义方法显示收入信息 Intent intentr=getIntent(); userid=intentr.getIntExtra("cwp.id",100000001);} public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { //监控/拦截/屏蔽返回键 Intent intent=new Intent(Author.this,About.class); intent.putExtra("cwp.id",userid); startActivity(intent); return true; } return super.onKeyDown(keyCode, event); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/BaseEffects.java ================================================ package com.cwp.cmoneycharge; import android.view.View; import com.nineoldandroids.animation.AnimatorSet; import com.nineoldandroids.view.ViewHelper; /** * Created by lee on 2014/7/30. * * * The MIT License (MIT) * * Copyright (c) 2014 daimajia * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * Acknowledgements daimajia * https://github.com/daimajia */ public abstract class BaseEffects { private static final int DURATION = 1 * 700; protected long mDuration =DURATION ; private AnimatorSet mAnimatorSet; { mAnimatorSet = new AnimatorSet(); } protected abstract void setupAnimation(View view); public void start(View view) { reset(view); setupAnimation(view); mAnimatorSet.start(); } public void reset(View view) { ViewHelper.setPivotX(view, view.getMeasuredWidth() / 2.0f); ViewHelper.setPivotY(view, view.getMeasuredHeight() / 2.0f); } public AnimatorSet getAnimatorSet() { return mAnimatorSet; } public void setDuration(long duration) { this.mDuration = duration; } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/BaseFrament.java ================================================ package com.cwp.cmoneycharge; import android.support.v4.app.Fragment; abstract public class BaseFrament extends Fragment { public void filngtonext() { } public void filngtonpre(){ } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/Config.java ================================================ package com.cwp.cmoneycharge; import com.baidu.voicerecognition.android.VoiceRecognitionConfig; import com.baidu.voicerecognition.android.ui.BaiduASRDigitalDialog; /** * 临时保存参数信息,Demo演示使用 * * @author yangliang02 */ public class Config { /** 对话框样式 */ public static int DIALOG_THEME = BaiduASRDigitalDialog.THEME_BLUE_LIGHTBG; /** 对话框样式 */ public static int pushlogindex = 0; public static int getPushlog() { return pushlogindex; } public static void setPushlog(int pushlog) { pushlogindex = pushlog; } /** * 当前识别语言 */ public static String CURRENT_LANGUAGE = VoiceRecognitionConfig.LANGUAGE_CHINESE; private static int CURRENT_LANGUAGE_INDEX = 0; /** * 当前垂直领域类型 */ public static int CURRENT_PROP = VoiceRecognitionConfig.PROP_INPUT; private static int CURRENT_PROP_INDEX = 0; public static String getCurrentLanguage() { return CURRENT_LANGUAGE; } public static int getCurrentLanguageIndex() { return CURRENT_LANGUAGE_INDEX; } public static void setCurrentLanguageIndex(int index) { switch (index) { case 1: CURRENT_LANGUAGE = VoiceRecognitionConfig.LANGUAGE_CANTONESE; break; case 2: CURRENT_LANGUAGE = VoiceRecognitionConfig.LANGUAGE_ENGLISH; break; default: CURRENT_LANGUAGE = VoiceRecognitionConfig.LANGUAGE_CHINESE; index = 0; break; } CURRENT_LANGUAGE_INDEX = index; } public static int getCurrentPropIndex() { return CURRENT_PROP_INDEX; } public static void setCurrentPropIndex(int index) { switch (index) { case 1: CURRENT_PROP = VoiceRecognitionConfig.PROP_SEARCH; break; case 2: CURRENT_PROP = VoiceRecognitionConfig.PROP_MAP; break; case 3: CURRENT_PROP = VoiceRecognitionConfig.PROP_MUSIC; break; case 4: CURRENT_PROP = VoiceRecognitionConfig.PROP_VIDEO; break; case 5: CURRENT_PROP = VoiceRecognitionConfig.PROP_APP; break; case 6: CURRENT_PROP = VoiceRecognitionConfig.PROP_WEB; break; case 7: CURRENT_PROP = VoiceRecognitionConfig.PROP_HEALTH; break; case 8: CURRENT_PROP = VoiceRecognitionConfig.PROP_SHOPPING; break; case 9: CURRENT_PROP = VoiceRecognitionConfig.PROP_PHONE; break; default: CURRENT_PROP = VoiceRecognitionConfig.PROP_INPUT; index = 0; break; } CURRENT_PROP_INDEX = index; } /** * 播放声音 */ public static boolean PLAY_START_SOUND = true; /** * 播放结束 */ public static boolean PLAY_END_SOUND = true; /** * 对话框提示音 */ public static boolean DIALOG_TIPS_SOUND = true; /** * 显示音量 */ public static boolean SHOW_VOL = true; } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/Constants.java ================================================ package com.cwp.cmoneycharge; public class Constants { /* * 请登录http://developer.baidu.com,注册成为百度开发 * 将对应的ApiKey和SecretKey填写后再测试 */ public static final String API_KEY = "8MAxI5o7VjKSZOKeBzS4XtxO"; public static final String SECRET_KEY = "Ge5GXVdGQpaxOmLzc8fOM8309ATCz9Ha"; } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/CrashApplication.java ================================================ package com.cwp.cmoneycharge; import com.cwp.pattern.LockPatternUtils; import android.app.Application; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; public class CrashApplication extends Application { public boolean isLocked = true; private static CrashApplication mInstance; private LockPatternUtils mLockPatternUtils; LockScreenReceiver receiver ; IntentFilter filter ; public static CrashApplication getInstance() { return mInstance; } @Override public void onCreate() { super.onCreate(); mInstance = this; mLockPatternUtils = new LockPatternUtils(this); receiver = new LockScreenReceiver(); filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_OFF); this.registerReceiver(receiver, filter); CrashHandler crashHandler = CrashHandler.getInstance(); crashHandler.init(this); } public LockPatternUtils getLockPatternUtils() { return mLockPatternUtils; } class LockScreenReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { /* 在这里处理广播 */ if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) { isLocked = true; } } } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/CrashHandler.java ================================================ package com.cwp.cmoneycharge; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.lang.Thread.UncaughtExceptionHandler; import java.lang.reflect.Field; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Timer; import java.util.TimerTask; import com.umeng.fb.example.CustomActivity; import android.content.Context; import android.content.ContextWrapper; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.os.Looper; import android.util.Log; import android.widget.Toast; /** * UncaughtException处理类,当程序发生Uncaught异常的时候,由该类来接管程序,并记录发送错误报告. * * @author way * */ public class CrashHandler implements UncaughtExceptionHandler { StringBuffer sb; String result; private static final String TAG = "CrashHandler"; private static final int MODE_WORLD_READABLE = 0x0001; private Thread.UncaughtExceptionHandler mDefaultHandler;// 系统默认的UncaughtException处理类 private static CrashHandler INSTANCE = new CrashHandler();// CrashHandler实例 private Context mContext;// 程序的Context对象 private Map info = new HashMap();// 用来存储设备信息和异常信息 private SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd-HH-mm-ss");// 用于格式化日期,作为日志文件名的一部分 /** 保证只有一个CrashHandler实例 */ private CrashHandler() { } /** 获取CrashHandler实例 ,单例模式 */ public static CrashHandler getInstance() { return INSTANCE; } /** * 初始化 * * @param context */ public void init(Context context) { mContext = context; ContextWrapper a = (ContextWrapper) mContext.getApplicationContext(); SharedPreferences sp = a.getSharedPreferences("preferences", MODE_WORLD_READABLE); if (sp.getString("sendlog", "").equals("开") || sp.getString("sendlog", "").equals("")) { mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();// 获取系统默认的UncaughtException处理器 Thread.setDefaultUncaughtExceptionHandler(this);// 设置该CrashHandler为程序的默认处理器 } } /** * 当UncaughtException发生时会转入该重写的方法来处理 */ @SuppressWarnings("static-access") public void uncaughtException(Thread thread, Throwable ex) { if (!handleException(ex) && mDefaultHandler != null) { // 如果自定义的没有处理则让系统默认的异常处理器来处理 mDefaultHandler.uncaughtException(thread, ex); } else { try { thread.sleep(3000);// 如果处理了,让程序继续运行3秒再退出,保证文件保存并上传到服务器 } catch (InterruptedException e) { e.printStackTrace(); } } } /** * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成. * * @param ex * 异常信息 * @return true:如果处理了该异常信息;否则返回false. */ public boolean handleException(Throwable ex) { if (ex == null || mContext == null) return false; new Thread() { public void run() { Looper.prepare(); Toast.makeText(mContext, "很抱歉,程序出现异常,即将退出", 0).show(); Toast.makeText(mContext, "请把错误日志反馈给开发者", Toast.LENGTH_LONG) .show(); Looper.loop(); } }.start(); // 收集设备参数信息 collectDeviceInfo(mContext); // 保存日志文件 final File file = saveCrashInfo2File(ex); TimerTask task = new TimerTask() { public void run() { // sendAppCrashReport(mContext, file); sendreport(mContext); } }; Timer timer = new Timer(); timer.schedule(task, 4000); return true; } protected void sendreport(Context mContext) { Intent intent = new Intent(mContext, CustomActivity.class); intent.putExtra("cwp.md", result); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(intent); SysApplication.getInstance().exit(); } public void sendAppCrashReport(Context mContext, File file) { // 通过系统分享发送文件 try { Intent intent = new Intent(); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);// 设置intent的Action属性 intent.setAction(Intent.ACTION_VIEW);// 获取文件file的MIME类型 String type = "text/plain";// 设置intent的data和Type属性。 intent.setDataAndType(Uri.fromFile(file), type);// 跳转 mContext.startActivity(intent); // Toast.makeText(mContext, "很抱歉,程序出现异常,即将退出", 0).show(); } catch (Exception e) { } finally { SysApplication.getInstance().exit(); } } /** * 收集设备参数信息 * * @param context */ public void collectDeviceInfo(Context context) { try { PackageManager pm = context.getPackageManager();// 获得包管理器 PackageInfo pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);// 得到该应用的信息,即主Activity if (pi != null) { String versionName = pi.versionName == null ? "null" : pi.versionName; String versionCode = pi.versionCode + ""; info.put("versionName", versionName); info.put("versionCode", versionCode); } } catch (NameNotFoundException e) { e.printStackTrace(); } Field[] fields = Build.class.getDeclaredFields();// 反射机制 for (Field field : fields) { try { field.setAccessible(true); info.put(field.getName(), field.get("").toString()); Log.d(TAG, field.getName() + ":" + field.get("")); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } } private File saveCrashInfo2File(Throwable ex) { sb = new StringBuffer(); for (Map.Entry entry : info.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); sb.append(key + "=" + value + "\r\n"); } Writer writer = new StringWriter(); PrintWriter pw = new PrintWriter(writer); ex.printStackTrace(pw); Throwable cause = ex.getCause(); // 循环着把所有的异常信息写入writer中 while (cause != null) { cause.printStackTrace(pw); cause = cause.getCause(); } pw.close();// 记得关闭 result = writer.toString(); sb.append(result); // 保存文件 long timetamp = System.currentTimeMillis(); String time = format.format(new Date()); String fileName = "crash-" + time + "-" + timetamp + ".log"; if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { try { File dir = new File(Environment.getExternalStorageDirectory() + "/crash/"); if (!dir.exists()) dir.mkdir(); File file = new File(dir, fileName); FileOutputStream fos = new FileOutputStream(file); fos.write(sb.toString().getBytes()); fos.close(); return file; } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } return null; } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/Description.java ================================================ package com.cwp.cmoneycharge; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.KeyEvent; import cwp.moneycharge.model.ActivityManager; public class Description extends Activity{ Intent intentr; int userid; public Description() { // TODO Auto-generated constructor stub } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.description); ActivityManager.getInstance().addActivity(this); } @Override protected void onStart() { // TODO Auto-generated method stub super.onStart();// 实现基类中的方法// 调用自定义方法显示收入信息 Intent intentr=getIntent(); userid=intentr.getIntExtra("cwp.id",100000001);} public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { //监控/拦截/屏蔽返回键 Intent intent=new Intent(Description.this,About.class); intent.putExtra("cwp.id",userid); startActivity(intent); return true; } return super.onKeyDown(keyCode, event); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/DialogShowUtil.java ================================================ package com.cwp.cmoneycharge; import android.app.Activity; import android.content.Context; import android.view.View; import android.widget.EditText; public class DialogShowUtil { private Context ctx; private Activity act; NiftyDialogBuilder dialogBuilder = null; private Effectstype effect; // 自定义Dialog String[] VoiceSave; static String type; static String VoiceDefault; public DialogShowUtil(Activity act, Context ctx, String[] VoiceSave, String type, String VoiceDefault) { this.ctx = ctx; this.act = act; this.VoiceSave = VoiceSave; this.type = type; this.VoiceDefault = VoiceDefault; } public void dialogShow(String showtype, String style, final String context1, String context2) { dialogBuilder = new NiftyDialogBuilder(ctx, R.style.dialog_untran); // 自定义dialogBuilder switch (showtype) { case "rotatebottom": effect = Effectstype.RotateBottom; break; case "shake": effect = Effectstype.Shake; break; } switch (style) { case "first": dialogBuilder.withTitle("语音记账") // .withTitle(null) no title .withTitleColor("#FFFFFF") // def .withDividerColor("#11000000") // def .withMessage("语音格式:\n早餐在餐厅食了20元。\n\n") // .withMessage(null) no Msg .withMessageColor("#FFFFFF") // def .withIcon(ctx.getResources().getDrawable(R.drawable.icon)) .isCancelableOnTouchOutside(false) // def |// // isCancelable(true) .withDuration(700) // def .withEffect(effect) // def Effectstype.Slidetop .withButton1Text("取消") // def gone .withButton2Text("开始语音") // def gone .setButton1Click(new View.OnClickListener() { @Override public void onClick(View v) { dialogBuilder.dismiss(); } }).setButton2Click(new View.OnClickListener() { @Override public void onClick(View v) { dialogBuilder.dismiss(); ((AddPay) act).VoiceRecognition(); } }).show(); break; case "notype": dialogBuilder.withTitle("识别成功") // .withTitle(null) no title .withTitleColor("#FFFFFF") // def .withDividerColor("#11000000") // def .withMessage("你刚刚说了“ " + context1 + "”\n\n" + context2) // .withMessage(null) no Msg .withMessageColor("#FFFFFF") // def .withIcon(ctx.getResources().getDrawable(R.drawable.icon)) .isCancelableOnTouchOutside(false) // def |// .withDuration(700) // def .withEffect(effect) // def Effectstype.Slidetop .withButton1Text("取消") // def gone .withButton2Text("是") // def gone .setButton1Click(new View.OnClickListener() { @Override public void onClick(View v) { dialogBuilder.dismiss(); } }).setButton2Click(new View.OnClickListener() { @Override public void onClick(View v) { dialogBuilder.dismiss(); VoiceDefault = "notype"; VoiceSave[3] = VoiceSave[3]; dialogShow("shake", "judge", context1, ""); } }).show(); break; case "wrong": dialogBuilder .withTitle("识别失败") // .withTitle(null) no title .withTitleColor("#FFFFFF") // def .withDividerColor("#11000000") // def .withMessage( "你刚刚说了“ " + context1 + "”不符合格式,请再试一次\n\n" + context2) // .withMessage(null) no Msg .withMessageColor("#FFFFFF") // def .withIcon(ctx.getResources().getDrawable(R.drawable.icon)) .isCancelableOnTouchOutside(false) // def | // isCancelable(true) .withDuration(700) // def .withEffect(effect) // def Effectstype.Slidetop .withButton1Text("取消") // def gone .withButton2Text("再次语音") // def gone .setButton1Click(new View.OnClickListener() { @Override public void onClick(View v) { dialogBuilder.dismiss(); } }).setButton2Click(new View.OnClickListener() { @Override public void onClick(View v) { dialogBuilder.dismiss(); ((AddPay) act).VoiceRecognition(); } }).show(); break; case "OK": dialogBuilder.withTitle("识别成功") // .withTitle(null) no title .withTitleColor("#FFFFFF") // def .withDividerColor("#11000000") // def .withMessage("成功!\n你刚刚说了“" + context1 + "”,\n是否确定要记录这条数据?") // .withMessage(null) no Msg .withMessageColor("#FFFFFF") // def .withIcon(ctx.getResources().getDrawable(R.drawable.icon)) .isCancelableOnTouchOutside(false) // def | // isCancelable(true) .withDuration(700) // def .withEffect(effect) // def Effectstype.Slidetop .withButton1Text("取消") // def gone .withButton2Text("确定") // def gone .setButton1Click(new View.OnClickListener() { @Override public void onClick(View v) { dialogBuilder.dismiss(); } }).setButton2Click(new View.OnClickListener() { @Override public void onClick(View v) { dialogBuilder.dismiss(); ((AddPay) act).VoiceSuccess(); } }).show(); break; case "judge": dialogBuilder .withTitle("识别成功") // .withTitle(null) no title .withTitleColor("#FFFFFF") // def .withDividerColor("#11000000") // def .withMessage( "成功!\n你刚刚说了“" + context1 + "”,\n<" + VoiceSave[3] + ">类别需要你请确认该笔是<开支>还是<收入>?\n") // .withMessage(null) no Msg .withMessageColor("#FFFFFF") // def .withIcon(ctx.getResources().getDrawable(R.drawable.icon)) .isCancelableOnTouchOutside(false) // def | // isCancelable(true) .withDuration(700) // def .withEffect(effect) // def Effectstype.Slidetop .withButton1Text("开支") // def gone .withButton2Text("收入") // def gone .setButton1Click(new View.OnClickListener() { @Override public void onClick(View v) { dialogBuilder.dismiss(); type = "pay"; ((AddPay) act).VoiceSuccess(); } }).setButton2Click(new View.OnClickListener() { @Override public void onClick(View v) { dialogBuilder.dismiss(); type = "income"; ((AddPay) act).VoiceSuccess(); } }).show(); break; case "quit": dialogBuilder.withTitle("退出程序") // .withTitle(null) no title .withTitleColor("#FFFFFF") // def .withDividerColor("#11000000") // def .withMessage("是否要退出程序?\n\n") // .withMessage(null) no Msg .withMessageColor("#FFFFFF") // def .withIcon(ctx.getResources().getDrawable(R.drawable.icon)) .isCancelableOnTouchOutside(false) // def | // isCancelable(true) .withDuration(700) // def .withEffect(effect) // def Effectstype.Slidetop .withButton1Text("取消") // def gone .withButton2Text("退出") // def gone .setButton1Click(new View.OnClickListener() { @Override public void onClick(View v) { dialogBuilder.dismiss(); } }).setButton2Click(new View.OnClickListener() { @Override public void onClick(View v) { SysApplication.getInstance().exit(); } }).show(); break; } } public static String dialoggettype() { return type; } public static String dialogVoiceDefault() { return VoiceDefault; } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/DigitUtil.java ================================================ package com.cwp.cmoneycharge; /** * @author loiy * www.agrilink.cn * 2012.11.30 */ import java.util.Hashtable; public class DigitUtil { /** * 汉字中的数字字符 */ private static final Character[] SCDigits = { '零', '一', '二', '两', '三', '四', '五', '六', '七', '八', '九' }; /** * 阿拉伯数字 */ private static final Character[] araDigits = { '0', '1', '2', '2', '3', '4', '5', '6', '7', '8', '9' }; /** * 阿拉伯数字 */ private static Hashtable araHash = new Hashtable(); /** * 阿拉伯数字 */ private static Hashtable YWQBSHash = new Hashtable(); static { for (int i = 0; i < SCDigits.length; i++) { araHash.put(SCDigits[i], araDigits[i]); } YWQBSHash.put('亿', 100000000); YWQBSHash.put('万', 10000); YWQBSHash.put('千', 1000); YWQBSHash.put('百', 100); YWQBSHash.put('十', 10); } /** * @param remain * 剩下多少个字符 * @param curchar * 当前分析的字符 */ private static int ywqbs(int num, Boolean bool, int no, int remain, char curchar, char lastshow) { if (num == 0) { num += no; return num; } else { String numString = String.valueOf(num); // 将num转换成String String last = numString.substring(numString.length() - 1, numString.length()); // 获取最后一个字符 String exceptlast = numString.substring(0, numString.length() - 1); // 获取除了最后一个字符所有字符串 if (exceptlast.length() == 0) { // 说明num是个位值 num = Integer.parseInt(last) * no; return num; } else { /***** 针对有连续的这些字符[十百千万亿] start *****/ if (bool && YWQBSHash.get(curchar) > YWQBSHash.get(lastshow)) { // 说明上个字符属于[十百千万亿] num *= no; return num; } /***** 针对有连续的这些字符[十百千万亿] end *****/ /***** 分析到最后一个字符 start *****/ /**** 针对这种情况(一千二百二十一万) ****/ if (remain == 1 && YWQBSHash.get(curchar) > YWQBSHash.get(lastshow)) { num *= YWQBSHash.get(curchar); return num; } /**** 针对这种情况(一千二百二十一万) ****/ /***** 分析到最后一个字符 end *****/ /***** last如果为0 start *****/ if (last.equals("0")) { // 循环到最后一位字符,last等于0 last = "1"; // } /***** last如果为0 end *****/ exceptlast = exceptlast + "0"; // 缺少最后一位,需要补上 num = Integer.parseInt(exceptlast) + Integer.parseInt(last) * no; return num; } } } public static int parse(String word) { int num = 0; char lastchar = '一'; // 上次字符,字符特指[十百千万亿],默认随便填写一个'一' char lastshow = '一'; // 上次出现的字符,字符特指[十百千万亿],默认随便填写一个'一' char[] ch = word.toCharArray(); Boolean bool = false; // 是否连续出现[十百千万亿] for (int i = 0; i < ch.length; i++) { Character find = araHash.get(ch[i]);// 获取阿拉伯数字数组[1,2,3...] if (find != null) { num += Integer.parseInt(String.valueOf(find.charValue())); bool = false; lastchar = '一'; // 恢复到默认值 continue; } else if (ch[i] == '十') { num = ywqbs(num, bool, 10, ch.length - i, ch[i], lastshow); bool = true; lastchar = '十'; lastshow = '十'; } else if (ch[i] == '千') { num = ywqbs(num, bool, 1000, ch.length - i, ch[i], lastshow); bool = true; lastchar = '千'; lastshow = '千'; } else if (ch[i] == '百') { num = ywqbs(num, bool, 100, ch.length - i, ch[i], lastshow); bool = true; lastchar = '百'; lastshow = '百'; } else if (ch[i] == '万') { num = ywqbs(num, bool, 10000, ch.length - i, ch[i], lastshow); bool = true; lastchar = '万'; lastshow = '万'; } } ch = null; return num; } // public static void main(String args[]) { // String wordes[] = { // "一千二百二十一万", // "一千二百二十一", // "一千零十", // "一万零一百", // "一千零十一", // "一万零一百十一", // "一千二百十九", // "一千万", // "五十五" // }; // for(int i = 0; i < wordes.length; i++) { // DigitUtil t = new DigitUtil(); // int num = t.parse(wordes[i]); // System.out.println(wordes[i] + " " + num); // } // } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/Effectstype.java ================================================ package com.cwp.cmoneycharge; import com.cwp.cmoneycharge.RotateBottom; import com.cwp.cmoneycharge.Shake; /** * Created by lee on 2014/7/30. */ public enum Effectstype { Slidetop(SlideTop.class), RotateBottom(RotateBottom.class), Shake(Shake.class); private Class effectsClazz; private Effectstype(Class mclass) { effectsClazz = mclass; } public BaseEffects getAnimator() { try { return (BaseEffects) effectsClazz.newInstance(); } catch (Exception e) { throw new Error("Can not init animatorClazz instance"); } } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/FragmentPage1.java ================================================ package com.cwp.cmoneycharge; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import com.cwp.chart.MyAdspter; import com.cwp.cmoneycharge.AddPay; import com.cwp.cmoneycharge.ModifyInP; import com.cwp.cmoneycharge.R; import cwp.moneycharge.dao.IncomeDAO; import cwp.moneycharge.dao.ItypeDAO; import cwp.moneycharge.dao.PayDAO; import cwp.moneycharge.dao.PtypeDAO; import cwp.moneycharge.model.ActivityManager; import cwp.moneycharge.model.Tb_income; import cwp.moneycharge.model.Tb_pay; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Toast; public class FragmentPage1 extends BaseFrament { int userid; Button baddpay; TextView income_amount; TextView expense_amount; PtypeDAO ptypeDAO; ItypeDAO itypeDAO; String nodata = " 还木有数据,赶紧买买买吧"; public void Pay() { // TODO Auto-generated constructor stub } ListView lvinfo;// 创建ListView对象 String strType = "";// 创建字符串,记录管理类型 private MyAdspter adapter; private int defaultYear; private int defaultMonth; private int defaultDay; private String dmonth; private String dday; private String date2; private String date1; private RelativeLayout lvnodata; private TextView lvtime; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_1, null); } public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); lvinfo = (ListView) getView().findViewById(R.id.lvoutaccountinfo);// 获取布局文件中的ListView组件 baddpay = (Button) getView().findViewById(R.id.add_expense_quickly_btn);// 添加按钮 income_amount = (TextView) getView().findViewById(R.id.income_amount); expense_amount = (TextView) getView().findViewById(R.id.expense_amount); lvtime = (TextView) getView().findViewById(R.id.lvtime); lvnodata = (RelativeLayout) getView().findViewById(R.id.lvnodata); ptypeDAO = new PtypeDAO(getActivity().getApplicationContext()); itypeDAO = new ItypeDAO(getActivity().getApplicationContext()); } @Override public void onStart() { // TODO Auto-generated method stub super.onStart();// 实现基类中的方法// 调用自定义方法显示收入信息 Intent intentr = getActivity().getIntent(); userid = intentr.getIntExtra("cwp.id", 100000001); Showamount(); ShowInfo(R.id.btnoutinfo); lvinfo.setOnItemClickListener(new OnItemClickListener()// 为ListView添加项单击事件 { // 覆写onItemClick方法 @Override public void onItemClick(AdapterView parent, View view, int position, long id) { TextView txno = (TextView) view.findViewById(R.id.no); TextView txkind = (TextView) view.findViewById(R.id.kind); String strtype = ((String) txkind.getText()).substring(1, ((String) txkind.getText()).indexOf(']')).trim();// 从收入信息中截取收支类型 String strno = (String) txno.getText(); // 从信息中截取收支编号 Intent intent = new Intent(getActivity(), AddPay.class);// 创建Intent对象 if (strtype.equals("收入")) { intent.putExtra("cwp.message", new String[] { strno, "btnininfo" });// 设置传递数据 } if (strtype.equals("支出")) { intent.putExtra("cwp.message", new String[] { strno, "btnoutinfo" });// 设置传递数据 } intent.putExtra("cwp.id", userid); startActivity(intent);// 执行Intent操作 } }); baddpay.setOnClickListener(new OnClickListener() { // 记一笔 @Override public void onClick(View arg0) { // Intent intent = new Intent(getActivity(), AddIncome.class); Intent intent = new Intent(getActivity(), AddPay.class);// 创建Intent对象 intent.putExtra("cwp.id", userid); intent.putExtra("keyboard", "true"); startActivity(intent); } }); } private void Showamount() { PayDAO paydao = new PayDAO(getActivity().getApplicationContext());// 创建PayDAO对象 IncomeDAO incomedao = new IncomeDAO(getActivity() .getApplicationContext());// 创建IncomeDAO对象 // 获取所有收入信息,并存储到List泛型集合中 Double incomeamount = incomedao.getamountData(userid); Double payamount = paydao.getamountData(userid); income_amount.setText("¥ " + incomeamount); expense_amount.setText("¥ " + payamount); } private void ShowInfo(int intType) {// 用来根据传入的管理类型,显示相应的信息 strType = "btnoutinfo";// 为strType变量赋值 PayDAO paydao = new PayDAO(getActivity().getApplicationContext());// 创建PayDAO对象 // 获取所有收入信息,并存储到List泛型集合中 List listinfos = paydao.getScrollData(userid, 0, (int) paydao.getCount(userid)); IncomeDAO incomedao = new IncomeDAO(getActivity() .getApplicationContext());// 创建IncomeDAO对象 final Calendar c = Calendar.getInstance();// 获取当前系统日期 defaultYear = c.get(Calendar.YEAR);// 获取年份 defaultMonth = c.get(Calendar.MONTH) + 1;// 获取月份 defaultDay = c.get(Calendar.DAY_OF_MONTH);// 获取天数 lvtime.setText("今天是" + defaultYear + "年" + defaultMonth + "月" + defaultDay + "日"); if (defaultMonth < 10) { dmonth = "0" + Integer.toString(defaultMonth); } else { dmonth = Integer.toString(defaultMonth); } if (defaultDay < 10) { dday = "0" + Integer.toString(defaultDay); } else { dday = Integer.toString(defaultDay); } date2 = Integer.toString(defaultYear) + "-" + dmonth + "-" + dday; date1 = Integer.toString(defaultYear) + "-" + dmonth + "-" + dday; List listinfos2 = incomedao.getScrollDataTotal(userid, 0, 0, date1, date2); // System.out.println("listinfos2" + listinfos2.size()); List> list = new ArrayList>(); if (listinfos2.size() == 0) { lvnodata.setVisibility(View.VISIBLE); lvinfo.setVisibility(View.GONE); } else { lvnodata.setVisibility(View.GONE); lvinfo.setVisibility(View.VISIBLE); for (Tb_income tb_income : listinfos2) {// 遍历List泛型集合 // 将收入相关信息组合成一个字符串,存储到字符串数组的相应位置 if (tb_income.getKind().equals("收入")) { // 收入 Map map = new HashMap(); map.put("img", itypeDAO.getOneImg(userid, tb_income.getType())); map.put("no", tb_income.getNo() + ""); map.put("kind", "[" + tb_income.getKind() + "]"); map.put("money", "¥ " + tb_income.getMoney2() + "元"); map.put("title", itypeDAO.getOneName(userid, tb_income.getType())); map.put("info", tb_income.getTime()); list.add(map); } else { // 支出 Map map = new HashMap(); map.put("img", ptypeDAO.getOneImg(userid, tb_income.getType())); map.put("no", tb_income.getNo() + ""); map.put("kind", "[" + tb_income.getKind() + "]"); map.put("money", "¥ " + tb_income.getMoney2() + "元"); map.put("title", ptypeDAO.getOneName(userid, tb_income.getType())); map.put("info", tb_income.getTime()); list.add(map); } } adapter = new MyAdspter(getActivity(), list, false); lvinfo.setAdapter(adapter);// 为ListView列表设置数据源 } } @Override public void filngtonext() { FragmentPage2.clickMyfeedBtn(); } @Override public void filngtonpre() { } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/FragmentPage2.java ================================================ package com.cwp.cmoneycharge; import com.cwp.cmoneycharge.R; import android.content.Context; import android.content.Intent; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.widget.ArrayAdapter; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.PopupWindow.OnDismissListener; public class FragmentPage2 extends Fragment implements OnClickListener { static int userid; private static FragmentPage1 fragmentPage1; private FragmentPage2 fragmentPage2; private static FragmentPage3 fragmentPage3; private static FragmentPage4 fragmentPage4; // 定义布局对象 private static FrameLayout friendfeedFl; private static FrameLayout myfeedFl; private static FrameLayout homeFl; private static FrameLayout moreFl; // 定义图片组件对象 private static ImageView friendfeedIv; private static ImageView myfeedIv; private static ImageView homeIv; private static ImageView moreIv; // 定义按钮图片组件 private ImageView toggleImageView, plusImageView; // 定义PopupWindow private PopupWindow popWindow; private LinearLayout popWinLayout; // 定义pop组件 private LinearLayout pop_voiceView; private LinearLayout pop_quickView; int value = 0; private LinearLayout pop_photoView; static FragmentActivity act; public FragmentPage2(FragmentActivity activity) { act = activity; } public FragmentPage2() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_2, null); } public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Intent intentr = getActivity().getIntent(); userid = intentr.getIntExtra("cwp.id", 100000001); initView(); initData(); switch (value) { case 0: clickFriendfeedBtn(); break; case 1: clickFriendfeedBtn(); break; case 2: clickMyfeedBtn(); break; case 3: clickHomeBtn(); break; case 4: clickMoreBtn(); break; } } /** * 初始化组件 */ public void initView() { value = MainActivity.getValueFM(); // 实例化布局对象 friendfeedFl = (FrameLayout) getActivity().findViewById( R.id.layout_friendfeed); myfeedFl = (FrameLayout) getActivity().findViewById(R.id.layout_myfeed); homeFl = (FrameLayout) getActivity().findViewById(R.id.layout_home); moreFl = (FrameLayout) getActivity().findViewById(R.id.layout_more); // 实例化图片组件对象 friendfeedIv = (ImageView) getActivity().findViewById( R.id.image_friendfeed); myfeedIv = (ImageView) getActivity().findViewById(R.id.image_myfeed); homeIv = (ImageView) getActivity().findViewById(R.id.image_home); moreIv = (ImageView) getActivity().findViewById(R.id.image_more); // 实例化按钮图片组件 toggleImageView = (ImageView) getActivity().findViewById( R.id.toggle_btn); plusImageView = (ImageView) getActivity().findViewById(R.id.plus_btn); } private void initData() { // 给布局对象设置监听 friendfeedFl.setOnClickListener(this); myfeedFl.setOnClickListener(this); homeFl.setOnClickListener(this); moreFl.setOnClickListener(this); // 给按钮图片设置监听 toggleImageView.setOnClickListener(this); } @Override public void onClick(View v) { // System.out.println("我按了" + v.getId()); switch (v.getId()) { // 点击动态按钮 case R.id.layout_friendfeed: clickFriendfeedBtn(); break; // 点击与我相关按钮 case R.id.layout_myfeed: clickMyfeedBtn(); break; // 点击我的空间按钮 case R.id.layout_home: clickHomeBtn(); break; // 点击更多按钮 case R.id.layout_more: clickMoreBtn(); break; // 点击中间按钮 case R.id.toggle_btn: clickToggleBtn(); break; // 点击中间按钮 case R.id.pop_voice: clickPop_voiceBtn(); break; case R.id.pop_quick: clickPop_quickBtn(); break; case R.id.pop_photo: clickPop_photoViewBtn(); break; } } private void clickPop_photoViewBtn() { Intent intent = new Intent(getActivity(), AddPay.class);// 创建Intent对象 intent.putExtra("cwp.id", userid); intent.putExtra("cwp.photo", "");// 设置传递数据 startActivity(intent); } /** * 显示PopupWindow弹出菜单 */ private void showPopupWindow(View parent) { DisplayMetrics dm = parent.getResources().getDisplayMetrics(); int w_screen = dm.widthPixels; int h_screen = dm.heightPixels; // System.out.println("你的设备w_screen:" + w_screen + " h_screen:" + // h_screen); if (popWindow == null) { LayoutInflater layoutInflater = (LayoutInflater) getActivity() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = layoutInflater.inflate(R.layout.popwindow_layout, null); popWinLayout = (LinearLayout) view.findViewById(R.id.popwindow); // 创建一个PopuWidow对象 float radiowith = w_screen / 480.0f; float radioheight = h_screen / 800.0f; popWindow = new PopupWindow(view, (int) (popWinLayout.getLayoutParams().width), h_screen / 4); } // 使其聚集 ,要想监听菜单里控件的事件就必须要调用此方法 popWindow.setFocusable(true); pop_voiceView = (LinearLayout) popWinLayout .findViewById(R.id.pop_voice); pop_quickView = (LinearLayout) popWinLayout .findViewById(R.id.pop_quick); pop_photoView = (LinearLayout) popWinLayout .findViewById(R.id.pop_photo); pop_voiceView.setOnClickListener(this); pop_quickView.setOnClickListener(this); pop_photoView.setOnClickListener(this); // 设置允许在外点击消失 popWindow.setOutsideTouchable(true); // 设置背景,这个是为了点击“返回Back”也能使其消失,并且并不会影响你的背景 popWindow.setBackgroundDrawable(new BitmapDrawable()); // 设置菜单显示的位置 int xPos = (w_screen - popWinLayout.getLayoutParams().width) / 2; popWindow.showAsDropDown(parent, xPos, 12); // popWindow.showAsDropDown(parent, Gravity.CENTER, 0); // 监听菜单的关闭事件 popWindow.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss() { // 改变显示的按钮图片为正常状态 changeButtonImage(); } }); // 监听触屏事件 popWindow.setTouchInterceptor(new OnTouchListener() { public boolean onTouch(View view, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_OUTSIDE) { // 改变显示的按钮图片为正常状态 changeButtonImage(); } return false; } }); } /** * 点击了“动态”按钮 */ public static void clickFriendfeedBtn() { // 实例化Fragment页面 fragmentPage1 = new FragmentPage1(); // 得到Fragment事务管理器 FragmentTransaction fragmentTransaction; fragmentTransaction = act.getSupportFragmentManager() .beginTransaction(); // 替换当前的页面 fragmentTransaction.replace(R.id.frame_content, fragmentPage1); // 事务管理提交 fragmentTransaction.commit(); friendfeedFl.setSelected(true); friendfeedIv.setSelected(true); myfeedFl.setSelected(false); myfeedIv.setSelected(false); homeFl.setSelected(false); homeIv.setSelected(false); moreFl.setSelected(false); moreIv.setSelected(false); } /** * 点击了“与我相关”按钮 */ public static void clickMyfeedBtn() { // Intent intentr = new Intent(getActivity(), PayData.class); Intent intentr = new Intent(act, PayChart.class); intentr.putExtra("cwp.id", userid); intentr.putExtra("type", 0); act.startActivity(intentr); act.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); } /** * 点击了“我的空间”按钮 */ public static void clickHomeBtn() { // 实例化Fragment页面 fragmentPage3 = new FragmentPage3(); // 得到Fragment事务管理器 FragmentTransaction fragmentTransaction = act .getSupportFragmentManager().beginTransaction(); // 替换当前的页面 fragmentTransaction.replace(R.id.frame_content, fragmentPage3); // 事务管理提交 fragmentTransaction.commit(); friendfeedFl.setSelected(false); friendfeedIv.setSelected(false); myfeedFl.setSelected(false); myfeedIv.setSelected(false); homeFl.setSelected(true); homeIv.setSelected(true); moreFl.setSelected(false); moreIv.setSelected(false); } /** * 点击了“更多”按钮 */ public static void clickMoreBtn() { // 实例化Fragment页面 fragmentPage4 = new FragmentPage4(); // 得到Fragment事务管理器 FragmentTransaction fragmentTransaction = act .getSupportFragmentManager().beginTransaction(); // 替换当前的页面 fragmentTransaction.replace(R.id.frame_content, fragmentPage4); // 事务管理提交 fragmentTransaction.commit(); friendfeedFl.setSelected(false); friendfeedIv.setSelected(false); myfeedFl.setSelected(false); myfeedIv.setSelected(false); homeFl.setSelected(false); homeIv.setSelected(false); moreFl.setSelected(true); moreIv.setSelected(true); } private void clickPop_voiceBtn() { Intent intent = new Intent(getActivity(), AddPay.class);// 创建Intent对象 intent.putExtra("cwp.id", userid); intent.putExtra("cwp.voice", "");// 设置传递数据 startActivity(intent); } private void clickPop_quickBtn() { Intent intent = new Intent(getActivity(), AddPay.class);// 创建Intent对象 intent.putExtra("cwp.id", userid); intent.putExtra("keyboard", "true"); startActivity(intent); } /** * 点击了中间按钮 */ private void clickToggleBtn() { showPopupWindow(plusImageView); // 改变按钮显示的图片为按下时的状态 plusImageView.setImageResource(R.drawable.toolbar_plusback); toggleImageView.setImageResource(R.drawable.toolbar_btn_pressed); } /** * 改变显示的按钮图片为正常状态 */ private void changeButtonImage() { plusImageView.setImageResource(R.drawable.toolbar_plus); toggleImageView.setImageResource(R.drawable.toolbar_btn_normal); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/FragmentPage3.java ================================================ package com.cwp.cmoneycharge; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import com.cwp.chart.FoldingLayout; import com.cwp.chart.PullToRefreshView; import com.cwp.chart.PullToRefreshView.OnFooterRefreshListener; import com.cwp.chart.PullToRefreshView.OnHeaderRefreshListener; import com.cwp.chart.RiseNumberTextView; import cwp.moneycharge.dao.IncomeDAO; import cwp.moneycharge.dao.ItypeDAO; import cwp.moneycharge.dao.PayDAO; import cwp.moneycharge.dao.PtypeDAO; import cwp.moneycharge.model.KindData; import cwp.moneycharge.model.Tb_income; import cwp.moneycharge.model.Tb_pay; import android.annotation.SuppressLint; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.net.ParseException; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.TranslateAnimation; import android.view.animation.Animation.AnimationListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.ExpandableListView.OnChildClickListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; @SuppressLint("InflateParams") public class FragmentPage3 extends BaseFrament implements OnHeaderRefreshListener, OnFooterRefreshListener { TextView sum_pay, sum_income, sum_title, February_date; ListView scrollview; ArrayAdapter arrayAdapter = null;// 创建ArrayAdapter对象 String[] strInfos = null;// 定义字符串数组,用来存储收入信息 Integer[] newStr = null; private PullToRefreshView mPullToRefreshView; PayDAO payDAO; IncomeDAO incomeDAO; List list_pay; List list_income; List KindDatap; PtypeDAO ptypeDAO; ItypeDAO itypeDAO; static int defaultYear; int defaultMonth; int defaultDay; int userid, height; String dmonth, dday, date1, date2; List list2; Animation pushup, pushout; RelativeLayout searchButton; LinearLayout frag3, fragall; private ExpandableListView elv; private ArrayList> groups; private ArrayList>> childs; private ArrayList> child1; private RiseNumberTextView sum_total; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_3, null); } public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); final Calendar c = Calendar.getInstance();// 获取当前系统日期 defaultYear = c.get(Calendar.YEAR);// 获取年份 defaultMonth = c.get(Calendar.MONTH) + 1;// 获取月份 findViews(); initData(0); elv.setOnChildClickListener(new OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View view, int groupPosition, int childPosition, long id) { TextView txno = (TextView) view.findViewById(R.id.no); TextView txkind = (TextView) view.findViewById(R.id.kind); String strtype = ((String) txkind.getText()).substring(1, ((String) txkind.getText()).indexOf(']')).trim();// 从收入信息中截取收支类型 String strno = (String) txno.getText(); // 从信息中截取收支编号 Intent intent = new Intent(getActivity(), AddPay.class);// 创建Intent对象 if (strtype.equals("收入")) { intent.putExtra("cwp.message", new String[] { strno, "btnininfo" });// 设置传递数据 } if (strtype.equals("支出")) { intent.putExtra("cwp.message", new String[] { strno, "btnoutinfo" });// 设置传递数据 } intent.putExtra("cwp.id", userid); intent.putExtra("cwp.frament3", "3"); startActivity(intent);// 执行Intent操作 return false; } }); } private void initData(int newyear) { int pay_sum = 0; int income_sum = 0; payDAO = new PayDAO(getActivity()); ptypeDAO = new PtypeDAO(getActivity()); incomeDAO = new IncomeDAO(getActivity()); itypeDAO = new ItypeDAO(getActivity()); switch (newyear) { case 1: defaultYear++; break; case -1: defaultYear--; break; } Intent intentr = getActivity().getIntent(); userid = intentr.getIntExtra("cwp.id", 100000001); sum_title.setText(Integer.toString(defaultYear) + "年结余"); list_income = incomeDAO.getScrollData(userid, 0, // 取每年的收入数据 (int) incomeDAO.getCount(userid), Integer.toString(defaultYear) + "-01-01", Integer.toString(defaultYear) + "-12-31"); list_pay = payDAO.getScrollData(userid, 0, // 取每年的支出数据 (int) payDAO.getCount(userid), Integer.toString(defaultYear) + "-01-01", Integer.toString(defaultYear) + "-12-31"); Integer[] str = new Integer[list_income.size() + list_pay.size()]; groups = new ArrayList>(); childs = new ArrayList>>(); if (list_income.size() == 0) { // 处理listview sum_income.setText("¥ 0.0"); } if (list_pay.size() == 0) { sum_pay.setText("¥ 0.0"); } if ((list_income.size() == 0) && (list_pay.size() == 0)) { sum_total.setText("¥ 0.0"); Map group1 = new HashMap(); group1.put("isnodata", "true"); groups.add(group1); } else { int n = 0; for (Tb_pay tb_pay : list_pay) {// 遍历List泛型集合 // 将收入相关信息组合成一个字符串,存储到字符串数组的相应位置 pay_sum += tb_pay.getMoney(); str[n] = Integer.parseInt(tb_pay.getTime().substring(5, 7)); n++; } for (Tb_income tb_income : list_income) {// 遍历List泛型集合 // 将收入相关信息组合成一个字符串,存储到字符串数组的相应位置 income_sum += tb_income.getMoney(); str[n] = Integer.parseInt(tb_income.getTime().substring(5, 7)); n++; } sum_pay.setText("¥ " + String.valueOf(pay_sum)); sum_income.setText("¥ " + String.valueOf(income_sum)); final int ip_sum = income_sum - pay_sum; sum_total.withNumber(ip_sum); sum_total.start(); list2 = new ArrayList(); for (int i = 0; i < str.length; i++) { if (!list2.contains(str[i])) {// 如果数组 list 不包含当前项,则增加该项到数组中 list2.add(str[i]); } } newStr = list2.toArray(new Integer[1]); Arrays.sort(newStr); for (int i = newStr.length; i > 0; i--) { // 循环获取数据 int sum = 0; if (newStr[i - 1] < 10) { dmonth = "0" + Integer.toString(newStr[i - 1]); } else { dmonth = Integer.toString(newStr[i - 1]); } date1 = Integer.toString(defaultYear) + "-" + dmonth + "-01"; date2 = Integer.toString(defaultYear) + "-" + dmonth + "-31"; List listinfos2 = incomeDAO.getScrollDataTotal( userid, 0, // 取每个月的数据 (int) incomeDAO.getCount(userid), date1, date2); if (listinfos2.size() != 0) { child1 = new ArrayList>(); for (Tb_income tb_income : listinfos2) {// 遍历List泛型集合 // 将收入相关信息组合成一个字符串,存储到字符串数组的相应位置 if (tb_income.getKind().equals("收入")) { // 收入 // 准备第一个一级列表中的二级列表数据:两个二级列表,分别显示"childData1"和"childData2" Map Data1 = new HashMap(); Data1.put("img", String.valueOf(itypeDAO.getOneImg( userid, tb_income.getType()))); Data1.put("no", tb_income.getNo() + ""); Data1.put("kind", "[" + tb_income.getKind() + "]"); Data1.put("money", "¥ " + tb_income.getMoney2() + "元"); Data1.put( "title", itypeDAO.getOneName(userid, tb_income.getType())); Data1.put("info", tb_income.getTime()); Data1.put("date", gofordate(tb_income.getTime())); child1.add(Data1); sum += tb_income.getMoney(); } else { // 支出 Map Data1 = new HashMap(); Data1.put("img", String.valueOf(ptypeDAO.getOneImg( userid, tb_income.getType()))); Data1.put("no", tb_income.getNo() + ""); Data1.put("kind", "[" + tb_income.getKind() + "]"); Data1.put("money", "¥ " + tb_income.getMoney2() + "元"); Data1.put( "title", ptypeDAO.getOneName(userid, tb_income.getType())); Data1.put("info", tb_income.getTime()); Data1.put("date", gofordate(tb_income.getTime())); child1.add(Data1); sum -= tb_income.getMoney(); } } // 准备一级列表中显示的数据:2个一级列表,分别显示"group1"和"group2" Map group1 = new HashMap(); group1.put("day", (newStr[i - 1]) + "月"); group1.put( "time", incomeDAO.gettime(defaultYear, (newStr[i - 1]), 0, true, false).substring(5, 10) + " ~ " + incomeDAO.gettime(defaultYear, (newStr[i - 1]), 0, false, true) .substring(5, 10)); group1.put("money", String.valueOf(sum)); groups.add(group1); // 用一个list对象保存所有的二级列表数据 childs.add(child1); } } } ExpandableAdapter viewAdapter = new ExpandableAdapter(getActivity(), groups, childs); elv.setGroupIndicator(null); elv.setAdapter(viewAdapter); } static String gofordate(String s) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date date = null; try { date = format.parse(s); } catch (java.text.ParseException e) { e.printStackTrace(); } String[] weekDays = { "周日", "周一", "周二", "周三", "周四", "周五", "周六" }; Calendar cal = Calendar.getInstance(); cal.setTime(date); int w = cal.get(Calendar.DAY_OF_WEEK) - 1; if (w < 0) w = 0; System.out.println("date" + date + " weekDays " + weekDays[w]); return weekDays[w]; } private void findViews() { elv = (ExpandableListView) getActivity().findViewById( R.id.expandableListView); sum_title = (TextView) getActivity().findViewById(R.id.sum_title); sum_total = (RiseNumberTextView) getActivity().findViewById( R.id.sum_total); // 设置动画播放时间 sum_total.setDuration(1000); // 开始播放动画 sum_pay = (TextView) getActivity().findViewById(R.id.sum_pay); sum_income = (TextView) getActivity().findViewById(R.id.sum_income); mPullToRefreshView = (PullToRefreshView) getActivity().findViewById( R.id.main_pull_refresh_view); mPullToRefreshView.setOnHeaderRefreshListener(this); mPullToRefreshView.setOnFooterRefreshListener(this); pushup = AnimationUtils.loadAnimation(getActivity(), R.anim.push_up_in); pushout = AnimationUtils.loadAnimation(getActivity(), R.anim.push_up_out); searchButton = (RelativeLayout) getActivity().findViewById( R.id.search_button); // 搜索控件 frag3 = (LinearLayout) getActivity().findViewById(R.id.frag3); // 搜索控件 fragall = (LinearLayout) getActivity().findViewById(R.id.fragall); // 搜索控件 searchButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { height = frag3.getHeight(); TranslateAnimation animation = new TranslateAnimation(0, 0, 0, -height); animation.setDuration(500); animation.setFillAfter(true); animation.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { Intent intent = new Intent(); intent.setClass(getActivity(), SearchActivity.class); startActivityForResult(intent, 100); getActivity().overridePendingTransition( R.anim.animation_2, R.anim.animation_1); } }); fragall.startAnimation(animation); } }); } // 自定义的ExpandListAdapter class ExpandableAdapter extends BaseExpandableListAdapter { private Context context; List> groups; List>> childs; /* * 构造函数: 参数1:context对象 参数2:一级列表数据源 参数3:二级列表数据源 */ public ExpandableAdapter(Context context, List> groups, List>> childs) { this.groups = groups; this.childs = childs; this.context = context; } @Override public Object getChild(int groupPosition, int childPosition) { return childs.get(groupPosition).get(childPosition); } @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } // 获取二级列表的View对象 @SuppressWarnings("unchecked") @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { LayoutInflater layoutInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); // 获取二级列表对应的布局文件, 并将其各元素设置相应的属性 LinearLayout linearLayout = (LinearLayout) layoutInflater.inflate( R.layout.list, null); RelativeLayout search_img2 = (RelativeLayout) linearLayout .findViewById(R.id.search_img2); RelativeLayout titlebar = (RelativeLayout) linearLayout .findViewById(R.id.titlebar); ImageView search_img = (ImageView) linearLayout .findViewById(R.id.search_img); TextView search_date = (TextView) linearLayout .findViewById(R.id.search_date); TextView search_date2 = (TextView) linearLayout .findViewById(R.id.search_date2); TextView no = (TextView) linearLayout.findViewById(R.id.no); TextView kind = (TextView) linearLayout.findViewById(R.id.kind); TextView title = (TextView) linearLayout.findViewById(R.id.title); TextView money = (TextView) linearLayout.findViewById(R.id.money); titlebar.setVisibility(View.GONE); search_img2.setVisibility(View.VISIBLE); title.setText(((Map) getChild(groupPosition, childPosition)).get("title")); no.setText(((Map) getChild(groupPosition, childPosition)).get("no")); kind.setText(((Map) getChild(groupPosition, childPosition)).get("kind")); money.setText(((Map) getChild(groupPosition, childPosition)).get("money")); search_date2.setText(((Map) getChild(groupPosition, childPosition)).get("date")); search_date.setText(((Map) getChild(groupPosition, childPosition)).get("info").substring(8, 10)); search_img.setImageResource(Integer .parseInt(((Map) getChild(groupPosition, childPosition)).get("img"))); if (((Map) getChild(groupPosition, childPosition)) .get("kind").equals("[收入]")) { money.setTextColor(Color.parseColor("#ffff0000")); } else { money.setTextColor(Color.parseColor("#5ea98d")); } return linearLayout; } @Override public int getChildrenCount(int groupPosition) { if (childs.isEmpty()) { return 0; } else { return childs.get(groupPosition).size(); } } @Override public Object getGroup(int groupPosition) { return groups.get(groupPosition); } @Override public int getGroupCount() { return groups.size(); } @Override public long getGroupId(int groupPosition) { return groupPosition; } // 获取一级列表View对象 @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { LinearLayout lv2; LayoutInflater layoutInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (groups.get(groupPosition).get("isnodata") == "true") { lv2 = (LinearLayout) layoutInflater.inflate(R.layout.child, null); lv2.setOnClickListener(null); elv.setDivider(null); } else { // 获取一级列表布局文件,设置相应元素属性 lv2 = (LinearLayout) layoutInflater.inflate(R.layout.group, null); TextView day = (TextView) lv2.findViewById(R.id.day); TextView time = (TextView) lv2.findViewById(R.id.time); TextView money = (TextView) lv2.findViewById(R.id.money); ImageView service_arrow = (ImageView) lv2 .findViewById(R.id.service_arrow); day.setText(groups.get(groupPosition).get("day")); time.setText(groups.get(groupPosition).get("time")); money.setText("¥" + groups.get(groupPosition).get("money")); if (Integer.parseInt(groups.get(groupPosition).get("money")) > 0) { money.setTextColor(Color.parseColor("#ffff0000")); } else if (Integer.parseInt(groups.get(groupPosition).get( "money")) < 0) { money.setTextColor(Color.parseColor("#5ea98d")); } if (isExpanded) { service_arrow .setBackgroundResource(R.drawable.service_arrow_up); } else { service_arrow .setBackgroundResource(R.drawable.service_arrow_down); } } return lv2; } @Override public boolean hasStableIds() { return false; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; // 必须改过来 } } @Override public void onFooterRefresh(PullToRefreshView view) { mPullToRefreshView.postDelayed(new Runnable() { @Override public void run() { mHandler.sendEmptyMessage(2); mPullToRefreshView.onFooterRefreshComplete(); } }, 1000); } @Override public void onHeaderRefresh(PullToRefreshView view) { mPullToRefreshView.postDelayed(new Runnable() { @Override public void run() { mHandler.sendEmptyMessage(1); mPullToRefreshView.onHeaderRefreshComplete(); } }, 1000); } private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); // groups = new ArrayList>(); // childs = new ArrayList>>(); switch (msg.what) { case 1: initData(1); sum_title.startAnimation(pushup); break; case 2: initData(-1); sum_title.startAnimation(pushout); break; default: break; } } }; @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { TranslateAnimation animation = new TranslateAnimation(0, 0, -height, 0); animation.setDuration(500); animation.setFillAfter(true); fragall.startAnimation(animation); super.onActivityResult(requestCode, resultCode, data); } public static int getyear() { return defaultYear; } @Override public void filngtonext() { System.out.println("filngtonext"); FragmentPage2.clickMoreBtn(); } @Override public void filngtonpre() { FragmentPage2.clickMyfeedBtn(); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/FragmentPage4.java ================================================ package com.cwp.cmoneycharge; import com.cwp.cmoneycharge.R; import cwp.moneycharge.dao.IncomeDAO; import cwp.moneycharge.dao.ItypeDAO; import cwp.moneycharge.dao.NoteDAO; import cwp.moneycharge.dao.PayDAO; import cwp.moneycharge.dao.PtypeDAO; import cwp.moneycharge.model.CustomDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; public class FragmentPage4 extends BaseFrament{ int userid; Intent intentr; private ListView listview; public void Setting() { // TODO Auto-generated constructor stub } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_4, null); } public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); listview = (ListView) getView().findViewById(R.id.settinglisv); ArrayAdapter adapter = ArrayAdapter.createFromResource( getView().getContext(), R.array.settingtype, android.R.layout.simple_expandable_list_item_1); listview.setAdapter(adapter); } @Override public void onStart() { super.onStart(); intentr = getActivity().getIntent(); userid = intentr.getIntExtra("cwp.id", 100000001); listview.setOnItemClickListener(new OnItemClickListener() {// 为GridView设置项单击事件 @Override public void onItemClick(AdapterView arg0, View arg1, int pos, long arg3) { String result = arg0.getItemAtPosition(pos).toString(); Intent intent = getActivity().getIntent();// 创建Intent对象 userid = intent.getIntExtra("cwp.id", 100000001); switch (pos) { case 0: alarmDialog(pos);// 清空收入数据 break; case 1: alarmDialog(pos); // 清空支出数据 break; case 2: intentr = new Intent(getActivity(), SettingActivity.class); // 设置百度语音 startActivity(intentr); break; case 3: intentr = new Intent(getActivity(), InPtypeManager.class); intentr.putExtra("cwp.id", userid); intentr.putExtra("type", 0); startActivity(intentr); break; case 4: intentr = new Intent(getActivity(), InPtypeManager.class); intentr.putExtra("cwp.id", userid); intentr.putExtra("type", 1); startActivity(intentr); break; case 5: alarmDialog(pos); // 数据初始化 break; case 6: // 关于系统 intentr = new Intent(getActivity(), About.class); intentr.putExtra("cwp.id", userid); startActivity(intentr); break; } } }); } private void alarmDialog(int type) { // 退出程序的方法 Dialog dialog = null; String ps = "收入数据", is = "支出数据"; CustomDialog.Builder customBuilder = new CustomDialog.Builder(getView() .getContext()); customBuilder.setTitle("警告"); // 创建标题 switch (type) { case 0: customBuilder .setMessage("将删除当前的用户所有" + ps) .setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { IncomeDAO incomeDAO = new IncomeDAO( getActivity()); incomeDAO.deleteUserData(userid); Toast.makeText(getActivity(), "已清空~!!", Toast.LENGTH_LONG).show(); } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); break; case 1: customBuilder .setMessage("将删除当前的用户所有" + is) .setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { PayDAO payDAO = new PayDAO(getActivity()); payDAO.deleteUserData(userid); Toast.makeText(getActivity(), "已清空~!!", Toast.LENGTH_LONG).show(); dialog.dismiss(); } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); break; case 5: customBuilder .setMessage("此操作将重置当前用户的收入、支出类型,确定还原吗?") .setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { ItypeDAO itypedao = new ItypeDAO( getActivity()); PtypeDAO ptypedao = new PtypeDAO( getActivity()); itypedao.initData(userid); ptypedao.initData(userid); Toast.makeText(getActivity(), "已还原~!!", Toast.LENGTH_LONG).show(); dialog.dismiss(); } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); break; } dialog = customBuilder.create();// 创建对话框 dialog.show(); // 显示对话框 } @Override public void filngtonext() { // TODO Auto-generated method stub } @Override public void filngtonpre() { FragmentPage2.clickHomeBtn(); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/InPtypeManager.java ================================================ package com.cwp.cmoneycharge; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import com.cwp.chart.SystemBarTintManager; import cwp.moneycharge.dao.ItypeDAO; import cwp.moneycharge.dao.PtypeDAO; import cwp.moneycharge.model.ActivityManager; import cwp.moneycharge.model.CustomDialog; import cwp.moneycharge.model.Tb_itype; import cwp.moneycharge.model.Tb_ptype; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.util.SparseBooleanArray; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Toast; public class InPtypeManager extends Activity { public InPtypeManager() { // TODO Auto-generated constructor stub } private List typename; private ListView lv; int userid, type; Intent intentr; ItypeDAO itypeDAO; PtypeDAO ptypeDAO; TextView inptext; Button add, delete; String inputStr = ""; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.inptypemanager); SystemBarTintManager mTintManager; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { findViewById(R.id.inptext_top).setVisibility(View.VISIBLE); setTranslucentStatus(true); } mTintManager = new SystemBarTintManager(this); mTintManager.setStatusBarTintEnabled(true); mTintManager.setStatusBarTintResource(R.color.statusbar_bg); SysApplication.getInstance().addActivity(this); // 在销毁队列中添加this inptext = (TextView) findViewById(R.id.inptext); lv = (ListView) findViewById(R.id.typelist);// 得到ListView对象的引用 add = (Button) findViewById(R.id.addtype); delete = (Button) findViewById(R.id.deletetype); } @TargetApi(19) private void setTranslucentStatus(boolean on) { Window win = getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; if (on) { winParams.flags |= bits; } else { winParams.flags &= ~bits; } win.setAttributes(winParams); } @Override public void onStart() { super.onStart(); // 获取数据 intentr = getIntent(); userid = intentr.getIntExtra("cwp.id", 100000001); type = intentr.getIntExtra("type", 0); itypeDAO = new ItypeDAO(InPtypeManager.this); ptypeDAO = new PtypeDAO(InPtypeManager.this); if (type == 0) { typename = itypeDAO.getItypeName(userid); inptext.setText("收入类型管理"); } else { typename = ptypeDAO.getPtypeName(userid); inptext.setText("支出类型管理"); } /* 为ListView设置Adapter来绑定数据 */ lv.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_checked, typename)); add.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { inputTitleDialog(); } }); delete.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { deleteDialog(); } }); } private void inputTitleDialog() { final EditText inputServer = new EditText(InPtypeManager.this); inputServer.setFocusable(true); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("添加类型").setView(inputServer) .setNegativeButton("取消", null); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { inputStr = inputServer.getText().toString(); int i = (int) itypeDAO.getCount(userid) + 1; if (inputStr.trim().equals("")) { Toast.makeText(InPtypeManager.this, "输入内容不能为空!", Toast.LENGTH_LONG).show(); refresh(); } else if (type == 0) { itypeDAO.add(new Tb_itype(userid, i, inputStr)); } else { ptypeDAO.add(new Tb_ptype(userid, i, inputStr)); } refresh(); } }); builder.show(); } private void deleteDialog() { // 退出程序的方法 Dialog dialog = null; CustomDialog.Builder customBuilder = new CustomDialog.Builder( InPtypeManager.this); customBuilder .setTitle("删除") // 创建标题 .setMessage("您确定要删除吗?") .setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { onDeleteClick(); Toast.makeText(InPtypeManager.this, "已删除!", Toast.LENGTH_LONG).show(); dialog.dismiss(); refresh(); } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); dialog = customBuilder.create();// 创建对话框 dialog.show(); // 显示对话框 } public void onDeleteClick() { // 获取选中的行 SparseBooleanArray checked = lv.getCheckedItemPositions(); List checkList = new ArrayList(); for (int i = 0; i < lv.getCount(); i++) { if (checked.get(i) == true) { // 获取到选择的行的数据 checkList.add(typename.get(i).toString()); } } if (checkList.size() > 0) { for (String lchecked : checkList) { if (type == 1) ptypeDAO.deleteByName(userid, lchecked); else itypeDAO.deleteByName(userid, lchecked); } } else { Toast.makeText(InPtypeManager.this, "您未选中任何项,请选择", Toast.LENGTH_LONG).show(); } lv.clearChoices();// 清空listView的选择状态,方便下次选择 } public void refresh() { finish(); Intent intentf = new Intent(InPtypeManager.this, InPtypeManager.class); intentf.putExtra("cwp.id", userid); intentf.putExtra("type", type); startActivity(intentf); } public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键 Intent intent = new Intent(InPtypeManager.this, MainActivity.class); intent.putExtra("cwp.id", userid); intent.putExtra("cwp.Fragment", "4");// 设置传递数据 startActivity(intent); return true; } return super.onKeyDown(keyCode, event); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/IncomeData.java ================================================ package com.cwp.cmoneycharge; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; import java.util.Random; import org.achartengine.ChartFactory; import org.achartengine.GraphicalView; import org.achartengine.model.CategorySeries; import org.achartengine.model.SeriesSelection; import org.achartengine.renderer.DefaultRenderer; import org.achartengine.renderer.SimpleSeriesRenderer; import cwp.moneycharge.dao.IncomeDAO; import cwp.moneycharge.dao.ItypeDAO; import cwp.moneycharge.model.ActivityManager; import cwp.moneycharge.model.KindData; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.text.format.Time; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Adapter; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.SpinnerAdapter; import android.widget.TextView; import android.widget.Toast; public class IncomeData extends Activity { int userid; Intent intentr; IncomeDAO incomeDAO; int defaultMonth; int defaultYear; Time time ;//获取当前时间 LinearLayout piechart,idataselect; Button beforet,aftert,anytime; Spinner year,month,day,yeare,monthe,daye;//界面上的任意时间 List yearlist; Adapter adapter; String date1,date2; List KindDatai; DefaultRenderer mRenderer ; CategorySeries mSeries ; GraphicalView mChartView; ItypeDAO itypeDAO; TextView nodata; private static int[] COLORS = new int[] { Color.rgb(180, 0, 0),Color.rgb(180, 120,130), Color.rgb(10, 180, 170),Color.rgb(10, 180, 10),Color.rgb(220, 180, 10),Color.rgb(220, 180, 130),Color.rgb(20, 180, 130) ,Color.rgb(20, 18, 130),Color.rgb(255, 120, 10),Color.rgb(255, 120, 100),Color.rgb(255, 12, 100),Color.rgb(217, 190, 100) ,Color.rgb(50,150, 100),Color.rgb(150,150, 100),Color.rgb(150,150, 190)}; public IncomeData() { // TODO Auto-generated constructor stub } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.incomedata); SysApplication.getInstance().addActivity(this); // 在销毁队列中添加this time = new Time("GMT+8"); time.setToNow(); defaultMonth=time.month+1;//设置默认月份 defaultYear=time.year; beforet=(Button)findViewById(R.id.ibefore); aftert=(Button)findViewById(R.id.iafter); anytime=(Button)findViewById(R.id.ianytime); year=(Spinner)findViewById(R.id.iyear); month=(Spinner)findViewById(R.id.imonth); day=(Spinner)findViewById(R.id.iday); yeare=(Spinner)findViewById(R.id.iyeare); monthe=(Spinner)findViewById(R.id.imonthe); daye=(Spinner)findViewById(R.id.idaye); nodata=(TextView)findViewById(R.id.nodata); idataselect=(LinearLayout)findViewById(R.id.idataselect); piechart=(LinearLayout)findViewById(R.id.ichart); mSeries = new CategorySeries(""); mRenderer = new DefaultRenderer();// PieChart的主要描绘器 yearlist=new ArrayList(); //生成年份列表 spinner itypeDAO=new ItypeDAO(IncomeData.this); //设置年 for(int i=0;i<=10;i++){ yearlist.add(String.valueOf(defaultYear-i)); } adapter=new ArrayAdapter(IncomeData.this,android.R.layout.simple_spinner_item,yearlist); year.setAdapter((SpinnerAdapter) adapter); yeare.setAdapter((SpinnerAdapter) adapter); } @Override protected void onStart(){ super.onStart(); intentr=getIntent(); userid=intentr.getIntExtra("cwp.id",100000001); defaultMonth=intentr.getIntExtra("default", defaultMonth); defaultYear=intentr.getIntExtra("defaulty", defaultYear); int type=intentr.getIntExtra("type",0);//为0,选择上下月,为1,选择任意时间 //饼图 /* mRenderer=new DefaultRenderer(); mRenderer.setApplyBackgroundColor(true); mRenderer.setBackgroundColor(Color.TRANSPARENT); // mRenderer.setChartTitleTextSize(20); mRenderer.setLabelsTextSize(20); mRenderer.setLabelsColor(Color.BLACK); mRenderer.setShowAxes(false); // 是否显示轴线 // mRenderer.setAxesColor(Color.RED); //设置轴颜色 mRenderer.setFitLegend(false); mRenderer.setInScroll(false); mRenderer.setPanEnabled(false); mRenderer.setShowCustomTextGrid(false); mRenderer.setShowLegend(false); //不显示图例 mRenderer.setShowGrid(false); mRenderer.setClickEnabled(true); // mRenderer.setScale(1.5f); // mRenderer.setLegendTextSize(15); // mRenderer.setMargins(new int[] { 20, 50, 15, 0 }); // mRenderer.setZoomButtonsVisible(true); mRenderer.setStartAngle(45); */ mRenderer.setZoomButtonsVisible(true);// 显示放大缩小功能按钮 mRenderer.setStartAngle(180);// 设置为水平开始 mRenderer.setDisplayValues(true);// 显示数据 mRenderer.setFitLegend(true);// 设置是否显示图例 mRenderer.setShowLabels(true); mRenderer.setLabelsTextSize(40); mRenderer.setShowLegend(true); mRenderer.setLabelsColor(Color.BLACK); mRenderer.setLegendTextSize(30);// 设置图例字体大小 mRenderer.setLegendHeight(30);// 设置图例高度 mRenderer.setChartTitleTextSize(34);// 设置饼图标题大小 incomeDAO=new IncomeDAO(IncomeData.this); if(type==0){ KindDatai=incomeDAO.getKDataOnMonth(userid, defaultYear, defaultMonth); mRenderer.setChartTitle(String.valueOf(defaultYear)+"-"+String.valueOf(defaultMonth)); }else{ date1=intentr.getStringExtra("date1"); date2=intentr.getStringExtra("date2"); KindDatai=incomeDAO.getKDataOnDay(userid, date1, date2); mRenderer.setChartTitle(date1+"~"+date2); } //数据 if(KindDatai.size()==0){ nodata.setVisibility(View.VISIBLE); }else{ double sum=0.00; int i=0; for(KindData ki:KindDatai) sum+=ki.getAmount();//总和 for(KindData ki:KindDatai){ mSeries.add(itypeDAO.getOneName(userid, ki.getKindname()), ki.getAmount()/ sum); SimpleSeriesRenderer renderer = new SimpleSeriesRenderer(); if(i 0) { if (start > 0) { editable.delete(start - 1, start); if (ed.getText().toString().indexOf(".") < 0) { a = true; } } } } else if (primaryCode == -8) { if (start > 0 && a) { editable.insert(start, "."); a = false; } } // else if (primaryCode == -11) { // 收入 // ((AddPay) act).update(); // } // else if (primaryCode == -12) { // 支出 // AddPay add = new AddPay(); // add.getupdatepay("income"); // } else if (primaryCode == -7) { hideKeyboard(); } else if (primaryCode == -9) { hideKeyboard(); AddPay.showVoiveDialog(); } else if (primaryCode == -10) { ed.setText(""); a = true; } else { if (a) { // 判断是否有小数点 if (editable.length() < 9) { editable.insert(start, Character.toString((char) primaryCode)); } } else { if (editable.toString().split("\\.").length < 2) { editable.insert(start, Character.toString((char) primaryCode)); } else { if (editable.toString().split("\\.")[1].length() < 2) { // 处理小数点后是否只能2位数 editable.insert(start, Character.toString((char) primaryCode)); } } } } } }; public void showKeyboard() { int visibility = keyboardView.getVisibility(); if (visibility == View.GONE || visibility == View.INVISIBLE) { keyboardView.setVisibility(View.VISIBLE); } } public void hideKeyboard() { int visibility = keyboardView.getVisibility(); if (visibility == View.VISIBLE) { keyboardView.setVisibility(View.INVISIBLE); } } private boolean isword(String str) { String wordstr = "abcdefghijklmnopqrstuvwxyz"; if (wordstr.indexOf(str.toLowerCase()) > -1) { return true; } return false; } public interface InputFinishListener { public void inputHasOver(String text); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/MainActivity.java ================================================ package com.cwp.cmoneycharge; import java.util.Calendar; import com.cwp.chart.SystemBarTintManager; import com.cwp.cmoneycharge.AddPay; import com.cwp.cmoneycharge.R; import com.cwp.pattern.UnlockGesturePasswordActivity; import com.cwp.pattern.UpdateManager; import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.graphics.drawable.BitmapDrawable; import android.os.Build; import android.os.Bundle; import android.os.StrictMode; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentTransaction; import android.util.DisplayMetrics; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.PopupWindow.OnDismissListener; public class MainActivity extends FragmentActivity implements OnClickListener { // 定义Fragment页面 private FragmentPage2 fragmentPage2; SharedPreferences sp; int userid; static int value = 0; DialogShowUtil dialogShowUtil = new DialogShowUtil(this, this, null, null, null); private Effectstype effect; // 自定义Dialog private FragmentPage3 fragmentPage3; private String updatedate; private Editor edit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); sp = this.getSharedPreferences("preferences", MODE_WORLD_READABLE); edit = sp.edit(); // initdefault();// 初始化数据 SystemBarTintManager mTintManager; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { setTranslucentStatus(true); } mTintManager = new SystemBarTintManager(this); mTintManager.setStatusBarTintEnabled(true); mTintManager.setStatusBarTintResource(R.color.statusbar_bg); fragmentPage2 = new FragmentPage2(this); // 得到Fragment事务管理器 FragmentTransaction fragmentTransaction = this .getSupportFragmentManager().beginTransaction(); // 替换当前的页面 fragmentTransaction.replace(R.id.frame_foot, fragmentPage2); fragmentTransaction.commit(); SysApplication.getInstance().addActivity(this); // 在销毁队列中添加this Intent intentr = getIntent(); userid = intentr.getIntExtra("cwp.id", 100000001); if (intentr.getStringExtra("cwp.Fragment") != null) { // 取回跳转的目的页面 value = Integer.parseInt(intentr.getStringExtra("cwp.Fragment")); } Calendar c = Calendar.getInstance();// 获取当前系统日期 int mYear = c.get(Calendar.YEAR);// 获取年份 int mMonth = c.get(Calendar.MONTH);// 获取月份 int mDay = c.get(Calendar.DAY_OF_MONTH);// 获取天数 updatedate = mYear + "-" + mMonth + 1 + "-" + mDay; // StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() // .detectDiskReads().detectDiskWrites().detectNetwork() // .penaltyLog().build()); // StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() // .detectLeakedSqlLiteObjects().detectLeakedClosableObjects() // .penaltyLog().penaltyDeath().build()); } private void initdefault() { // 初始化数据 edit.putString("sendlog", "开"); // 报log edit.putString("gesturepw", "开"); // 手势开 edit.commit(); } @Override public void onClick(View v) { } public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键 dialogShowUtil.dialogShow("shake", "quit", "", ""); } return super.onKeyDown(keyCode, event); } public static int getValueFM() { return value; } @TargetApi(19) private void setTranslucentStatus(boolean on) { Window win = getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; if (on) { winParams.flags |= bits; } else { winParams.flags &= ~bits; } win.setAttributes(winParams); } protected void onResume() { super.onResume(); CrashApplication myApplaction = (CrashApplication) getApplication(); if ((myApplaction.isLocked) && (sp.getString("gesturepw", "").equals("开"))) {// 判断是否需要跳转到密码界面 Intent intent = new Intent(this, UnlockGesturePasswordActivity.class); startActivity(intent); } if (!updatedate.equals(sp.getString("updatedate", ""))) { // 今天已经检查过就不自动检查了 UpdateManager manager = new UpdateManager(MainActivity.this); manager.checkUpdate("noshow"); edit.putString("updatedate", updatedate); // 一天只检查一次 edit.commit(); } }; } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/ModifyInP.java ================================================ package com.cwp.cmoneycharge; import java.util.Calendar; import java.util.List; import com.cwp.cmoneycharge.R; import cwp.moneycharge.dao.IncomeDAO; import cwp.moneycharge.dao.ItypeDAO; import cwp.moneycharge.dao.PtypeDAO; import cwp.moneycharge.model.ActivityManager; import cwp.moneycharge.model.Tb_income; import cwp.moneycharge.model.Tb_pay; import android.annotation.SuppressLint; import android.app.Activity; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import cwp.moneycharge.dao.IncomeDAO; import cwp.moneycharge.dao.PayDAO; public class ModifyInP extends Activity{ protected static final int DATE_DIALOG_ID = 0;// 创建日期对话框常量 TextView tvtitle, textView;// 创建两个TextView对象 EditText txtMoney, txtTime, txtHA, txtMark;// 创建4个EditText对象 Spinner spType;// 创建Spinner对象 Button btnEdit, btnDel;// 创建两个Button对象 String[] strInfos;// 定义字符串数组 String strno, strType;// 定义两个字符串变量,分别用来记录信息编号和管理类型 int userid; ItypeDAO itypeDAO=new ItypeDAO(ModifyInP.this); PtypeDAO ptypeDAO=new PtypeDAO(ModifyInP.this); List spdatalist; private int mYear;// 年 private int mMonth;// 月 private int mDay;// 日 private ArrayAdapter adapter; private String[] spdata; PayDAO payDAO= new PayDAO(ModifyInP.this );// 创建PayDAO对象 IncomeDAO incomeDAO = new IncomeDAO(ModifyInP.this);// 创建IncomeDAO对象 public ModifyInP() { // TODO Auto-generated constructor stub } @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.modifyinp);// 设置布局文件 ActivityManager.getInstance().addActivity(this); //管理Activity,退出按钮点击时调用 tvtitle = (TextView) findViewById(R.id.inouttitle);// 获取标题标签对象 textView = (TextView) findViewById(R.id.tvInOut);// 获取地点/付款方标签对象 txtMoney = (EditText) findViewById(R.id.txtInOutMoney);// 获取金额文本框 txtTime = (EditText) findViewById(R.id.txtInOutTime);// 获取时间文本框 spType = (Spinner) findViewById(R.id.spInOutType);// 获取类别下拉列表 txtHA = (EditText) findViewById(R.id.txtInOut);// 获取地点/付款方文本框 txtMark = (EditText) findViewById(R.id.txtInOutMark);// 获取备注文本框 btnEdit = (Button) findViewById(R.id.btnInOutEdit);// 获取修改按钮 btnDel = (Button) findViewById(R.id.btnInOutDelete);// 获取删除按钮 } @Override protected void onStart(){ super.onStart(); Intent intent = getIntent();// 创建Intent对象 Bundle bundle = intent.getExtras();// 获取传入的数据,并使用Bundle记录 strInfos = bundle.getStringArray("cwp.message");// 获取Bundle中记录的信息 strno = strInfos[0];// 记录id strType = strInfos[1];// 记录类型 userid=intent.getIntExtra("cwp.id",100000001); if (strType.equals("btnoutinfo"))// 如果类型是btnoutinfo { //选择列表初始化 spdatalist=ptypeDAO.getPtypeName(userid); spdata=spdatalist.toArray(new String[spdatalist.size()]);//在tb_itype中按用户id读取 adapter =new ArrayAdapter(ModifyInP.this,android.R.layout.simple_spinner_item,spdata); //动态生成收入类型列表 spType.setAdapter(adapter); tvtitle.setText("支出管理");// 设置标题为“支出管理” textView.setText("地 点:");// 设置“地点/付款方”标签文本为“地 点:” // 根据编号查找支出信息,并存储到Tb_pay对象中 Tb_pay tb_pay = payDAO.find(userid,Integer.parseInt(strno)); txtMoney.setText(String.valueOf(tb_pay.getMoney()));// 显示金额 txtTime.setText(tb_pay.getTime());// 显示时间 spType.setSelection(tb_pay.getType()-1);// 显示类别 txtHA.setText(tb_pay.getAddress());// 显示地点 txtMark.setText(tb_pay.getMark());// 显示备注 } else if (strType.equals("btnininfo"))// 如果类型是btnininfo { //选择列表初始化 spdatalist=itypeDAO.getItypeName(userid); spdata=spdatalist.toArray(new String[spdatalist.size()]);//在tb_itype中按用户id读取 adapter =new ArrayAdapter(ModifyInP.this,android.R.layout.simple_spinner_item,spdata); //动态生成收入类型列表 spType.setAdapter(adapter); tvtitle.setText("收入管理");// 设置标题为“收入管理” textView.setText("付款方:");// 设置“地点/付款方”标签文本为“付款方:” // 根据编号查找收入信息,并存储到Tb_pay对象中 Tb_income tb_income = incomeDAO.find(userid,Integer.parseInt(strno)); txtMoney.setText(String.valueOf(tb_income.getMoney()));// 显示金额 txtTime.setText(tb_income.getTime());// 显示时间 spType.setSelection(tb_income.getType()-1);// 显示类别 txtHA.setText(tb_income.getHandler());// 显示付款方 txtMark.setText(tb_income.getMark());// 显示备注 } txtTime.setOnClickListener(new OnClickListener() {// 为时间文本框设置单击监听事件 @SuppressWarnings("deprecation") @Override public void onClick(View arg0) { // TODO Auto-generated method stub showDialog(DATE_DIALOG_ID);// 显示日期选择对话框 } }); btnEdit.setOnClickListener(new OnClickListener() {// 为修改按钮设置监听事件 @Override public void onClick(View arg0) { // TODO Auto-generated method stub if (strType.equals("btnoutinfo"))// 判断类型如果是btnoutinfo { Tb_pay tb_pay = new Tb_pay();// 创建Tb_pay对象 tb_pay.set_id(userid);// 设置userid tb_pay.setNo(Integer.parseInt(strno));// 设置编号 tb_pay.setMoney(Double.parseDouble(txtMoney.getText().toString()));// 设置金额 tb_pay.setTime(setTimeFormat(txtTime.getText().toString()));// 设置时间 tb_pay.setType(spType.getSelectedItemPosition()+1);// 设置类别 tb_pay.setAddress(txtHA.getText().toString());// 设置地点 tb_pay.setMark(txtMark.getText().toString());// 设置备注 payDAO.update(tb_pay);// 更新支出信息 Toast.makeText(ModifyInP.this, "〖数据〗修改成功!", Toast.LENGTH_SHORT).show(); gotoback(); } else if (strType.equals("btnininfo"))// 判断类型如果是btnininfo { Tb_income tb_income = new Tb_income();// 创建Tb_income对象 tb_income.set_id(userid);// 设置编号 tb_income.setNo(Integer.parseInt(strno));// 设置编号 tb_income.setMoney(Double.parseDouble(txtMoney.getText().toString()));// 设置金额 tb_income.setTime(setTimeFormat(txtTime.getText().toString()));// 设置时间 tb_income.setType(spType.getSelectedItemPosition()+1);// 设置类别 tb_income.setHandler(txtHA.getText().toString());// 设置付款方 tb_income.setMark(txtMark.getText().toString());// 设置备注 incomeDAO.update(tb_income);// 更新收入信息 Toast.makeText(ModifyInP.this, "〖数据〗修改成功!", Toast.LENGTH_SHORT).show(); gotoback(); } // 弹出信息提示 } }); btnDel.setOnClickListener(new OnClickListener() {// 为删除按钮设置监听事件 @Override public void onClick(View arg0) { // TODO Auto-generated method stub if (strType.equals("btnoutinfo"))// 判断类型如果是btnoutinfo { payDAO.detele(userid,Integer.parseInt(strno));// 根据编号删除支出信息 gotoback(); } else if (strType.equals("btnininfo"))// 判断类型如果是btnininfo { incomeDAO.detele(userid,Integer.parseInt(strno));// 根据编号删除收入信息 gotoback(); } Toast.makeText(ModifyInP.this, "〖数据〗删除成功!", Toast.LENGTH_SHORT) .show(); } }); final Calendar c = Calendar.getInstance();// 获取当前系统日期 mYear = c.get(Calendar.YEAR);// 获取年份 mMonth = c.get(Calendar.MONTH);// 获取月份 mDay = c.get(Calendar.DAY_OF_MONTH);// 获取天数 updateDisplay();// 显示当前系统时间 } @Override protected Dialog onCreateDialog(int id)// 重写onCreateDialog方法 { switch (id) { case DATE_DIALOG_ID:// 弹出日期选择对话框 return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay); } return null; } private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { mYear = year;// 为年份赋值 mMonth = monthOfYear;// 为月份赋值 mDay = dayOfMonth;// 为天赋值 updateDisplay();// 显示设置的日期 } }; private void updateDisplay() { // 显示设置的时间 txtTime.setText(new StringBuilder().append(mYear).append("-") .append(mMonth + 1).append("-").append(mDay)); } private void gotoback(){ Intent intent=new Intent(ModifyInP.this,MainActivity.class); intent.putExtra("cwp.id",userid); startActivity(intent); } private String setTimeFormat(String txtTime){ String date=txtTime; int y,m,d; String sm,sd; int i=0,j=0,k=0; for (i = 0; i < date.length(); i++) { if (date.substring(i, i + 1).equals("-") && j==0) j=i; else if(date.substring(i, i + 1).equals("-")) k=i; } y=Integer.valueOf(date.substring(0,j)); m=Integer.valueOf(date.substring(j+1,k)); d=Integer.valueOf(date.substring(k+1)); if(m<10){ sm="0"+String.valueOf(m); } else sm=String.valueOf(m); if(d<10){ sd="0"+String.valueOf(d); } else sd=String.valueOf(d); return String.valueOf(y)+"-"+sm+"-"+sd; } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/NiftyDialogBuilder.java ================================================ package com.cwp.cmoneycharge; import com.cwp.cmoneycharge.R; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; /** * Created by lee on 2014/7/30. */ public class NiftyDialogBuilder extends Dialog implements DialogInterface { private final String defTextColor="#FFFFFFFF"; private final String defDividerColor="#11000000"; private final String defMsgColor="#FFFFFFFF"; private final String defDialogColor="#FFE74C3C"; private Effectstype type=null; private LinearLayout mLinearLayoutView; private RelativeLayout mRelativeLayoutView; private LinearLayout mLinearLayoutMsgView; private LinearLayout mLinearLayoutTopView; private FrameLayout mFrameLayoutCustomView; private View mDialogView; private View mDivider; private TextView mTitle; private TextView mMessage; private ImageView mIcon; private Button mButton1; private Button mButton2; private int mDuration = -1; private static int mOrientation=1; private boolean isCancelable=true; private volatile static NiftyDialogBuilder instance; public NiftyDialogBuilder(Context context) { super(context); init(context); } public NiftyDialogBuilder(Context context,int theme) { super(context, theme); init(context); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WindowManager.LayoutParams params = getWindow().getAttributes(); params.height = ViewGroup.LayoutParams.MATCH_PARENT; params.width = ViewGroup.LayoutParams.MATCH_PARENT; getWindow().setAttributes((android.view.WindowManager.LayoutParams) params); } public static NiftyDialogBuilder getInstance(Context context) { int ort=context.getResources().getConfiguration().orientation; if (mOrientation!=ort){ mOrientation=ort; instance=null; } if (instance == null) { synchronized (NiftyDialogBuilder.class) { if (instance == null) { instance = new NiftyDialogBuilder(context,R.style.dialog_untran); } } } return instance; } private void init(Context context) { mDialogView = View.inflate(context, R.layout.dialog_layout, null); mLinearLayoutView=(LinearLayout)mDialogView.findViewById(R.id.parentPanel); mRelativeLayoutView=(RelativeLayout)mDialogView.findViewById(R.id.main); mLinearLayoutTopView=(LinearLayout)mDialogView.findViewById(R.id.topPanel); mLinearLayoutMsgView=(LinearLayout)mDialogView.findViewById(R.id.contentPanel); mFrameLayoutCustomView=(FrameLayout)mDialogView.findViewById(R.id.customPanel); mTitle = (TextView) mDialogView.findViewById(R.id.alertTitle); mMessage = (TextView) mDialogView.findViewById(R.id.message); mIcon = (ImageView) mDialogView.findViewById(R.id.icon); mDivider = mDialogView.findViewById(R.id.titleDivider); mButton1=(Button)mDialogView.findViewById(R.id.button1); mButton2=(Button)mDialogView.findViewById(R.id.button2); setContentView(mDialogView); this.setOnShowListener(new OnShowListener() { @Override public void onShow(DialogInterface dialogInterface) { mLinearLayoutView.setVisibility(View.VISIBLE); if(type==null){ type=Effectstype.Slidetop; } start(type); } }); mRelativeLayoutView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (isCancelable)dismiss(); } }); } public void toDefault(){ mTitle.setTextColor(Color.parseColor(defTextColor)); mDivider.setBackgroundColor(Color.parseColor(defDividerColor)); mMessage.setTextColor(Color.parseColor(defMsgColor)); mLinearLayoutView.setBackgroundColor(Color.parseColor(defDialogColor)); } public NiftyDialogBuilder withDividerColor(String colorString) { mDivider.setBackgroundColor(Color.parseColor(colorString)); return this; } public NiftyDialogBuilder withTitle(CharSequence title) { toggleView(mLinearLayoutTopView,title); mTitle.setText(title); return this; } public NiftyDialogBuilder withTitleColor(String colorString) { mTitle.setTextColor(Color.parseColor(colorString)); return this; } public NiftyDialogBuilder withMessage(int textResId) { toggleView(mLinearLayoutMsgView,textResId); mMessage.setText(textResId); return this; } public NiftyDialogBuilder withMessage(CharSequence msg) { toggleView(mLinearLayoutMsgView,msg); mMessage.setText(msg); return this; } public NiftyDialogBuilder withMessageColor(String colorString) { mMessage.setTextColor(Color.parseColor(colorString)); return this; } public NiftyDialogBuilder withIcon(int drawableResId) { mIcon.setImageResource(drawableResId); return this; } public NiftyDialogBuilder withIcon(Drawable icon) { mIcon.setImageDrawable(icon); return this; } public NiftyDialogBuilder withDuration(int duration) { this.mDuration=duration; return this; } public NiftyDialogBuilder withEffect(Effectstype type) { this.type=type; return this; } public NiftyDialogBuilder withButtonDrawable(int resid) { mButton1.setBackgroundResource(resid); mButton2.setBackgroundResource(resid); return this; } public NiftyDialogBuilder withButton1Text(CharSequence text) { mButton1.setVisibility(View.VISIBLE); mButton1.setText(text); return this; } public NiftyDialogBuilder withButton2Text(CharSequence text) { mButton2.setVisibility(View.VISIBLE); mButton2.setText(text); return this; } public NiftyDialogBuilder setButton1Click(View.OnClickListener click) { mButton1.setOnClickListener(click); return this; } public NiftyDialogBuilder setButton2Click(View.OnClickListener click) { mButton2.setOnClickListener(click); return this; } public NiftyDialogBuilder setCustomView(int resId, Context context) { View customView = View.inflate(context, resId, null); if (mFrameLayoutCustomView.getChildCount()>0){ mFrameLayoutCustomView.removeAllViews(); } mFrameLayoutCustomView.addView(customView); return this; } public NiftyDialogBuilder setCustomView(View view, Context context) { if (mFrameLayoutCustomView.getChildCount()>0){ mFrameLayoutCustomView.removeAllViews(); } mFrameLayoutCustomView.addView(view); return this; } public NiftyDialogBuilder isCancelableOnTouchOutside(boolean cancelable) { this.isCancelable=cancelable; this.setCanceledOnTouchOutside(cancelable); return this; } public NiftyDialogBuilder isCancelable(boolean cancelable) { this.isCancelable=cancelable; this.setCancelable(cancelable); return this; } private void toggleView(View view,Object obj){ if (obj==null){ view.setVisibility(View.GONE); }else { view.setVisibility(View.VISIBLE); } } @Override public void show() { if (mTitle.getText().equals("")) mDialogView.findViewById(R.id.topPanel).setVisibility(View.GONE); super.show(); } private void start(Effectstype type){ BaseEffects animator = type.getAnimator(); if(mDuration != -1){ animator.setDuration(Math.abs(mDuration)); } animator.start(mRelativeLayoutView); } @Override public void dismiss() { super.dismiss(); mButton1.setVisibility(View.GONE); mButton2.setVisibility(View.GONE); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/PayChart.java ================================================ package com.cwp.cmoneycharge; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Random; import com.cwp.chart.ChartProp; import com.cwp.chart.ChartPropChangeListener; import com.cwp.chart.MenuFragment; import com.cwp.chart.MyButton; import com.cwp.chart.PieView; import com.cwp.chart.SystemBarTintManager; import com.cwp.pattern.UnlockGesturePasswordActivity; import com.slidingmenu.lib.SlidingMenu; import com.slidingmenu.lib.app.SlidingActivity; import cwp.moneycharge.dao.IncomeDAO; import cwp.moneycharge.dao.ItypeDAO; import cwp.moneycharge.dao.PayDAO; import cwp.moneycharge.dao.PtypeDAO; import cwp.moneycharge.model.KindData; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.annotation.TargetApi; import android.app.FragmentTransaction; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.text.format.Time; import android.util.DisplayMetrics; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.widget.Adapter; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.Spinner; import android.widget.SpinnerAdapter; import android.widget.TextView; import android.widget.PopupWindow.OnDismissListener; public class PayChart extends SlidingActivity implements OnClickListener { DialogShowUtil dialogShowUtil = new DialogShowUtil(this, this, null, null, null); // 定义布局对象 private FrameLayout friendfeedFl, myfeedFl, homeFl, moreFl; // 定义图片组件对象 private ImageView friendfeedIv, myfeedIv, homeIv, moreIv; // 定义按钮图片组件 private ImageView toggleImageView, plusImageView; // 定义PopupWindow private PopupWindow popWindow; private LinearLayout popWinLayout; // 定义pop组件 private LinearLayout pop_voiceView; private LinearLayout pop_quickView; private int[] itemColor;// 选项颜色 private String[] itemText;// 选项文字 private PieView pieView; private float surfacViewWidth = 0; private float surfacViewHeight = 0; private MyButton myButton; LinearLayout piechart, pdataselect; private TextView textView; private TextView textView2, example_center; private ImageView example_left, example_left2, example_right; Button anytime; String date1 = "", date2 = "", dday, dmonth; Spinner year, month, day, yeare, monthe, daye;// 界面上的任意时间 List yearlist; static String amount = ""; Time time;// 获取当前时间 int defaultMonth, defaultDay; int defaultYear; Intent intentr; int userid; int type; String datatype = "pay"; Adapter adapter; PayDAO payDAO; IncomeDAO incomeDAO; List KindDatap; PtypeDAO ptypeDAO; ItypeDAO itypeDAO; @Override public void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_NO_TITLE); super.onCreate(savedInstanceState); // getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, // WindowManager.LayoutParams.FLAG_FULLSCREEN); SysApplication.getInstance().addActivity(this); // 在销毁队列中添加this setContentView(R.layout.paychart); // set the Behind View setBehindContentView(R.layout.frame_menu); SystemBarTintManager mTintManager; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { setTranslucentStatus(true); } mTintManager = new SystemBarTintManager(this); mTintManager.setStatusBarTintEnabled(true); mTintManager.setStatusBarTintResource(R.color.fragment2); payDAO = new PayDAO(PayChart.this); KindDatap = new ArrayList(); ptypeDAO = new PtypeDAO(PayChart.this); incomeDAO = new IncomeDAO(PayChart.this); itypeDAO = new ItypeDAO(PayChart.this); FragmentTransaction fragmentTransaction = getFragmentManager() .beginTransaction(); MenuFragment menuFragment = new MenuFragment(); fragmentTransaction.replace(R.id.menu, menuFragment); fragmentTransaction.commit(); // customize the SlidingMenu SlidingMenu sm = getSlidingMenu(); sm.setMode(SlidingMenu.LEFT); sm.setShadowWidth(50); sm.setShadowDrawable(R.drawable.shadow); sm.setBehindOffset(260); sm.setFadeDegree(0.4f); // 设置slding menu的几种手势模式 // TOUCHMODE_FULLSCREEN 全屏模式,在content页面中,滑动,可以打开sliding menu // TOUCHMODE_MARGIN 边缘模式,在content页面中,如果想打开slding ,你需要在屏幕边缘滑动才可以打开slding // menu // TOUCHMODE_NONE 自然是不能通过手势打开啦 sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN); // 使用左上方icon可点,这样在onOptionsItemSelected里面才可以监听到R.id.home // getActionBar().setDisplayHomeAsUpEnabled(true); initView(); } @TargetApi(19) private void setTranslucentStatus(boolean on) { Window win = getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; if (on) { winParams.flags |= bits; } else { winParams.flags &= ~bits; } win.setAttributes(winParams); } @Override protected void onStart() { super.onStart(); } @Override protected void onResume() { super.onResume(); pieView.rotateEnable(); SharedPreferences sp = this.getSharedPreferences("preferences", MODE_WORLD_READABLE); CrashApplication myApplaction = (CrashApplication) getApplication(); if ((myApplaction.isLocked) && (sp.getString("gesturepw", "").equals("开"))) {// 判断是否需要跳转到密码界面 Intent intent = new Intent(this, UnlockGesturePasswordActivity.class); startActivity(intent); } } protected void onPause() { super.onPause(); if (pieView != null) { pieView.rotateDisable(); } } /** * * Description:初始化界面元紿 * */ public void initView() { final Calendar c = Calendar.getInstance();// 获取当前系统日期 defaultYear = c.get(Calendar.YEAR);// 获取年份 defaultMonth = c.get(Calendar.MONTH) + 1;// 获取月份 defaultDay = c.get(Calendar.DAY_OF_MONTH);// 获取天数 if (defaultMonth < 10) { dmonth = "0" + Integer.toString(defaultMonth); } else { dmonth = Integer.toString(defaultMonth); } if (defaultDay < 10) { dday = "0" + Integer.toString(defaultDay); } else { dday = Integer.toString(defaultDay); } date2 = Integer.toString(defaultYear) + "-" + dmonth + "-" + dday; date1 = Integer.toString(defaultYear) + "-01-01"; intentr = getIntent(); userid = intentr.getIntExtra("cwp.id", 100000001); defaultMonth = intentr.getIntExtra("default", defaultMonth); defaultYear = intentr.getIntExtra("defaulty", defaultYear); pieView = (PieView) this.findViewById(R.id.lotteryView); // myButton = (MyButton) this.findViewById(R.id.MyBt); textView = (TextView) this.findViewById(R.id.MyTV); textView2 = (TextView) this.findViewById(R.id.MyTVbottom); example_left = (ImageView) findViewById(R.id.example_left); example_left2 = (ImageView) findViewById(R.id.example_left2); example_right = (ImageView) findViewById(R.id.example_right); example_center = (TextView) this.findViewById(R.id.example_center); pdataselect = (LinearLayout) findViewById(R.id.pdataselect); year = (Spinner) findViewById(R.id.pyear); month = (Spinner) findViewById(R.id.pmonth); day = (Spinner) findViewById(R.id.pday); yeare = (Spinner) findViewById(R.id.pyeare); monthe = (Spinner) findViewById(R.id.pmonthe); daye = (Spinner) findViewById(R.id.pdaye); yearlist = new ArrayList(); // 生成年份列表 spinner anytime = (Button) findViewById(R.id.panytime); // 设置年 for (int i = 0; i <= 10; i++) { yearlist.add(String.valueOf(defaultYear - i)); } adapter = new ArrayAdapter(PayChart.this, android.R.layout.simple_spinner_item, yearlist); year.setAdapter((SpinnerAdapter) adapter); yeare.setAdapter((SpinnerAdapter) adapter); // 实例化布局对象 friendfeedFl = (FrameLayout) this.findViewById(R.id.layout_friendfeed2); myfeedFl = (FrameLayout) this.findViewById(R.id.layout_myfeed2); homeFl = (FrameLayout) this.findViewById(R.id.layout_home2); moreFl = (FrameLayout) this.findViewById(R.id.layout_more2); // 实例化图片组件对象 friendfeedIv = (ImageView) this.findViewById(R.id.image_friendfeed2); myfeedIv = (ImageView) this.findViewById(R.id.image_myfeed2); homeIv = (ImageView) this.findViewById(R.id.image_home2); moreIv = (ImageView) this.findViewById(R.id.image_more2); // 实例化按钮图片组件 toggleImageView = (ImageView) this.findViewById(R.id.toggle_btn2); plusImageView = (ImageView) this.findViewById(R.id.plus_btn2); initData(); textView.setOnClickListener(this); example_left.setOnClickListener(this); example_left2.setOnClickListener(this); example_right.setOnClickListener(this); anytime.setOnClickListener(this); type = intentr.getIntExtra("type", 0);// 为0,选择上下月,为1,选择任意时间 if (intentr.getStringExtra("datatype") != null) { datatype = intentr.getStringExtra("datatype"); } if ((intentr.getStringExtra("date1") != null) && (intentr.getStringExtra("date2") != null)) { date1 = intentr.getStringExtra("date1"); date2 = intentr.getStringExtra("date2"); } // 为0,选择上下月,为1,选择任意时间 // 获取数据 if (type == 0) { pdataselect.setVisibility(View.GONE); example_left.setVisibility(View.VISIBLE); example_right.setVisibility(View.VISIBLE); example_center.setText(String.valueOf(defaultYear) + "年 - " + String.valueOf(defaultMonth) + "月"); if (datatype.equals("pay")) { KindDatap = payDAO.getKDataOnMonth(userid, defaultYear, defaultMonth); } else { KindDatap = incomeDAO.getKDataOnMonth(userid, defaultYear, defaultMonth); } } else { pdataselect.setVisibility(View.VISIBLE); example_left.setVisibility(View.GONE); example_right.setVisibility(View.GONE); example_center.setText(date1 + " ~ " + date2); if (datatype.equals("pay")) { KindDatap = payDAO.getKDataOnDay(userid, date1, date2); } else { KindDatap = payDAO.getKDataOnDay(userid, date1, date2); } monthe.setSelection(defaultMonth - 1); // spinner显示当前月 daye.setSelection(defaultDay - 1); // spinner显示当前日 } initItem(); // 初始化数据 if (!(KindDatap.size() == 0)) { // 当获取到数据时 Message msg = new Message(); msg.obj = pieView.getCurrentChartProp(); handler.sendMessage(msg); // 发送消息,更新UI } pieView.setChartPropChangeListener(new ChartPropChangeListener() { @Override public void getChartProp(ChartProp chartProp) { Message msg = new Message(); msg.obj = chartProp; handler.sendMessage(msg); // 发送消息,更新UI } }); pieView.start(); } public Handler handler = new Handler() { // 创建线程 public void handleMessage(android.os.Message msg) { ChartProp chartProp = (ChartProp) msg.obj; // myButton.setBackgroundPaintColor(chartProp.getColor()); textView.setText(chartProp.getName()); textView2.setText(chartProp.getName2()); textView.setTextColor(chartProp.getColor()); }; }; private LinearLayout pop_photoView; DecimalFormat df = new DecimalFormat("#.00"); /** * * Description:初始化转盘的颜色 * */ public void initItem() { int i = 0; int fivecolor[] = new int[] { Color.rgb(56, 220, 244), Color.GREEN, Color.RED, Color.YELLOW, Color.CYAN }; if (KindDatap.size() == 0) { // 没有数据的情况 amount = "暂无数据"; // 无数据下总数的提示文字 } else { // 获取数据的情况 double sum = 0.00; for (KindData kp : KindDatap) { sum += kp.getAmount();// 取得总和 i++; } // 初始化数组 String names[] = new String[i]; float percent[] = new float[i]; String names2[] = new String[i]; int color[] = new int[i]; i = 0; for (KindData kp : KindDatap) { if (datatype.equals("pay")) { names[i] = ptypeDAO.getOneName(userid, kp.getKindname()); } else { names[i] = itypeDAO.getOneName(userid, kp.getKindname()); } if (i < fivecolor.length) { color[i] = fivecolor[i]; // 使用自定义颜色 } else { color[i] = getRandomColor(); // 使用随机生成的颜色 } java.text.NumberFormat percentFormat = java.text.NumberFormat .getPercentInstance(); percentFormat.setMaximumFractionDigits(2); // 最大小数位数 // 自动转换成百分比显示. names2[i] = percentFormat.format(kp.getAmount() / sum) + ":¥" + df.format(kp.getAmount()); percent[i] = (float) (kp.getAmount() / sum); // 计算所占百分比 i++; } amount = df.format(sum); // 总数的费用 // 创建图表 ArrayList acps = pieView.createCharts(i); int size = acps.size(); for (int k = 0; k < size; k++) { // 把数据传入图表 ChartProp chartProp = acps.get(k); chartProp.setColor(color[k]); chartProp.setPercent(percent[k]); chartProp.setName(names[k]); chartProp.setName2(names2[k]); } pieView.initPercents(); } } private int getRandomColor() {// 分别产生RBG数值 Random random = new Random(); int R = random.nextInt(255); int G = random.nextInt(255); int B = random.nextInt(255); return Color.rgb(R, G, B); } public static String getamount() { return amount; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.layout_friendfeed2: clickSwitchBtn("1"); break; // 点击与我相关按钮 case R.id.layout_myfeed2: clickSwitchBtn("2"); break; // 点击我的空间按钮 case R.id.layout_home2: clickSwitchBtn("3"); break; // 点击更多按钮 case R.id.layout_more2: clickSwitchBtn("4"); break; // 点击中间按钮 case R.id.toggle_btn2: clickToggleBtn(); break; // 点击中间按钮 case R.id.pop_voice: clickPop_voiceBtn(); break; case R.id.pop_quick: clickPop_quickBtn(); break; case R.id.pop_photo: clickPop_photoViewBtn(); break; case R.id.panytime: getAnyDate(); Intent intentp = new Intent(PayChart.this, PayChart.class); intentp.putExtra("type", 1); intentp.putExtra("datatype", datatype); intentp.putExtra("date1", date1); intentp.putExtra("date2", date2); intentp.putExtra("cwp.id", userid); startActivity(intentp); break; case R.id.example_left2: toggle(); break; case R.id.example_left: // 上一个月的按键 if (defaultMonth != 1) defaultMonth = defaultMonth - 1; else { defaultMonth = 12; defaultYear = defaultYear - 1; } Intent intentl = new Intent(PayChart.this, PayChart.class); intentl.putExtra("type", 0); intentl.putExtra("defaulty", defaultYear); intentl.putExtra("default", defaultMonth); intentl.putExtra("datatype", datatype); intentl.putExtra("cwp.id", userid); startActivity(intentl); overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left); this.finish(); break; case R.id.example_right: // 下一个月的按键 if (defaultMonth != 12) defaultMonth = defaultMonth + 1; else { defaultMonth = 1; defaultYear = defaultYear + 1; } Intent intentr = new Intent(PayChart.this, PayChart.class); intentr.putExtra("type", 0); intentr.putExtra("defaulty", defaultYear); intentr.putExtra("default", defaultMonth); intentr.putExtra("cwp.id", userid); intentr.putExtra("datatype", datatype); startActivity(intentr); overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right); this.finish(); break; } } private void clickPop_photoViewBtn() { Intent intent = new Intent(PayChart.this, AddPay.class);// 创建Intent对象 intent.putExtra("cwp.id", userid); intent.putExtra("cwp.photo", "");// 设置传递数据 startActivity(intent); } private void clickSwitchBtn(String i) { Intent intent = new Intent(PayChart.this, MainActivity.class); intent.putExtra("cwp.id", userid); intent.putExtra("cwp.Fragment", i);// 设置传递数据 startActivity(intent); overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // toggle就是程序自动判断是打开还是关闭 toggle(); // getSlidingMenu().showMenu();// show menu // getSlidingMenu().showContent();//show content return true; } return super.onOptionsItemSelected(item); } /** * 显示PopupWindow弹出菜单 */ private void showPopupWindow(View parent) { DisplayMetrics dm = parent.getResources().getDisplayMetrics(); int w_screen = dm.widthPixels; int h_screen = dm.heightPixels; // System.out // .println("你的设备w_screen:" + w_screen + " h_screen:" + h_screen); if (popWindow == null) { LayoutInflater layoutInflater = (LayoutInflater) this .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View view = layoutInflater.inflate(R.layout.popwindow_layout, null); popWinLayout = (LinearLayout) view.findViewById(R.id.popwindow); // 创建一个PopuWidow对象 float radiowith = w_screen / 480.0f; float radioheight = h_screen / 800.0f; popWindow = new PopupWindow(view, (int) (popWinLayout.getLayoutParams().width), h_screen / 4); } // 使其聚集 ,要想监听菜单里控件的事件就必须要调用此方法 popWindow.setFocusable(true); pop_voiceView = (LinearLayout) popWinLayout .findViewById(R.id.pop_voice); pop_quickView = (LinearLayout) popWinLayout .findViewById(R.id.pop_quick); pop_photoView = (LinearLayout) popWinLayout .findViewById(R.id.pop_photo); pop_voiceView.setOnClickListener(this); pop_quickView.setOnClickListener(this); pop_photoView.setOnClickListener(this); // 设置允许在外点击消失 popWindow.setOutsideTouchable(true); // 设置背景,这个是为了点击“返回Back”也能使其消失,并且并不会影响你的背景 popWindow.setBackgroundDrawable(new BitmapDrawable()); // 设置菜单显示的位置 int xPos = (w_screen - popWinLayout.getLayoutParams().width) / 2; popWindow.showAsDropDown(parent, xPos, 12); // popWindow.showAsDropDown(parent, Gravity.CENTER, 0); // 监听菜单的关闭事件 popWindow.setOnDismissListener(new OnDismissListener() { @Override public void onDismiss() { // 改变显示的按钮图片为正常状态 changeButtonImage(); } }); // 监听触屏事件 popWindow.setTouchInterceptor(new OnTouchListener() { public boolean onTouch(View view, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_OUTSIDE) { // 改变显示的按钮图片为正常状态 changeButtonImage(); } return false; } }); } /** * 点击了中间按钮 */ private void clickToggleBtn() { showPopupWindow(plusImageView); // 改变按钮显示的图片为按下时的状态 plusImageView.setImageResource(R.drawable.toolbar_plusback); toggleImageView.setImageResource(R.drawable.toolbar_btn_pressed); } /** * 改变显示的按钮图片为正常状态 */ private void changeButtonImage() { plusImageView.setImageResource(R.drawable.toolbar_plus); toggleImageView.setImageResource(R.drawable.toolbar_btn_normal); } private void clickPop_voiceBtn() { Intent intent = new Intent(PayChart.this, AddPay.class);// 创建Intent对象 intent.putExtra("cwp.id", userid); intent.putExtra("cwp.voice", "");// 设置传递数据 startActivity(intent); } private void clickPop_quickBtn() { Intent intent = new Intent(PayChart.this, AddPay.class);// 创建Intent对象 intent.putExtra("cwp.id", userid); startActivity(intent); } private void initData() { // 给布局对象设置监听 friendfeedFl.setOnClickListener(this); myfeedFl.setOnClickListener(this); homeFl.setOnClickListener(this); moreFl.setOnClickListener(this); // 给按钮图片设置监听 toggleImageView.setOnClickListener(this); myfeedFl.setSelected(true); myfeedIv.setSelected(true); } public void getAnyDate() {// 处理任意时间 date1 = year.getSelectedItem().toString() + "-" + month.getSelectedItem().toString() + "-" + day.getSelectedItem().toString(); date2 = yeare.getSelectedItem().toString() + "-" + monthe.getSelectedItem().toString() + "-" + daye.getSelectedItem().toString(); if (Integer.parseInt(year.getSelectedItem().toString()) > Integer .parseInt(yeare.getSelectedItem().toString())) { change(); } else { if (Integer.parseInt(month.getSelectedItem().toString()) > Integer .parseInt(monthe.getSelectedItem().toString())) { change(); } else { if (Integer.parseInt(day.getSelectedItem().toString()) > Integer .parseInt(daye.getSelectedItem().toString())) { change(); } } } } private void change() { String temp = date1; date1 = date2; date2 = temp; } public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键 dialogShowUtil.dialogShow("shake", "quit", "", ""); return true; } return super.onKeyDown(keyCode, event); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/PayData.java ================================================ package com.cwp.cmoneycharge; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Random; import org.achartengine.ChartFactory; import org.achartengine.GraphicalView; import org.achartengine.model.CategorySeries; import org.achartengine.model.SeriesSelection; import org.achartengine.renderer.DefaultRenderer; import org.achartengine.renderer.SimpleSeriesRenderer; import org.w3c.dom.Text; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.text.format.Time; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Adapter; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.SpinnerAdapter; import android.widget.TextView; import android.widget.Toast; import cwp.moneycharge.dao.PayDAO; import cwp.moneycharge.dao.PtypeDAO; import cwp.moneycharge.model.ActivityManager; import cwp.moneycharge.model.KindData; public class PayData extends Activity { int userid; Intent intentr; PayDAO payDAO; int defaultMonth; int defaultYear; Time time;// 获取当前时间 LinearLayout piechart, pdataselect; Button beforet, aftert, anytime; Spinner year, month, day, yeare, monthe, daye;// 界面上的任意时间 List yearlist; Adapter adapter; String date1 = "", date2 = ""; List KindDatap; DefaultRenderer mRenderer; CategorySeries mSeries; GraphicalView mChartView; PtypeDAO ptypeDAO; TextView nodata; private static int[] COLORS = new int[] { Color.rgb(180, 0, 0), Color.rgb(180, 120, 130), Color.rgb(10, 180, 170), Color.rgb(10, 180, 10), Color.rgb(220, 180, 10), Color.rgb(220, 180, 130), Color.rgb(20, 180, 130), Color.rgb(20, 18, 130), Color.rgb(255, 120, 10), Color.rgb(255, 120, 100), Color.rgb(255, 12, 100), Color.rgb(217, 190, 100), Color.rgb(50, 150, 100), Color.rgb(150, 150, 100), Color.rgb(150, 150, 190) }; public PayData() { // TODO Auto-generated constructor stub } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.paydata); SysApplication.getInstance().addActivity(this); // 在销毁队列中添加this time = new Time("GMT+8"); time.setToNow(); defaultMonth = time.month + 1;// 设置默认月份 defaultYear = time.year; beforet = (Button) findViewById(R.id.pbefore); aftert = (Button) findViewById(R.id.pafter); anytime = (Button) findViewById(R.id.panytime); year = (Spinner) findViewById(R.id.pyear); month = (Spinner) findViewById(R.id.pmonth); day = (Spinner) findViewById(R.id.pday); yeare = (Spinner) findViewById(R.id.pyeare); monthe = (Spinner) findViewById(R.id.pmonthe); daye = (Spinner) findViewById(R.id.pdaye); piechart = (LinearLayout) findViewById(R.id.pchart); nodata = (TextView) findViewById(R.id.nodata); pdataselect = (LinearLayout) findViewById(R.id.pdataselect); mSeries = new CategorySeries(""); mRenderer = new DefaultRenderer();// PieChart的主要描绘器 yearlist = new ArrayList(); // 生成年份列表 spinner payDAO = new PayDAO(PayData.this); KindDatap = new ArrayList(); ptypeDAO = new PtypeDAO(PayData.this); // 设置年 for (int i = 0; i <= 10; i++) { yearlist.add(String.valueOf(defaultYear - i)); } adapter = new ArrayAdapter(PayData.this, android.R.layout.simple_spinner_item, yearlist); year.setAdapter((SpinnerAdapter) adapter); yeare.setAdapter((SpinnerAdapter) adapter); } @Override protected void onStart() { super.onStart(); intentr = getIntent(); userid = intentr.getIntExtra("cwp.id", 100000001); defaultMonth = intentr.getIntExtra("default", defaultMonth); defaultYear = intentr.getIntExtra("defaulty", defaultYear); int type = intentr.getIntExtra("type", 0);// 为0,选择上下月,为1,选择任意时间 payDAO = new PayDAO(PayData.this); mRenderer.setZoomButtonsVisible(true); // 显示放大缩小功能按钮 mRenderer.setStartAngle(180); // 设置为水平开始 mRenderer.setDisplayValues(true); // 显示数据 mRenderer.setFitLegend(true); // 设置自动按比例缩放 mRenderer.setShowLabels(true); // 显示标签 mRenderer.setLabelsTextSize(54); // 设置轴刻度文字的大小 mRenderer.setShowLegend(false); // 不显示底部 mRenderer.setLabelsColor(Color.BLACK); // 设置轴标签颜色 mRenderer.setLegendTextSize(54); // 设置图例字体大小 mRenderer.setLegendHeight(30); // 设置图例高度 mRenderer.setChartTitleTextSize(54); // 设置饼图标题大小 if (type == 0) { KindDatap = payDAO.getKDataOnMonth(userid, defaultYear, defaultMonth); mRenderer.setChartTitle(String.valueOf(defaultYear) + "-" + String.valueOf(defaultMonth)); } else { date1 = intentr.getStringExtra("date1"); date2 = intentr.getStringExtra("date2"); KindDatap = payDAO.getKDataOnDay(userid, date1, date2); mRenderer.setChartTitle(date1 + "~" + date2); } // 数据 if (KindDatap.size() == 0) { nodata.setVisibility(View.VISIBLE); } else { double sum = 0.00; int i = 0; for (KindData kp : KindDatap) sum += kp.getAmount();// 总和 for (KindData kp : KindDatap) { mSeries.add(ptypeDAO.getOneName(userid, kp.getKindname()), kp.getAmount() / sum); SimpleSeriesRenderer renderer = new SimpleSeriesRenderer(); if (i < COLORS.length) { renderer.setColor(COLORS[i]); } else { renderer.setColor(getRandomColor()); } renderer.setChartValuesFormat(NumberFormat.getPercentInstance());// 设置百分比 mRenderer.addSeriesRenderer(renderer);// 将最新的描绘器添加到DefaultRenderer中 i++; } mChartView = ChartFactory.getPieChartView(getApplicationContext(), mSeries, mRenderer);// 构建mChartView mRenderer.setClickEnabled(true);// 允许点击事件 mChartView.setOnClickListener(new View.OnClickListener() {// 具体内容 @Override public void onClick(View v) { SeriesSelection seriesSelection = mChartView .getCurrentSeriesAndPoint();// 获取当前的类别和指针 if (seriesSelection == null) { Toast.makeText(getApplicationContext(), "您未选择数据", Toast.LENGTH_SHORT).show(); } else { for (int i = 0; i < mSeries.getItemCount(); i++) { mRenderer.getSeriesRendererAt(i) .setHighlighted( i == seriesSelection .getPointIndex()); } mChartView.repaint(); Toast.makeText( getApplicationContext(), "您选择的是第" + (seriesSelection .getPointIndex() + 1) + " 项 " + " 百分比为 " + NumberFormat .getPercentInstance() .format(seriesSelection .getValue()), Toast.LENGTH_SHORT).show(); } } }); piechart.addView(mChartView); } beforet.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (defaultMonth != 1) defaultMonth = defaultMonth - 1; else { defaultMonth = 12; defaultYear = defaultYear - 1; } mSeries.clear(); Intent intentp = new Intent(PayData.this, PayData.class); intentp.putExtra("defaulty", defaultYear); intentp.putExtra("default", defaultMonth); intentp.putExtra("cwp.id", userid); startActivity(intentp); } }); aftert.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (defaultMonth != 12) defaultMonth = defaultMonth + 1; else { defaultMonth = 1; defaultYear = defaultYear + 1; } mSeries.clear(); Intent intentp = new Intent(PayData.this, PayData.class); intentp.putExtra("defaulty", defaultYear); intentp.putExtra("default", defaultMonth); intentp.putExtra("cwp.id", userid); startActivity(intentp); } }); anytime.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub getAnyDate(); mSeries.clear(); Intent intentp = new Intent(PayData.this, PayData.class); intentp.putExtra("type", 1); intentp.putExtra("date1", date1); intentp.putExtra("date2", date2); intentp.putExtra("cwp.id", userid); startActivity(intentp); } }); } public void getAnyDate() { date1 = year.getSelectedItem().toString() + "-" + month.getSelectedItem().toString() + "-" + day.getSelectedItem().toString(); date2 = yeare.getSelectedItem().toString() + "-" + monthe.getSelectedItem().toString() + "-" + daye.getSelectedItem().toString(); } private int getRandomColor() {// 分别产生RBG数值 Random random = new Random(); int R = random.nextInt(255); int G = random.nextInt(255); int B = random.nextInt(255); return Color.rgb(R, G, B); } public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键 Intent intent = new Intent(PayData.this, MainActivity.class); intent.putExtra("cwp.id", userid); intent.putExtra("cwp.Fragment", "2");// 设置传递数据 startActivity(intent); return true; } return super.onKeyDown(keyCode, event); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/RotateBottom.java ================================================ package com.cwp.cmoneycharge; import android.view.View; import android.widget.RelativeLayout; import com.nineoldandroids.animation.ObjectAnimator; import com.nineoldandroids.view.ViewHelper; /** * Created by lee on 2014/7/31. */ public class RotateBottom extends BaseEffects{ @Override protected void setupAnimation(View view) { getAnimatorSet().playTogether( ObjectAnimator.ofFloat(view, "rotationX",90, 0).setDuration(mDuration), ObjectAnimator.ofFloat(view, "translationY", 300, 0).setDuration(mDuration), ObjectAnimator.ofFloat(view, "alpha", 0, 1).setDuration(mDuration*3/2) ); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/SearchActivity.java ================================================ package com.cwp.cmoneycharge; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Map; import com.cwp.chart.CustomMultiChoiceDialog; import com.cwp.chart.MyAdspter; import com.cwp.chart.SystemBarTintManager; import cwp.moneycharge.dao.IncomeDAO; import cwp.moneycharge.dao.ItypeDAO; import cwp.moneycharge.dao.PayDAO; import cwp.moneycharge.dao.PtypeDAO; import cwp.moneycharge.model.Tb_income; import android.annotation.TargetApi; import android.app.Activity; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.os.Build; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.DatePicker; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; public class SearchActivity extends Activity { private String arrs[] = { "自定义时间段", "今天", "昨天", "本周", "上周", "本月", "上月", "本季", "上季", "本年" }; private boolean boos[] = { false, false, false, false, false, false, false, false, false, false }; private CustomMultiChoiceDialog.Builder multiChoiceDialogBuilder; public String contact_name; private CustomMultiChoiceDialog multiChoiceDialog; protected static final int DATE_DIALOG_ID = 0;// 创建日期对话框常量 EditText query_dialog; ListView mListView; LinearLayout mlayout; private int userid; IncomeDAO incomeDAO = new IncomeDAO(this); PtypeDAO ptypeDAO = new PtypeDAO(this); ItypeDAO itypeDAO = new ItypeDAO(this); PayDAO payDAO = new PayDAO(this);// 创建PayDAO对象 private String[] strInfos; private TextView searchincome; private TextView searchpay; private TextView seachbalance; private ArrayAdapter arrayAdapter; private Editable text; private MyAdspter adapter; private TextView search_quit; private RelativeLayout search_more; private LinearLayout search_more_list; private RelativeLayout search_list_time; private TextView search_list_time_text; private RelativeLayout search_list_starttime; private static TextView search_starttime; private RelativeLayout search_list_endtime; private static TextView search_endtime; private RelativeLayout search_list_paytype; private TextView search_paytype; private RelativeLayout search_list_incometype; private TextView search_incometype; private List spdatalistpay; private List spdatalistincome; private String[] spdatapay; private String[] spdataincome; private boolean[] paychoice; private boolean[] incomechoice; protected String searchtype; public String[] resultpay; public String[] resultincome; private int mYear; private int mMonth; private int mDay; protected String timetype; private LinearLayout search_list_timeall; private RelativeLayout search_more_close; public int defaultMonth; public String dmonth; public int defaultDay; public String dday; private Calendar c; protected String searchstate = "quit"; public boolean timeselect; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.search_activity); SystemBarTintManager mTintManager; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { setTranslucentStatus(true); } mTintManager = new SystemBarTintManager(this); mTintManager.setStatusBarTintEnabled(true); mTintManager.setStatusBarTintResource(R.color.statusbar_bg); init(); } public void init() { Intent intentr = getIntent(); userid = intentr.getIntExtra("cwp.id", 100000001); mlayout = (LinearLayout) findViewById(R.id.mlayout);// 获取金额文本框 search_list_timeall = (LinearLayout) findViewById(R.id.search_list_timeall);// 获取金额文本框 search_more_list = (LinearLayout) findViewById(R.id.search_more_list);// 获取金额文本框 search_more = (RelativeLayout) findViewById(R.id.search_more);// 获取金额文本框 search_more_close = (RelativeLayout) findViewById(R.id.search_more_close);// 获取金额文本框 search_list_time = (RelativeLayout) findViewById(R.id.search_list_time);// 获取金额文本框 search_list_starttime = (RelativeLayout) findViewById(R.id.search_list_starttime);// 获取金额文本框 search_list_endtime = (RelativeLayout) findViewById(R.id.search_list_endtime);// 获取金额文本框 search_list_paytype = (RelativeLayout) findViewById(R.id.search_list_paytype);// 获取金额文本框 search_list_incometype = (RelativeLayout) findViewById(R.id.search_list_incometype);// 获取金额文本框 mListView = (ListView) findViewById(R.id.mListView);// 获取金额文本框 query_dialog = (EditText) findViewById(R.id.query_dialog);// 获取金额文本框 searchincome = (TextView) findViewById(R.id.searchincome);// 获取金额文本框 seachbalance = (TextView) findViewById(R.id.seachbalance);// 获取金额文本框 searchpay = (TextView) findViewById(R.id.searchpay);// 获取金额文本框 search_quit = (TextView) findViewById(R.id.search_quit);// 获取金额文本框 search_list_time_text = (TextView) findViewById(R.id.search_list_time_text);// 获取金额文本框 search_starttime = (TextView) findViewById(R.id.search_starttime);// 获取金额文本框 search_endtime = (TextView) findViewById(R.id.search_endtime);// 获取金额文本框 search_paytype = (TextView) findViewById(R.id.search_paytype);// 获取金额文本框 search_incometype = (TextView) findViewById(R.id.search_incometype);// 获取金额文本框 c = Calendar.getInstance();// 获取当前系统日期 mYear = c.get(Calendar.YEAR);// 获取年份 mMonth = c.get(Calendar.MONTH) + 1;// 获取月份 mDay = c.get(Calendar.DAY_OF_MONTH);// 获取天数 search_list_endtime.setOnTouchListener(new OnTouchListener() { // 为时间文本框设置单击监听事件 @Override public boolean onTouch(View v, MotionEvent event) { showDialog(DATE_DIALOG_ID);// 显示日期选择对话框 timetype = "end"; return false; } }); search_list_starttime.setOnTouchListener(new OnTouchListener() { // 为时间文本框设置单击监听事件 @Override public boolean onTouch(View v, MotionEvent event) { showDialog(DATE_DIALOG_ID);// 显示日期选择对话框 timetype = "start"; return false; } }); spdatalistpay = ptypeDAO.getPtypeName(userid); spdatalistincome = itypeDAO.getItypeName(userid); spdatapay = spdatalistpay.toArray(new String[spdatalistpay.size()]);// 在tb_itype中按用户id读取 spdataincome = spdatalistincome.toArray(new String[spdatalistincome .size()]);// 在tb_itype中按用户id读取 search_list_time.setOnClickListener(new OnClickListener() { // 高级搜索时间列表 @Override public void onClick(View v) { showMultiChoiceDialog(v, null); } }); search_list_paytype.setOnClickListener(new OnClickListener() {// 高级搜索支出列表 @Override public void onClick(View v) { showMultiChoiceDialog(v, "pay"); searchtype = "pay"; } }); search_list_incometype.setOnClickListener(new OnClickListener() {// 高级搜索收入列表 @Override public void onClick(View v) { showMultiChoiceDialog(v, "income"); searchtype = "income"; } }); search_more_close.setOnClickListener(new OnClickListener() { // 按了更多选项 @Override public void onClick(View v) { closemore(); } }); search_more.setOnClickListener(new OnClickListener() { // 按了更多选项 @Override public void onClick(View v) { InputMethodManager imm = (InputMethodManager) getApplicationContext() .getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getWindowToken(), 0); // 强制关闭软键盘 search_more.setVisibility(View.GONE); mlayout.setVisibility(View.GONE); search_more_list.setVisibility(View.VISIBLE); search_quit.setText("开始查询"); searchstate = "search"; search_starttime.setText(mYear + "-01-01"); search_endtime.setText(mYear + "-12-31"); search_paytype.setText(""); search_incometype.setText(""); resultincome = null; resultpay = null; paychoice = null; incomechoice = null; } }); class OnClickListenernormal implements OnClickListener { // 执行查询 private String String; @Override public void onClick(View v) { if (searchstate == "quit") { SearchActivity.this.finish(); } else { if (timeselect) { try { DateCompare(search_starttime.getText(), search_endtime.getText()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // System.out.println("timeselect " // + search_starttime.getText() + " " // + search_endtime.getText()); } else { // System.out.println("2 " + search_starttime.getText() // + " " + search_endtime.getText()); } if (resultincome == null) { resultincome = new String[1]; resultincome[0] = (String) search_incometype.getText(); } if (resultpay == null) { resultpay = new String[1]; resultpay[0] = (String) search_paytype.getText(); } // for (int i = 0; i < resultincome.length; i++) { // System.out.println("收入 " + resultincome[i]); // } // for (int i = 0; i < resultpay.length; i++) { // System.out.println("支出 " + resultpay[i]); // } if (text == null) { String = ""; } else { String = text.toString(); } List listinfosall = incomeDAO.searchALL(userid, search_starttime.getText() + "", search_endtime.getText() + "", resultpay, resultincome, String); closemore(); dispay(listinfosall); } } } search_quit.setOnClickListener(new OnClickListenernormal()); mListView.setOnItemClickListener(new OnItemClickListener()// 为ListView添加项单击事件 { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { TextView txno = (TextView) view.findViewById(R.id.no); TextView txkind = (TextView) view .findViewById(R.id.kind); String strtype = ((String) txkind.getText()).substring( 1, ((String) txkind.getText()).indexOf(']')) .trim();// 从收入信息中截取收支类型 String strno = (String) txno.getText(); // 从信息中截取收支编号 Intent intent = new Intent(SearchActivity.this, AddPay.class);// 创建Intent对象 if (strtype.equals("收入")) { intent.putExtra("cwp.message", new String[] { strno, "btnininfo" });// 设置传递数据 } if (strtype.equals("支出")) { intent.putExtra("cwp.message", new String[] { strno, "btnoutinfo" });// 设置传递数据 } intent.putExtra("cwp.id", userid); intent.putExtra("cwp.search", "search"); startActivityForResult(intent, 101);// 执行Intent操作 } }); query_dialog.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // text 输入框中改变前的字符串信息 // start 输入框中改变前的字符串的起始位置 // count 输入框中改变前后的字符串改变数量一般为0 // after 输入框中改变后的字符串与起始位置的偏移量 } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // text 输入框中改变后的字符串信息 // start 输入框中改变后的字符串的起始位置 // before 输入框中改变前的字符串的位置 默认为0 // count 输入框中改变后的一共输入字符串的数量 } @Override public void afterTextChanged(Editable s) { // edit 输入结束呈现在输入框中的信息 text = s; update(text.toString()); } }); } protected void closemore() { InputMethodManager imm = (InputMethodManager) getApplicationContext() .getSystemService(Context.INPUT_METHOD_SERVICE); imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS); search_more.setVisibility(View.VISIBLE); search_more_list.setVisibility(View.GONE); search_quit.setText("取消"); searchstate = "quit"; search_more.setBackgroundColor(Color.parseColor("#00000000")); } int getQuarterInMonth(int month, boolean isQuarterStart) { int months[] = { 1, 4, 7, 10 }; if (!isQuarterStart) { months = new int[] { 3, 6, 9, 12 }; } if (month >= 2 && month <= 4) return months[0]; else if (month >= 5 && month <= 7) return months[1]; else if (month >= 8 && month <= 10) return months[2]; else return months[3]; } public void showMultiChoiceDialog(View view, String type) { // 类型选择 paychoice = new boolean[spdatalistpay.size()]; incomechoice = new boolean[spdatalistincome.size()]; for (int i = 0; i < paychoice.length; i++) { paychoice[i] = false; } for (int i = 0; i < incomechoice.length; i++) { incomechoice[i] = false; } multiChoiceDialogBuilder = new CustomMultiChoiceDialog.Builder(this); if (type == "pay") { multiChoiceDialog = multiChoiceDialogBuilder .setTitle("收入类别") .setMultiChoiceItems(true, spdatapay, paychoice, null, true) .setPositiveButton("确定", new PositiveClickListener()) .setNegativeButton("取消", null).create(); } else if (type == "income") { multiChoiceDialog = multiChoiceDialogBuilder .setTitle("支出类别") .setMultiChoiceItems(true, spdataincome, incomechoice, null, true) .setPositiveButton("确定", new PositiveClickListener()) .setNegativeButton("取消", null).create(); } else { multiChoiceDialog = multiChoiceDialogBuilder.setTitle("时间范围") .setMultiChoiceItems(false, arrs, boos, new onitem(), true) .setPositiveButton(null, null) .setNegativeButton(null, null).create(); } multiChoiceDialog.getWindow().setBackgroundDrawable( new BitmapDrawable()); multiChoiceDialog.show(); } class PositiveClickListener implements DialogInterface.OnClickListener { // 点确定按钮 @Override public void onClick(DialogInterface dialog, int which) { if (CustomMultiChoiceDialog.Builder.getisMultiChoice()) { if (searchtype == "pay") { boos = multiChoiceDialogBuilder.getCheckedItems(); int j1 = 0, j2 = 0; for (int i = 0; i < boos.length; i++) { if (boos[i]) { j1++; } } resultpay = new String[j1]; for (int i = 0; i < boos.length; i++) { if (boos[i]) { resultpay[j2] = spdatapay[i]; j2++; } } if (j1 > 1) { search_paytype.setText(resultpay[0] + "," + resultpay[1] + "..."); } else { if (resultpay.length != 0) { search_paytype.setText(resultpay[0]); } else { search_paytype.setText("早餐"); } } } else if (searchtype == "income") { boos = multiChoiceDialogBuilder.getCheckedItems(); int j1 = 0, j2 = 0; for (int i = 0; i < boos.length; i++) { if (boos[i]) { j1++; } } resultincome = new String[j1]; for (int i = 0; i < boos.length; i++) { if (boos[i]) { resultincome[j2] = spdataincome[i]; j2++; } } if (j1 > 1) { search_incometype.setText(resultincome[0] + "," + resultincome[1] + "..."); } else { if (resultincome.length != 0) { search_incometype.setText(resultincome[0]); } else { search_incometype.setText("早餐"); } } } } else { String s = CustomMultiChoiceDialog.Builder.getcontact_name(); // alert(MainActivity.this, s); } } } class onitem implements OnItemClickListener { // 时间范围响应事件 @Override public void onItemClick(AdapterView parent, View view, int position, long id) { TextView cn = (TextView) view.findViewById(R.id.contact_name); search_list_time_text.setText(cn.getText()); switch (position) { case 0: // 自定义时间 search_starttime.setText(mYear + "-01-01"); search_endtime.setText(mYear + "-12-31"); search_list_timeall.setVisibility(view.VISIBLE); timeselect = true; break; case 1:// 今天 search_list_timeall.setVisibility(view.GONE); timeselect = false; search_starttime.setText(incomeDAO.gettime(mYear, mMonth, mDay, false, false)); search_endtime.setText(incomeDAO.gettime(mYear, mMonth, mDay, false, false)); break; case 2:// 昨天 search_list_timeall.setVisibility(view.GONE); timeselect = false; if (mDay == 1) { search_starttime.setText(incomeDAO.gettime(mYear, mMonth - 1, mDay, false, true)); search_endtime.setText(incomeDAO.gettime(mYear, mMonth - 1, mDay, false, true)); } else { search_starttime.setText(incomeDAO.gettime(mYear, mMonth, mDay - 1, false, false)); search_endtime.setText(incomeDAO.gettime(mYear, mMonth, mDay - 1, false, false)); } // System.out.println(search_starttime.getText() + " " // + search_endtime.getText()); break; case 3:// 本周 search_list_timeall.setVisibility(view.GONE); timeselect = false; int n = 0; // n为推迟的周数,0本周,-1向前推迟一周,1下周,依次类推 c.add(Calendar.DATE, n * 7); // 想周几,这里就传几Calendar.MONDAY(TUESDAY...) c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); search_starttime.setText(incomeDAO.gettime( c.get(Calendar.YEAR), (c.get(Calendar.MONTH) + 1), c.get(Calendar.DAY_OF_MONTH), false, false)); c.add(Calendar.DATE, 6); search_endtime.setText(incomeDAO.gettime(c.get(Calendar.YEAR), (c.get(Calendar.MONTH) + 1), c.get(Calendar.DAY_OF_MONTH), false, false)); break; case 4:// 上周 timeselect = false; search_list_timeall.setVisibility(view.GONE); // n为推迟的周数,0本周,-1向前推迟一周,1下周,依次类推 c.add(Calendar.DATE, (-1) * 7); // 想周几,这里就传几Calendar.MONDAY(TUESDAY...) c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); search_starttime.setText(incomeDAO.gettime( c.get(Calendar.YEAR), (c.get(Calendar.MONTH) + 1), c.get(Calendar.DAY_OF_MONTH), false, false)); c.add(Calendar.DATE, 6); search_endtime.setText(incomeDAO.gettime(c.get(Calendar.YEAR), (c.get(Calendar.MONTH) + 1), c.get(Calendar.DAY_OF_MONTH), false, false)); break; case 5:// 本月 timeselect = false; search_list_timeall.setVisibility(view.GONE); search_starttime.setText(incomeDAO.gettime(mYear, mMonth, mDay, true, false)); search_endtime.setText(incomeDAO.gettime(mYear, mMonth, mDay, false, true)); break; case 6:// 上月 timeselect = false; search_list_timeall.setVisibility(view.GONE); search_starttime.setText(incomeDAO.gettime(mYear, mMonth - 1, mDay, true, false)); search_endtime.setText(incomeDAO.gettime(mYear, mMonth - 1, mDay, false, true)); break; case 7:// 本季 timeselect = false; search_list_timeall.setVisibility(view.GONE); Calendar calendar = new GregorianCalendar(); calendar.setTime(new Date()); int month = getQuarterInMonth(calendar.get(Calendar.MONTH) + 1, true); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, 1); search_starttime.setText(incomeDAO.gettime( calendar.get(Calendar.YEAR), (calendar.get(Calendar.MONTH) + 1), calendar.get(Calendar.DAY_OF_MONTH), false, false)); // 季度末 calendar.setTime(new Date()); month = getQuarterInMonth(calendar.get(Calendar.MONTH) + 1, false); calendar.set(Calendar.MONTH, month + 1); calendar.set(Calendar.DAY_OF_MONTH, 0); search_endtime.setText(incomeDAO.gettime( calendar.get(Calendar.YEAR), (calendar.get(Calendar.MONTH) + 1), calendar.get(Calendar.DAY_OF_MONTH), false, false)); break; case 8:// 上季 timeselect = false; search_list_timeall.setVisibility(view.GONE); Calendar calendar2 = new GregorianCalendar(); calendar2.setTime(new Date()); int month2 = getQuarterInMonth( calendar2.get(calendar2.MONTH) + 1, true); calendar2.set(calendar2.MONTH, month2 - 3); calendar2.set(calendar2.DAY_OF_MONTH, 1); search_starttime.setText(incomeDAO.gettime( calendar2.get(calendar2.YEAR), (calendar2.get(calendar2.MONTH) + 1), calendar2.get(calendar2.DAY_OF_MONTH), false, false)); calendar2.setTime(new Date()); month2 = getQuarterInMonth(calendar2.get(calendar2.MONTH) + 1, false); calendar2.set(calendar2.MONTH, month2 - 2); calendar2.set(calendar2.DAY_OF_MONTH, 0); search_endtime.setText(incomeDAO.gettime( calendar2.get(calendar2.YEAR), (calendar2.get(calendar2.MONTH) + 1), calendar2.get(calendar2.DAY_OF_MONTH), false, false)); break; case 9:// 上年 timeselect = false; search_list_timeall.setVisibility(view.GONE); search_starttime.setText(incomeDAO.gettime(mYear - 1, 1, 1, false, false)); search_endtime.setText(incomeDAO.gettime(mYear - 1, 12, 31, false, false)); break; } multiChoiceDialog.dismiss(); } } protected void update(String string) { List listinfos2 = incomeDAO.search(userid, string); dispay(listinfos2); } private void dispay(List listinfos2) { mlayout.setVisibility(View.VISIBLE); search_more.setBackgroundColor(Color.parseColor("#e8e8e8")); List> list = new ArrayList>(); int m = 0, income = 0, pay = 0;// 定义一个开始标识 strInfos = new String[listinfos2.size()]; if (listinfos2.size() == 0) { // 处理listview seachbalance.setText("¥ 0.0"); searchpay.setText("¥ 0.0"); searchincome.setText("¥ 0.0"); mListView.setVisibility(View.GONE); } else { mListView.setVisibility(View.VISIBLE); for (Tb_income tb_income : listinfos2) {// 遍历List泛型集合 // 将收入相关信息组合成一个字符串,存储到字符串数组的相应位置 if (tb_income.getKind().equals("收入")) { // 收入 Map map = new HashMap(); map.put("img", itypeDAO.getOneImg(userid, tb_income.getType())); map.put("no", tb_income.getNo() + ""); map.put("kind", "[" + tb_income.getKind() + "]"); map.put("address", tb_income.getHandler()); map.put("money", "¥ " + tb_income.getMoney2() + "元"); map.put("title", itypeDAO.getOneName(userid, tb_income.getType())); map.put("info", tb_income.getTime()); map.put("date", FragmentPage3.gofordate(tb_income.getTime())); list.add(map); income += tb_income.getMoney(); m++;// 标识加1 } else { // 支出 Map map = new HashMap(); map.put("img", ptypeDAO.getOneImg(userid, tb_income.getType())); map.put("no", tb_income.getNo() + ""); map.put("kind", "[" + tb_income.getKind() + "]"); map.put("address", tb_income.getHandler()); map.put("money", "¥ " + tb_income.getMoney2() + "元"); map.put("title", ptypeDAO.getOneName(userid, tb_income.getType())); map.put("info", tb_income.getTime()); map.put("date", FragmentPage3.gofordate(tb_income.getTime())); list.add(map); pay += tb_income.getMoney(); m++;// 标识加1 } } seachbalance.setText("¥ " + String.valueOf(income - pay)); searchpay.setText("¥ " + String.valueOf(-pay)); searchincome.setText("¥ " + String.valueOf(income)); adapter = new MyAdspter(this, list, true); mListView.setAdapter(adapter); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); if (resultCode == 3) { if (text != null) { update(text.toString()); } } } DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { mYear = year;// 为年份赋值 mMonth = monthOfYear;// 为月份赋值 mDay = dayOfMonth;// 为天赋值 updateDisplay();// 显示设置的日期 } }; @Override protected Dialog onCreateDialog(int id)// 重写onCreateDialog方法 { switch (id) { case DATE_DIALOG_ID:// 弹出日期选择对话框 return new DatePickerDialog(this, AlertDialog.THEME_HOLO_LIGHT, mDateSetListener, mYear, mMonth, mDay); } return null; } private void updateDisplay() { if (timetype == "start") { search_starttime.setText(incomeDAO.gettime(mYear, mMonth + 1, mDay, false, false)); } else { search_endtime.setText(incomeDAO.gettime(mYear, mMonth + 1, mDay, false, false)); } } public static void DateCompare(CharSequence s1, CharSequence s2) throws Exception { // 设定时间的模板 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 得到指定模范的时间 Date d1 = sdf.parse(s1 + ""); Date d2 = sdf.parse(s2 + ""); // 比较 if (d1.getTime() - d2.getTime() > 0) { CharSequence a = search_starttime.getText(); search_starttime.setText(search_endtime.getText()); search_endtime.setText(a); } } @TargetApi(19) private void setTranslucentStatus(boolean on) { Window win = getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; if (on) { winParams.flags |= bits; } else { winParams.flags &= ~bits; } win.setAttributes(winParams); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/SettingActivity.java ================================================ package com.cwp.cmoneycharge; import com.baidu.voicerecognition.android.ui.BaiduASRDigitalDialog; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.Spinner; /** * Demo调整识别参数使用,开发逤?须关注 * * @author yangliang02 */ public class SettingActivity extends Activity implements OnCheckedChangeListener { private Spinner propTypeSpinner; private Spinner dialogThemeSpinner; private Spinner languageSpinner; private CheckBox startSoundCheckBox; private CheckBox endSoundCheckBox; private CheckBox dialogTipsCheckBox; private CheckBox showVolCheckBox; int userid, type; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.voice_setting); Intent intentr = getIntent(); userid = intentr.getIntExtra("cwp.id", 100000001); SysApplication.getInstance().addActivity(this); // 在销毁队列中添加this startSoundCheckBox = (CheckBox) findViewById(R.id.cb_play_start_sound); startSoundCheckBox.setChecked(Config.PLAY_START_SOUND); startSoundCheckBox.setOnCheckedChangeListener(this); endSoundCheckBox = (CheckBox) findViewById(R.id.cb_play_end_sound); endSoundCheckBox.setChecked(Config.PLAY_END_SOUND); endSoundCheckBox.setOnCheckedChangeListener(this); dialogTipsCheckBox = (CheckBox) findViewById(R.id.cb_dialog_tips_sound); dialogTipsCheckBox.setChecked(Config.DIALOG_TIPS_SOUND); dialogTipsCheckBox.setOnCheckedChangeListener(this); showVolCheckBox = (CheckBox) findViewById(R.id.cb_show_vol); showVolCheckBox.setChecked(Config.SHOW_VOL); showVolCheckBox.setOnCheckedChangeListener(this); propTypeSpinner = (Spinner) this.findViewById(R.id.propType); propTypeSpinner.setSelection(Config.getCurrentPropIndex()); propTypeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { Config.setCurrentPropIndex(position); } @Override public void onNothingSelected(AdapterView parent) { // TODO Auto-generated method stub } }); languageSpinner = (Spinner) this.findViewById(R.id.languages); languageSpinner.setSelection(Config.getCurrentLanguageIndex()); languageSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { Config.setCurrentLanguageIndex(position); } @Override public void onNothingSelected(AdapterView parent) { // TODO Auto-generated method stub } }); int selection = 0; switch (Config.DIALOG_THEME) { case BaiduASRDigitalDialog.THEME_BLUE_DEEPBG: selection = 0; break; case BaiduASRDigitalDialog.THEME_BLUE_LIGHTBG: selection = 1; break; case BaiduASRDigitalDialog.THEME_GREEN_DEEPBG: selection = 2; break; case BaiduASRDigitalDialog.THEME_GREEN_LIGHTBG: selection = 3; break; case BaiduASRDigitalDialog.THEME_ORANGE_DEEPBG: selection = 4; break; case BaiduASRDigitalDialog.THEME_ORANGE_LIGHTBG: selection = 5; break; case BaiduASRDigitalDialog.THEME_RED_DEEPBG: selection = 6; break; case BaiduASRDigitalDialog.THEME_RED_LIGHTBG: selection = 7; break; default: break; } dialogThemeSpinner = (Spinner) this.findViewById(R.id.dialogTheme); dialogThemeSpinner.setSelection(selection); dialogThemeSpinner .setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView parent, View view, int position, long id) { int result = BaiduASRDigitalDialog.THEME_BLUE_DEEPBG; switch (position) { case 0: result = BaiduASRDigitalDialog.THEME_BLUE_DEEPBG; break; case 1: result = BaiduASRDigitalDialog.THEME_BLUE_LIGHTBG; break; case 2: result = BaiduASRDigitalDialog.THEME_GREEN_DEEPBG; break; case 3: result = BaiduASRDigitalDialog.THEME_GREEN_LIGHTBG; break; case 4: result = BaiduASRDigitalDialog.THEME_ORANGE_DEEPBG; break; case 5: result = BaiduASRDigitalDialog.THEME_ORANGE_LIGHTBG; break; case 6: result = BaiduASRDigitalDialog.THEME_RED_DEEPBG; break; case 7: result = BaiduASRDigitalDialog.THEME_RED_LIGHTBG; break; default: break; } Config.DIALOG_THEME = result; } @Override public void onNothingSelected(AdapterView parent) { // TODO Auto-generated method stub } }); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (buttonView == showVolCheckBox) { Config.SHOW_VOL = isChecked; } if (buttonView == startSoundCheckBox) { Config.PLAY_START_SOUND = isChecked; } if (buttonView == endSoundCheckBox) { Config.PLAY_END_SOUND = isChecked; } if (buttonView == dialogTipsCheckBox) { Config.DIALOG_TIPS_SOUND = isChecked; } } public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键 Intent intent = new Intent(SettingActivity.this, MainActivity.class); intent.putExtra("cwp.id", userid); intent.putExtra("cwp.Fragment", "4");// 设置传递数据 startActivity(intent); return true; } return super.onKeyDown(keyCode, event); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/Shake.java ================================================ package com.cwp.cmoneycharge; import android.view.View; import com.nineoldandroids.animation.ObjectAnimator; /** * Created by lee on 2014/7/31. */ public class Shake extends BaseEffects{ @Override protected void setupAnimation(View view) { getAnimatorSet().playTogether( ObjectAnimator.ofFloat(view, "translationX", 0, .10f, -25, .26f, 25,.42f, -25, .58f, 25,.74f,-25,.90f,1,0).setDuration(mDuration) ); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/SlideTop.java ================================================ package com.cwp.cmoneycharge; import android.view.View; import com.nineoldandroids.animation.ObjectAnimator; /** * Created by lee on 2014/7/31. */ public class SlideTop extends BaseEffects{ @Override protected void setupAnimation(View view) { getAnimatorSet().playTogether( ObjectAnimator.ofFloat(view, "translationY", -300, 0).setDuration(mDuration), ObjectAnimator.ofFloat(view, "alpha", 0, 1).setDuration(mDuration*3/2) ); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/cmoneycharge/SysApplication.java ================================================ package com.cwp.cmoneycharge; import java.util.LinkedList; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.app.Application; import android.content.DialogInterface; import android.content.Intent; public class SysApplication extends Application { private List mList = new LinkedList(); private static SysApplication instance; private SysApplication() { } public synchronized static SysApplication getInstance() { if (null == instance) { instance = new SysApplication(); } return instance; } // add Activity public void addActivity(Activity activity) { mList.add(activity); } public void exit() { try { for (Activity activity : mList) { if (activity != null) activity.finish(); } } catch (Exception e) { e.printStackTrace(); } finally { System.exit(0); } } @Override public void onLowMemory() { super.onLowMemory(); System.gc(); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/pattern/CreateGesturePasswordActivity.java ================================================ package com.cwp.pattern; import java.util.ArrayList; import java.util.List; import com.cwp.chart.SystemBarTintManager; import com.cwp.cmoneycharge.CrashApplication; import com.cwp.cmoneycharge.R; import com.cwp.cmoneycharge.SysApplication; import com.cwp.pattern.LockPatternView.Cell; import com.cwp.pattern.LockPatternView.DisplayMode; import android.annotation.TargetApi; import android.app.Activity; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class CreateGesturePasswordActivity extends Activity implements OnClickListener { private static final int ID_EMPTY_MESSAGE = -1; private static final String KEY_UI_STAGE = "uiStage"; private static final String KEY_PATTERN_CHOICE = "chosenPattern"; private LockPatternView mLockPatternView; private Button mFooterRightButton; private Button mFooterLeftButton; protected TextView mHeaderText; protected List mChosenPattern = null; private Toast mToast; private Stage mUiStage = Stage.Introduction; private View mPreviewViews[][] = new View[3][3]; /** * The patten used during the help screen to show how to draw a pattern. */ private final List mAnimatePattern = new ArrayList(); /** * The states of the left footer button. */ enum LeftButtonMode { Cancel(android.R.string.cancel, true), CancelDisabled( android.R.string.cancel, false), Retry( R.string.lockpattern_retry_button_text, true), RetryDisabled( R.string.lockpattern_retry_button_text, false), Gone( ID_EMPTY_MESSAGE, false); /** * @param text * The displayed text for this mode. * @param enabled * Whether the button should be enabled. */ LeftButtonMode(int text, boolean enabled) { this.text = text; this.enabled = enabled; } final int text; final boolean enabled; } /** * The states of the right button. */ enum RightButtonMode { Continue(R.string.lockpattern_continue_button_text, true), ContinueDisabled( R.string.lockpattern_continue_button_text, false), Confirm( R.string.lockpattern_confirm_button_text, true), ConfirmDisabled( R.string.lockpattern_confirm_button_text, false), Ok( android.R.string.ok, true); /** * @param text * The displayed text for this mode. * @param enabled * Whether the button should be enabled. */ RightButtonMode(int text, boolean enabled) { this.text = text; this.enabled = enabled; } final int text; final boolean enabled; } /** * Keep track internally of where the user is in choosing a pattern. */ protected enum Stage { Introduction(R.string.lockpattern_recording_intro_header, LeftButtonMode.Cancel, RightButtonMode.ContinueDisabled, ID_EMPTY_MESSAGE, true), HelpScreen( R.string.lockpattern_settings_help_how_to_record, LeftButtonMode.Gone, RightButtonMode.Ok, ID_EMPTY_MESSAGE, false), ChoiceTooShort( R.string.lockpattern_recording_incorrect_too_short, LeftButtonMode.Retry, RightButtonMode.ContinueDisabled, ID_EMPTY_MESSAGE, true), FirstChoiceValid( R.string.lockpattern_pattern_entered_header, LeftButtonMode.Retry, RightButtonMode.Continue, ID_EMPTY_MESSAGE, false), NeedToConfirm( R.string.lockpattern_need_to_confirm, LeftButtonMode.Cancel, RightButtonMode.ConfirmDisabled, ID_EMPTY_MESSAGE, true), ConfirmWrong( R.string.lockpattern_need_to_unlock_wrong, LeftButtonMode.Cancel, RightButtonMode.ConfirmDisabled, ID_EMPTY_MESSAGE, true), ChoiceConfirmed( R.string.lockpattern_pattern_confirmed_header, LeftButtonMode.Cancel, RightButtonMode.Confirm, ID_EMPTY_MESSAGE, false); /** * @param headerMessage * The message displayed at the top. * @param leftMode * The mode of the left button. * @param rightMode * The mode of the right button. * @param footerMessage * The footer message. * @param patternEnabled * Whether the pattern widget is enabled. */ Stage(int headerMessage, LeftButtonMode leftMode, RightButtonMode rightMode, int footerMessage, boolean patternEnabled) { this.headerMessage = headerMessage; this.leftMode = leftMode; this.rightMode = rightMode; this.footerMessage = footerMessage; this.patternEnabled = patternEnabled; } final int headerMessage; final LeftButtonMode leftMode; final RightButtonMode rightMode; final int footerMessage; final boolean patternEnabled; } private void showToast(CharSequence message) { if (null == mToast) { mToast = Toast.makeText(this, message, Toast.LENGTH_SHORT); } else { mToast.setText(message); } mToast.show(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.gesturepassword_create); SysApplication.getInstance().addActivity(this); // 在销毁队列中添加this SystemBarTintManager mTintManager; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { setTranslucentStatus(true); } mTintManager = new SystemBarTintManager(this); mTintManager.setStatusBarTintEnabled(true); mTintManager.setStatusBarTintResource(R.color.statusbar_bg); // 初始化演示动画 mAnimatePattern.add(LockPatternView.Cell.of(0, 0)); mAnimatePattern.add(LockPatternView.Cell.of(0, 1)); mAnimatePattern.add(LockPatternView.Cell.of(1, 1)); mAnimatePattern.add(LockPatternView.Cell.of(2, 1)); mAnimatePattern.add(LockPatternView.Cell.of(2, 2)); mLockPatternView = (LockPatternView) this .findViewById(R.id.gesturepwd_create_lockview); mHeaderText = (TextView) findViewById(R.id.gesturepwd_create_text); mLockPatternView.setOnPatternListener(mChooseNewLockPatternListener); mLockPatternView.setTactileFeedbackEnabled(true); mFooterRightButton = (Button) this.findViewById(R.id.right_btn); mFooterLeftButton = (Button) this.findViewById(R.id.reset_btn); mFooterRightButton.setOnClickListener(this); mFooterLeftButton.setOnClickListener(this); initPreviewViews(); if (savedInstanceState == null) { updateStage(Stage.Introduction); updateStage(Stage.HelpScreen); } else { // restore from previous state final String patternString = savedInstanceState .getString(KEY_PATTERN_CHOICE); if (patternString != null) { mChosenPattern = LockPatternUtils .stringToPattern(patternString); } updateStage(Stage.values()[savedInstanceState.getInt(KEY_UI_STAGE)]); } } private void initPreviewViews() { mPreviewViews = new View[3][3]; mPreviewViews[0][0] = findViewById(R.id.gesturepwd_setting_preview_0); mPreviewViews[0][1] = findViewById(R.id.gesturepwd_setting_preview_1); mPreviewViews[0][2] = findViewById(R.id.gesturepwd_setting_preview_2); mPreviewViews[1][0] = findViewById(R.id.gesturepwd_setting_preview_3); mPreviewViews[1][1] = findViewById(R.id.gesturepwd_setting_preview_4); mPreviewViews[1][2] = findViewById(R.id.gesturepwd_setting_preview_5); mPreviewViews[2][0] = findViewById(R.id.gesturepwd_setting_preview_6); mPreviewViews[2][1] = findViewById(R.id.gesturepwd_setting_preview_7); mPreviewViews[2][2] = findViewById(R.id.gesturepwd_setting_preview_8); } private void updatePreviewViews() { if (mChosenPattern == null) return; Log.i("way", "result = " + mChosenPattern.toString()); for (LockPatternView.Cell cell : mChosenPattern) { Log.i("way", "cell.getRow() = " + cell.getRow() + ", cell.getColumn() = " + cell.getColumn()); mPreviewViews[cell.getRow()][cell.getColumn()] .setBackgroundResource(R.drawable.gesture_create_grid_selected); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(KEY_UI_STAGE, mUiStage.ordinal()); if (mChosenPattern != null) { outState.putString(KEY_PATTERN_CHOICE, LockPatternUtils.patternToString(mChosenPattern)); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { if (mUiStage == Stage.HelpScreen) { updateStage(Stage.Introduction); return true; } } if (keyCode == KeyEvent.KEYCODE_MENU && mUiStage == Stage.Introduction) { updateStage(Stage.HelpScreen); return true; } return false; } private Runnable mClearPatternRunnable = new Runnable() { public void run() { mLockPatternView.clearPattern(); } }; protected LockPatternView.OnPatternListener mChooseNewLockPatternListener = new LockPatternView.OnPatternListener() { public void onPatternStart() { mLockPatternView.removeCallbacks(mClearPatternRunnable); patternInProgress(); } public void onPatternCleared() { mLockPatternView.removeCallbacks(mClearPatternRunnable); } public void onPatternDetected(List pattern) { if (pattern == null) return; // Log.i("way", "result = " + pattern.toString()); if (mUiStage == Stage.NeedToConfirm || mUiStage == Stage.ConfirmWrong) { if (mChosenPattern == null) throw new IllegalStateException( "null chosen pattern in stage 'need to confirm"); if (mChosenPattern.equals(pattern)) { updateStage(Stage.ChoiceConfirmed); } else { updateStage(Stage.ConfirmWrong); } } else if (mUiStage == Stage.Introduction || mUiStage == Stage.ChoiceTooShort) { if (pattern.size() < LockPatternUtils.MIN_LOCK_PATTERN_SIZE) { updateStage(Stage.ChoiceTooShort); } else { mChosenPattern = new ArrayList( pattern); updateStage(Stage.FirstChoiceValid); } } else { throw new IllegalStateException("Unexpected stage " + mUiStage + " when " + "entering the pattern."); } } private void patternInProgress() { mHeaderText.setText(R.string.lockpattern_recording_inprogress); mFooterLeftButton.setEnabled(false); mFooterRightButton.setEnabled(false); } @Override public void onPatternCellAdded(List pattern) { } }; private void updateStage(Stage stage) { mUiStage = stage; if (stage == Stage.ChoiceTooShort) { mHeaderText.setText(getResources().getString(stage.headerMessage, LockPatternUtils.MIN_LOCK_PATTERN_SIZE)); } else { mHeaderText.setText(stage.headerMessage); } if (stage.leftMode == LeftButtonMode.Gone) { mFooterLeftButton.setVisibility(View.GONE); } else { mFooterLeftButton.setVisibility(View.VISIBLE); mFooterLeftButton.setText(stage.leftMode.text); mFooterLeftButton.setEnabled(stage.leftMode.enabled); } mFooterRightButton.setText(stage.rightMode.text); mFooterRightButton.setEnabled(stage.rightMode.enabled); // same for whether the patten is enabled if (stage.patternEnabled) { mLockPatternView.enableInput(); } else { mLockPatternView.disableInput(); } mLockPatternView.setDisplayMode(DisplayMode.Correct); switch (mUiStage) { case Introduction: mLockPatternView.clearPattern(); break; case HelpScreen: mLockPatternView.setPattern(DisplayMode.Animate, mAnimatePattern); break; case ChoiceTooShort: mLockPatternView.setDisplayMode(DisplayMode.Wrong); postClearPatternRunnable(); break; case FirstChoiceValid: break; case NeedToConfirm: mLockPatternView.clearPattern(); updatePreviewViews(); break; case ConfirmWrong: mLockPatternView.setDisplayMode(DisplayMode.Wrong); postClearPatternRunnable(); break; case ChoiceConfirmed: break; } } // clear the wrong pattern unless they have started a new one // already private void postClearPatternRunnable() { mLockPatternView.removeCallbacks(mClearPatternRunnable); mLockPatternView.postDelayed(mClearPatternRunnable, 2000); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.reset_btn: if (mUiStage.leftMode == LeftButtonMode.Retry) { mChosenPattern = null; mLockPatternView.clearPattern(); updateStage(Stage.Introduction); } else if (mUiStage.leftMode == LeftButtonMode.Cancel) { // They are canceling the entire wizard finish(); } else { throw new IllegalStateException( "left footer button pressed, but stage of " + mUiStage + " doesn't make sense"); } break; case R.id.right_btn: if (mUiStage.rightMode == RightButtonMode.Continue) { if (mUiStage != Stage.FirstChoiceValid) { throw new IllegalStateException("expected ui stage " + Stage.FirstChoiceValid + " when button is " + RightButtonMode.Continue); } updateStage(Stage.NeedToConfirm); } else if (mUiStage.rightMode == RightButtonMode.Confirm) { if (mUiStage != Stage.ChoiceConfirmed) { throw new IllegalStateException("expected ui stage " + Stage.ChoiceConfirmed + " when button is " + RightButtonMode.Confirm); } saveChosenPatternAndFinish(); } else if (mUiStage.rightMode == RightButtonMode.Ok) { if (mUiStage != Stage.HelpScreen) { throw new IllegalStateException( "Help screen is only mode with ok button, but " + "stage is " + mUiStage); } mLockPatternView.clearPattern(); mLockPatternView.setDisplayMode(DisplayMode.Correct); updateStage(Stage.Introduction); } break; } } @TargetApi(19) private void setTranslucentStatus(boolean on) { Window win = getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; if (on) { winParams.flags |= bits; } else { winParams.flags &= ~bits; } win.setAttributes(winParams); } private void saveChosenPatternAndFinish() { CrashApplication.getInstance().getLockPatternUtils() .saveLockPattern(mChosenPattern); showToast("密码设置成功"); this.setResult(3);// this.setResult(int resultCode),resultCode 可以自定义 this.finish(); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/pattern/GuideGesturePasswordActivity.java ================================================ package com.cwp.pattern; import com.cwp.chart.SystemBarTintManager; import com.cwp.cmoneycharge.About; import com.cwp.cmoneycharge.CrashApplication; import com.cwp.cmoneycharge.R; import com.cwp.cmoneycharge.SysApplication; import android.annotation.TargetApi; import android.app.Activity; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.View.OnClickListener; import android.widget.Toast; public class GuideGesturePasswordActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.gesturepassword_guide); SysApplication.getInstance().addActivity(this); // 在销毁队列中添加this SystemBarTintManager mTintManager; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { setTranslucentStatus(true); } mTintManager = new SystemBarTintManager(this); mTintManager.setStatusBarTintEnabled(true); mTintManager.setStatusBarTintResource(R.color.statusbar_bg); findViewById(R.id.gesturepwd_guide_btn).setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { CrashApplication.getInstance().getLockPatternUtils() .clearLock(); Intent intent = new Intent( GuideGesturePasswordActivity.this, CreateGesturePasswordActivity.class); // 打开新的Activity startActivityForResult(intent, 1); } }); } @TargetApi(19) private void setTranslucentStatus(boolean on) { Window win = getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; if (on) { winParams.flags |= bits; } else { winParams.flags &= ~bits; } win.setAttributes(winParams); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); // System.out.println("asdrequestCode" + requestCode + " " + resultCode); if (requestCode == 1) { if (resultCode == 3) { this.setResult(3); this.finish(); } } } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/pattern/LockPatternUtils.java ================================================ package com.cwp.pattern; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import android.content.Context; import android.os.FileObserver; import android.util.Log; /** * 图案解锁加密、解密工具类 * * @author way * */ public class LockPatternUtils { private static final String TAG = "LockPatternUtils"; private static final String LOCK_PATTERN_FILE = "gesture.key"; /** * The minimum number of dots in a valid pattern. */ public static final int MIN_LOCK_PATTERN_SIZE = 4; /** * The maximum number of incorrect attempts before the user is prevented * from trying again for {@link #FAILED_ATTEMPT_TIMEOUT_MS}. */ public static final int FAILED_ATTEMPTS_BEFORE_TIMEOUT = 5; /** * The minimum number of dots the user must include in a wrong pattern * attempt for it to be counted against the counts that affect * {@link #FAILED_ATTEMPTS_BEFORE_TIMEOUT} and * {@link #FAILED_ATTEMPTS_BEFORE_RESET} */ public static final int MIN_PATTERN_REGISTER_FAIL = MIN_LOCK_PATTERN_SIZE; /** * How long the user is prevented from trying again after entering the wrong * pattern too many times. */ public static final long FAILED_ATTEMPT_TIMEOUT_MS = 30000L; private static File sLockPatternFilename; private static final AtomicBoolean sHaveNonZeroPatternFile = new AtomicBoolean( false); private static FileObserver sPasswordObserver; private static class LockPatternFileObserver extends FileObserver { public LockPatternFileObserver(String path, int mask) { super(path, mask); } @Override public void onEvent(int event, String path) { Log.d(TAG, "file path" + path); if (LOCK_PATTERN_FILE.equals(path)) { Log.d(TAG, "lock pattern file changed"); sHaveNonZeroPatternFile.set(sLockPatternFilename.length() > 0); } } } public LockPatternUtils(Context context) { if (sLockPatternFilename == null) { String dataSystemDirectory = context.getFilesDir() .getAbsolutePath(); sLockPatternFilename = new File(dataSystemDirectory , LOCK_PATTERN_FILE); sHaveNonZeroPatternFile.set(sLockPatternFilename.length() > 0); int fileObserverMask = FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_TO | FileObserver.CREATE; sPasswordObserver = new LockPatternFileObserver( dataSystemDirectory, fileObserverMask); sPasswordObserver.startWatching(); } } /** * Check to see if the user has stored a lock pattern. * * @return Whether a saved pattern exists. */ public boolean savedPatternExists() { return sHaveNonZeroPatternFile.get(); } public void clearLock() { saveLockPattern(null); } /** * Deserialize a pattern. 解密,用于保存状濊 * * @param string * The pattern serialized with {@link #patternToString} * @return The pattern. */ public static List stringToPattern(String string) { List result = new ArrayList(); 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 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 new String(res); } /** * Save a lock pattern. * * @param pattern * The new pattern to save. * @param isFallback * Specifies if this is a fallback to biometric weak */ public void saveLockPattern(List pattern) { // Compute the hash final byte[] hash = LockPatternUtils.patternToHash(pattern); try { // Write the hash to file RandomAccessFile raf = new RandomAccessFile(sLockPatternFilename, "rwd"); // Truncate the file if pattern is null, to clear the lock if (pattern == null) { raf.setLength(0); } else { raf.write(hash, 0, hash.length); } raf.close(); } catch (FileNotFoundException fnfe) { // Cant do much, unless we want to fail over to using the settings // provider Log.e(TAG, "Unable to save lock pattern to " + sLockPatternFilename); } catch (IOException ioe) { // Cant do much Log.e(TAG, "Unable to save lock pattern to " + sLockPatternFilename); } } /* * Generate an SHA-1 hash for the pattern. Not the most secure, but it is at * least a second level of protection. First level is that the file is in a * location only readable by the system process. * * @param pattern the gesture pattern. * * @return the hash of the pattern in a byte array. */ private static byte[] patternToHash(List pattern) { if (pattern == null) { return null; } 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()); } try { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] hash = md.digest(res); return hash; } catch (NoSuchAlgorithmException nsa) { return res; } } /** * Check to see if a pattern matches the saved pattern. If no pattern * exists, always returns true. * * @param pattern * The pattern to check. * @return Whether the pattern matches the stored one. */ public boolean checkPattern(List pattern) { try { // Read all the bytes from the file RandomAccessFile raf = new RandomAccessFile(sLockPatternFilename, "r"); final byte[] stored = new byte[(int) raf.length()]; int got = raf.read(stored, 0, stored.length); raf.close(); if (got <= 0) { return true; } // Compare the hash from the file with the entered pattern's hash return Arrays.equals(stored, LockPatternUtils.patternToHash(pattern)); } catch (FileNotFoundException fnfe) { return true; } catch (IOException ioe) { return true; } } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/pattern/LockPatternView.java ================================================ package com.cwp.pattern; import java.util.ArrayList; import java.util.List; import com.cwp.cmoneycharge.R; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.os.Debug; import android.os.Parcel; import android.os.Parcelable; import android.os.SystemClock; import android.util.AttributeSet; import android.util.Log; import android.view.HapticFeedbackConstants; import android.view.MotionEvent; import android.view.View; import android.view.accessibility.AccessibilityEvent; /** * Displays and detects the user's unlock attempt, which is a drag of a finger * across 9 regions of the screen. * * Is also capable of displaying a static pattern in "in progress", "wrong" or * "correct" states. * * @author way */ public class LockPatternView extends View { private static final String TAG = "LockPatternView"; // Aspect to use when rendering this view private static final int ASPECT_SQUARE = 0; // View will be the minimum of // width/height private static final int ASPECT_LOCK_WIDTH = 1; // Fixed width; height will // be minimum of (w,h) private static final int ASPECT_LOCK_HEIGHT = 2; // Fixed height; width will // be minimum of (w,h) private static final boolean PROFILE_DRAWING = false; private boolean mDrawingProfilingStarted = false; private Paint mPaint = new Paint(); private Paint mPathPaint = new Paint(); // TODO: make this common with PhoneWindow static final int STATUS_BAR_HEIGHT = 25; /** * How many milliseconds we spend animating each circle of a lock pattern if * the animating mode is set. The entire animation should take this constant * * the length of the pattern to complete. */ private static final int MILLIS_PER_CIRCLE_ANIMATING = 700; private OnPatternListener mOnPatternListener; private ArrayList mPattern = new ArrayList(9); /** * Lookup table for the circles of the pattern we are currently drawing. * This will be the cells of the complete pattern unless we are animating, * in which case we use this to hold the cells we are drawing for the in * progress animation. */ private boolean[][] mPatternDrawLookup = new boolean[3][3]; /** * the in progress point: - during interaction: where the user's finger is - * during animation: the current tip of the animating line */ private float mInProgressX = -1; private float mInProgressY = -1; private long mAnimatingPeriodStart; private DisplayMode mPatternDisplayMode = DisplayMode.Correct; private boolean mInputEnabled = true; private boolean mInStealthMode = false; private boolean mEnableHapticFeedback = false; private boolean mPatternInProgress = false; private float mDiameterFactor = 0.10f; // TODO: move to attrs private final int mStrokeAlpha = 128; private float mHitFactor = 0.6f; private float mSquareWidth; private float mSquareHeight; private Bitmap mBitmapCircleDefault; private Bitmap mBitmapCircleGreen; private Bitmap mBitmapCircleRed; private final Path mCurrentPath = new Path(); private final Rect mInvalidate = new Rect(); private int mBitmapWidth; private int mBitmapHeight; private int mAspect; private final Matrix mCircleMatrix = new Matrix(); /** * Represents a cell in the 3 X 3 matrix of the unlock pattern view. */ public static class Cell { int row; int column; // keep # objects limited to 9 static Cell[][] sCells = new Cell[3][3]; static { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { sCells[i][j] = new Cell(i, j); } } } /** * @param row * The row of the cell. * @param column * The column of the cell. */ private Cell(int row, int column) { checkRange(row, column); this.row = row; this.column = column; } public int getRow() { return row; } public int getColumn() { return column; } /** * @param row * The row of the cell. * @param column * The column of the cell. */ public static synchronized Cell of(int row, int column) { checkRange(row, column); return sCells[row][column]; } private static void checkRange(int row, int column) { if (row < 0 || row > 2) { throw new IllegalArgumentException("row must be in range 0-2"); } if (column < 0 || column > 2) { throw new IllegalArgumentException( "column must be in range 0-2"); } } public String toString() { return "(row=" + row + ",clmn=" + column + ")"; } } /** * How to display the current pattern. */ public enum DisplayMode { /** * The pattern drawn is correct (i.e draw it in a friendly color) */ Correct, /** * Animate the pattern (for demo, and help). */ Animate, /** * The pattern is wrong (i.e draw a foreboding color) */ Wrong } /** * The call back interface for detecting patterns entered by the user. */ public static interface OnPatternListener { /** * A new pattern has begun. */ void onPatternStart(); /** * The pattern was cleared. */ void onPatternCleared(); /** * The user extended the pattern currently being drawn by one cell. * * @param pattern * The pattern with newly added cell. */ void onPatternCellAdded(List pattern); /** * A pattern was detected from the user. * * @param pattern * The pattern. */ void onPatternDetected(List pattern); } public LockPatternView(Context context) { this(context, null); } public LockPatternView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LockPatternView); final String aspect = a.getString(R.styleable.LockPatternView_aspect); if ("square".equals(aspect)) { mAspect = ASPECT_SQUARE; } else if ("lock_width".equals(aspect)) { mAspect = ASPECT_LOCK_WIDTH; } else if ("lock_height".equals(aspect)) { mAspect = ASPECT_LOCK_HEIGHT; } else { mAspect = ASPECT_SQUARE; } setClickable(true); mPathPaint.setAntiAlias(true); mPathPaint.setDither(true); mPathPaint.setColor(Color.YELLOW); // TODO this should be from the style mPathPaint.setAlpha(mStrokeAlpha); mPathPaint.setStyle(Paint.Style.STROKE); mPathPaint.setStrokeJoin(Paint.Join.ROUND); mPathPaint.setStrokeCap(Paint.Cap.ROUND); mBitmapCircleDefault = getBitmapFor(R.drawable.gesture_pattern_item_bg); mBitmapCircleGreen = getBitmapFor(R.drawable.gesture_pattern_selected); mBitmapCircleRed = getBitmapFor(R.drawable.gesture_pattern_selected_wrong); // bitmaps have the size of the largest bitmap in this group final Bitmap bitmaps[] = { mBitmapCircleDefault, mBitmapCircleGreen, mBitmapCircleRed }; for (Bitmap bitmap : bitmaps) { mBitmapWidth = Math.max(mBitmapWidth, bitmap.getWidth()); mBitmapHeight = Math.max(mBitmapHeight, bitmap.getHeight()); } a.recycle(); } private Bitmap getBitmapFor(int resId) { return BitmapFactory.decodeResource(getContext().getResources(), resId); } /** * @return Whether the view is in stealth mode. */ public boolean isInStealthMode() { return mInStealthMode; } /** * @return Whether the view has tactile feedback enabled. */ public boolean isTactileFeedbackEnabled() { return mEnableHapticFeedback; } /** * Set whether the view is in stealth mode. If true, there will be no * visible feedback as the user enters the pattern. * * @param inStealthMode * Whether in stealth mode. */ public void setInStealthMode(boolean inStealthMode) { mInStealthMode = inStealthMode; } /** * Set whether the view will use tactile feedback. If true, there will be * tactile feedback as the user enters the pattern. * * @param tactileFeedbackEnabled * Whether tactile feedback is enabled */ public void setTactileFeedbackEnabled(boolean tactileFeedbackEnabled) { mEnableHapticFeedback = tactileFeedbackEnabled; } /** * Set the call back for pattern detection. * * @param onPatternListener * The call back. */ public void setOnPatternListener(OnPatternListener onPatternListener) { mOnPatternListener = onPatternListener; } /** * Set the pattern explicitely (rather than waiting for the user to input a * pattern). * * @param displayMode * How to display the pattern. * @param pattern * The pattern. */ public void setPattern(DisplayMode displayMode, List pattern) { mPattern.clear(); mPattern.addAll(pattern); clearPatternDrawLookup(); for (Cell cell : pattern) { mPatternDrawLookup[cell.getRow()][cell.getColumn()] = true; } setDisplayMode(displayMode); } /** * Set the display mode of the current pattern. This can be useful, for * instance, after detecting a pattern to tell this view whether change the * in progress result to correct or wrong. * * @param displayMode * The display mode. */ public void setDisplayMode(DisplayMode displayMode) { mPatternDisplayMode = displayMode; if (displayMode == DisplayMode.Animate) { if (mPattern.size() == 0) { throw new IllegalStateException( "you must have a pattern to " + "animate if you want to set the display mode to animate"); } mAnimatingPeriodStart = SystemClock.elapsedRealtime(); final Cell first = mPattern.get(0); mInProgressX = getCenterXForColumn(first.getColumn()); mInProgressY = getCenterYForRow(first.getRow()); clearPatternDrawLookup(); } invalidate(); } private void notifyCellAdded() { if (mOnPatternListener != null) { mOnPatternListener.onPatternCellAdded(mPattern); } sendAccessEvent(R.string.lockscreen_access_pattern_cell_added); } private void notifyPatternStarted() { if (mOnPatternListener != null) { mOnPatternListener.onPatternStart(); } sendAccessEvent(R.string.lockscreen_access_pattern_start); } private void notifyPatternDetected() { if (mOnPatternListener != null) { mOnPatternListener.onPatternDetected(mPattern); } sendAccessEvent(R.string.lockscreen_access_pattern_detected); } private void notifyPatternCleared() { if (mOnPatternListener != null) { mOnPatternListener.onPatternCleared(); } sendAccessEvent(R.string.lockscreen_access_pattern_cleared); } /** * Clear the pattern. */ public void clearPattern() { resetPattern(); } /** * Reset all pattern state. */ private void resetPattern() { mPattern.clear(); clearPatternDrawLookup(); mPatternDisplayMode = DisplayMode.Correct; invalidate(); } /** * Clear the pattern lookup table. */ private void clearPatternDrawLookup() { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { mPatternDrawLookup[i][j] = false; } } } /** * Disable input (for instance when displaying a message that will timeout * so user doesn't get view into messy state). */ public void disableInput() { mInputEnabled = false; } /** * Enable input. */ public void enableInput() { mInputEnabled = true; } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { final int width = w - getPaddingLeft() - getPaddingRight(); mSquareWidth = width / 3.0f; final int height = h - getPaddingTop() - getPaddingBottom(); mSquareHeight = height / 3.0f; } private int resolveMeasured(int measureSpec, int desired) { int result = 0; int specSize = MeasureSpec.getSize(measureSpec); switch (MeasureSpec.getMode(measureSpec)) { case MeasureSpec.UNSPECIFIED: result = desired; break; case MeasureSpec.AT_MOST: result = Math.max(specSize, desired); break; case MeasureSpec.EXACTLY: default: result = specSize; } return result; } @Override protected int getSuggestedMinimumWidth() { // View should be large enough to contain 3 side-by-side target bitmaps return 3 * mBitmapWidth; } @Override protected int getSuggestedMinimumHeight() { // View should be large enough to contain 3 side-by-side target bitmaps return 3 * mBitmapWidth; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int minimumWidth = getSuggestedMinimumWidth(); final int minimumHeight = getSuggestedMinimumHeight(); int viewWidth = resolveMeasured(widthMeasureSpec, minimumWidth); int viewHeight = resolveMeasured(heightMeasureSpec, minimumHeight); switch (mAspect) { case ASPECT_SQUARE: viewWidth = viewHeight = Math.min(viewWidth, viewHeight); break; case ASPECT_LOCK_WIDTH: viewHeight = Math.min(viewWidth, viewHeight); break; case ASPECT_LOCK_HEIGHT: viewWidth = Math.min(viewWidth, viewHeight); break; } Log.v(TAG, "LockPatternView dimensions: " + viewWidth + "x" + viewHeight); setMeasuredDimension(viewWidth, viewHeight); } /** * Determines whether the point x, y will add a new point to the current * pattern (in addition to finding the cell, also makes heuristic choices * such as filling in gaps based on current pattern). * * @param x * The x coordinate. * @param y * The y coordinate. */ private Cell detectAndAddHit(float x, float y) { final Cell cell = checkForNewHit(x, y); if (cell != null) { // check for gaps in existing pattern Cell fillInGapCell = null; final ArrayList pattern = mPattern; if (!pattern.isEmpty()) { final Cell lastCell = pattern.get(pattern.size() - 1); int dRow = cell.row - lastCell.row; int dColumn = cell.column - lastCell.column; int fillInRow = lastCell.row; int fillInColumn = lastCell.column; if (Math.abs(dRow) == 2 && Math.abs(dColumn) != 1) { fillInRow = lastCell.row + ((dRow > 0) ? 1 : -1); } if (Math.abs(dColumn) == 2 && Math.abs(dRow) != 1) { fillInColumn = lastCell.column + ((dColumn > 0) ? 1 : -1); } fillInGapCell = Cell.of(fillInRow, fillInColumn); } if (fillInGapCell != null && !mPatternDrawLookup[fillInGapCell.row][fillInGapCell.column]) { addCellToPattern(fillInGapCell); } addCellToPattern(cell); // if (mEnableHapticFeedback) { // performHapticFeedback( // HapticFeedbackConstants.VIRTUAL_KEY, // HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING // | HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING); // } return cell; } return null; } private void addCellToPattern(Cell newCell) { mPatternDrawLookup[newCell.getRow()][newCell.getColumn()] = true; mPattern.add(newCell); notifyCellAdded(); } // helper method to find which cell a point maps to private Cell checkForNewHit(float x, float y) { final int rowHit = getRowHit(y); if (rowHit < 0) { return null; } final int columnHit = getColumnHit(x); if (columnHit < 0) { return null; } if (mPatternDrawLookup[rowHit][columnHit]) { return null; } return Cell.of(rowHit, columnHit); } /** * Helper method to find the row that y falls into. * * @param y * The y coordinate * @return The row that y falls in, or -1 if it falls in no row. */ private int getRowHit(float y) { final float squareHeight = mSquareHeight; float hitSize = squareHeight * mHitFactor; float offset = getPaddingTop() + (squareHeight - hitSize) / 2f; for (int i = 0; i < 3; i++) { final float hitTop = offset + squareHeight * i; if (y >= hitTop && y <= hitTop + hitSize) { return i; } } return -1; } /** * Helper method to find the column x fallis into. * * @param x * The x coordinate. * @return The column that x falls in, or -1 if it falls in no column. */ private int getColumnHit(float x) { final float squareWidth = mSquareWidth; float hitSize = squareWidth * mHitFactor; float offset = getPaddingLeft() + (squareWidth - hitSize) / 2f; for (int i = 0; i < 3; i++) { final float hitLeft = offset + squareWidth * i; if (x >= hitLeft && x <= hitLeft + hitSize) { return i; } } return -1; } @Override public boolean onTouchEvent(MotionEvent event) { if (!mInputEnabled || !isEnabled()) { return false; } switch (event.getAction()) { case MotionEvent.ACTION_DOWN: handleActionDown(event); return true; case MotionEvent.ACTION_UP: handleActionUp(event); return true; case MotionEvent.ACTION_MOVE: handleActionMove(event); return true; case MotionEvent.ACTION_CANCEL: resetPattern(); mPatternInProgress = false; notifyPatternCleared(); if (PROFILE_DRAWING) { if (mDrawingProfilingStarted) { Debug.stopMethodTracing(); mDrawingProfilingStarted = false; } } return true; } return false; } private void handleActionMove(MotionEvent event) { // Handle all recent motion events so we don't skip any cells even when // the device // is busy... final int historySize = event.getHistorySize(); for (int i = 0; i < historySize + 1; i++) { final float x = i < historySize ? event.getHistoricalX(i) : event .getX(); final float y = i < historySize ? event.getHistoricalY(i) : event .getY(); final int patternSizePreHitDetect = mPattern.size(); Cell hitCell = detectAndAddHit(x, y); final int patternSize = mPattern.size(); if (hitCell != null && patternSize == 1) { mPatternInProgress = true; notifyPatternStarted(); } // note current x and y for rubber banding of in progress patterns final float dx = Math.abs(x - mInProgressX); final float dy = Math.abs(y - mInProgressY); if (dx + dy > mSquareWidth * 0.01f) { float oldX = mInProgressX; float oldY = mInProgressY; mInProgressX = x; mInProgressY = y; if (mPatternInProgress && patternSize > 0) { final ArrayList pattern = mPattern; final float radius = mSquareWidth * mDiameterFactor * 0.5f; final Cell lastCell = pattern.get(patternSize - 1); float startX = getCenterXForColumn(lastCell.column); float startY = getCenterYForRow(lastCell.row); float left; float top; float right; float bottom; final Rect invalidateRect = mInvalidate; if (startX < x) { left = startX; right = x; } else { left = x; right = startX; } if (startY < y) { top = startY; bottom = y; } else { top = y; bottom = startY; } // Invalidate between the pattern's last cell and the // current location invalidateRect.set((int) (left - radius), (int) (top - radius), (int) (right + radius), (int) (bottom + radius)); if (startX < oldX) { left = startX; right = oldX; } else { left = oldX; right = startX; } if (startY < oldY) { top = startY; bottom = oldY; } else { top = oldY; bottom = startY; } // Invalidate between the pattern's last cell and the // previous location invalidateRect.union((int) (left - radius), (int) (top - radius), (int) (right + radius), (int) (bottom + radius)); // Invalidate between the pattern's new cell and the // pattern's previous cell if (hitCell != null) { startX = getCenterXForColumn(hitCell.column); startY = getCenterYForRow(hitCell.row); if (patternSize >= 2) { // (re-using hitcell for old cell) hitCell = pattern.get(patternSize - 1 - (patternSize - patternSizePreHitDetect)); oldX = getCenterXForColumn(hitCell.column); oldY = getCenterYForRow(hitCell.row); if (startX < oldX) { left = startX; right = oldX; } else { left = oldX; right = startX; } if (startY < oldY) { top = startY; bottom = oldY; } else { top = oldY; bottom = startY; } } else { left = right = startX; top = bottom = startY; } final float widthOffset = mSquareWidth / 2f; final float heightOffset = mSquareHeight / 2f; invalidateRect.set((int) (left - widthOffset), (int) (top - heightOffset), (int) (right + widthOffset), (int) (bottom + heightOffset)); } invalidate(invalidateRect); } else { invalidate(); } } } } private void sendAccessEvent(int resId) { setContentDescription(getContext().getString(resId)); sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED); setContentDescription(null); } private void handleActionUp(MotionEvent event) { // report pattern detected if (!mPattern.isEmpty()) { mPatternInProgress = false; notifyPatternDetected(); invalidate(); } if (PROFILE_DRAWING) { if (mDrawingProfilingStarted) { Debug.stopMethodTracing(); mDrawingProfilingStarted = false; } } } private void handleActionDown(MotionEvent event) { resetPattern(); final float x = event.getX(); final float y = event.getY(); final Cell hitCell = detectAndAddHit(x, y); if (hitCell != null) { mPatternInProgress = true; mPatternDisplayMode = DisplayMode.Correct; notifyPatternStarted(); } else { mPatternInProgress = false; notifyPatternCleared(); } if (hitCell != null) { final float startX = getCenterXForColumn(hitCell.column); final float startY = getCenterYForRow(hitCell.row); final float widthOffset = mSquareWidth / 2f; final float heightOffset = mSquareHeight / 2f; invalidate((int) (startX - widthOffset), (int) (startY - heightOffset), (int) (startX + widthOffset), (int) (startY + heightOffset)); } mInProgressX = x; mInProgressY = y; if (PROFILE_DRAWING) { if (!mDrawingProfilingStarted) { Debug.startMethodTracing("LockPatternDrawing"); mDrawingProfilingStarted = true; } } } private float getCenterXForColumn(int column) { return getPaddingLeft() + column * mSquareWidth + mSquareWidth / 2f; } private float getCenterYForRow(int row) { return getPaddingTop() + row * mSquareHeight + mSquareHeight / 2f; } @Override protected void onDraw(Canvas canvas) { final ArrayList pattern = mPattern; final int count = pattern.size(); final boolean[][] drawLookup = mPatternDrawLookup; if (mPatternDisplayMode == DisplayMode.Animate) { // figure out which circles to draw // + 1 so we pause on complete pattern final int oneCycle = (count + 1) * MILLIS_PER_CIRCLE_ANIMATING; final int spotInCycle = (int) (SystemClock.elapsedRealtime() - mAnimatingPeriodStart) % oneCycle; final int numCircles = spotInCycle / MILLIS_PER_CIRCLE_ANIMATING; clearPatternDrawLookup(); for (int i = 0; i < numCircles; i++) { final Cell cell = pattern.get(i); drawLookup[cell.getRow()][cell.getColumn()] = true; } // figure out in progress portion of ghosting line final boolean needToUpdateInProgressPoint = numCircles > 0 && numCircles < count; if (needToUpdateInProgressPoint) { final float percentageOfNextCircle = ((float) (spotInCycle % MILLIS_PER_CIRCLE_ANIMATING)) / MILLIS_PER_CIRCLE_ANIMATING; final Cell currentCell = pattern.get(numCircles - 1); final float centerX = getCenterXForColumn(currentCell.column); final float centerY = getCenterYForRow(currentCell.row); final Cell nextCell = pattern.get(numCircles); final float dx = percentageOfNextCircle * (getCenterXForColumn(nextCell.column) - centerX); final float dy = percentageOfNextCircle * (getCenterYForRow(nextCell.row) - centerY); mInProgressX = centerX + dx; mInProgressY = centerY + dy; } // TODO: Infinite loop here... invalidate(); } final float squareWidth = mSquareWidth; final float squareHeight = mSquareHeight; float radius = (squareWidth * mDiameterFactor * 0.5f); mPathPaint.setStrokeWidth(radius); final Path currentPath = mCurrentPath; currentPath.rewind(); // TODO: the path should be created and cached every time we hit-detect // a cell // only the last segment of the path should be computed here // draw the path of the pattern (unless the user is in progress, and // we are in stealth mode) final boolean drawPath = (!mInStealthMode || mPatternDisplayMode == DisplayMode.Wrong); // draw the arrows associated with the path (unless the user is in // progress, and // we are in stealth mode) boolean oldFlag = (mPaint.getFlags() & Paint.FILTER_BITMAP_FLAG) != 0; mPaint.setFilterBitmap(true); // draw with higher quality since we // render with transforms // draw the lines if (drawPath) { boolean anyCircles = false; for (int i = 0; i < count; i++) { Cell cell = pattern.get(i); // only draw the part of the pattern stored in // the lookup table (this is only different in the case // of animation). if (!drawLookup[cell.row][cell.column]) { break; } anyCircles = true; float centerX = getCenterXForColumn(cell.column); float centerY = getCenterYForRow(cell.row); if (i == 0) { currentPath.moveTo(centerX, centerY); } else { currentPath.lineTo(centerX, centerY); } } // add last in progress section if ((mPatternInProgress || mPatternDisplayMode == DisplayMode.Animate) && anyCircles) { currentPath.lineTo(mInProgressX, mInProgressY); } // chang the line color in different DisplayMode if (mPatternDisplayMode == DisplayMode.Wrong) mPathPaint.setColor(Color.RED); else mPathPaint.setColor(Color.YELLOW); canvas.drawPath(currentPath, mPathPaint); } // draw the circles final int paddingTop = getPaddingTop(); final int paddingLeft = getPaddingLeft(); for (int i = 0; i < 3; i++) { float topY = paddingTop + i * squareHeight; // float centerY = mPaddingTop + i * mSquareHeight + (mSquareHeight // / 2); for (int j = 0; j < 3; j++) { float leftX = paddingLeft + j * squareWidth; drawCircle(canvas, (int) leftX, (int) topY, drawLookup[i][j]); } } mPaint.setFilterBitmap(oldFlag); // restore default flag } /** * @param canvas * @param leftX * @param topY * @param partOfPattern * Whether this circle is part of the pattern. */ private void drawCircle(Canvas canvas, int leftX, int topY, boolean partOfPattern) { Bitmap outerCircle; Bitmap innerCircle = null; if (!partOfPattern || (mInStealthMode && mPatternDisplayMode != DisplayMode.Wrong)) { // unselected circle outerCircle = mBitmapCircleDefault; innerCircle = null; } else if (mPatternInProgress) { // user is in middle of drawing a pattern outerCircle = mBitmapCircleDefault; innerCircle = mBitmapCircleGreen; } else if (mPatternDisplayMode == DisplayMode.Wrong) { // the pattern is wrong outerCircle = mBitmapCircleDefault; innerCircle = mBitmapCircleRed; } else if (mPatternDisplayMode == DisplayMode.Correct || mPatternDisplayMode == DisplayMode.Animate) { // the pattern is correct outerCircle = mBitmapCircleDefault; innerCircle = mBitmapCircleGreen; } else { throw new IllegalStateException("unknown display mode " + mPatternDisplayMode); } final int width = mBitmapWidth; final int height = mBitmapHeight; final float squareWidth = mSquareWidth; final float squareHeight = mSquareHeight; int offsetX = (int) ((squareWidth - width) / 2f); int offsetY = (int) ((squareHeight - height) / 2f); // Allow circles to shrink if the view is too small to hold them. float sx = Math.min(mSquareWidth / mBitmapWidth, 1.0f); float sy = Math.min(mSquareHeight / mBitmapHeight, 1.0f); mCircleMatrix.setTranslate(leftX + offsetX, topY + offsetY); mCircleMatrix.preTranslate(mBitmapWidth / 2, mBitmapHeight / 2); mCircleMatrix.preScale(sx, sy); mCircleMatrix.preTranslate(-mBitmapWidth / 2, -mBitmapHeight / 2); canvas.drawBitmap(outerCircle, mCircleMatrix, mPaint); if (innerCircle != null) canvas.drawBitmap(innerCircle, mCircleMatrix, mPaint); } @Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); return new SavedState(superState, LockPatternUtils.patternToString(mPattern), mPatternDisplayMode.ordinal(), mInputEnabled, mInStealthMode, mEnableHapticFeedback); } @Override protected void onRestoreInstanceState(Parcelable state) { final SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); setPattern(DisplayMode.Correct, LockPatternUtils.stringToPattern(ss.getSerializedPattern())); mPatternDisplayMode = DisplayMode.values()[ss.getDisplayMode()]; mInputEnabled = ss.isInputEnabled(); mInStealthMode = ss.isInStealthMode(); mEnableHapticFeedback = ss.isTactileFeedbackEnabled(); } /** * The parecelable for saving and restoring a lock pattern view. */ private static class SavedState extends BaseSavedState { private final String mSerializedPattern; private final int mDisplayMode; private final boolean mInputEnabled; private final boolean mInStealthMode; private final boolean mTactileFeedbackEnabled; /** * Constructor called from {@link LockPatternView#onSaveInstanceState()} */ private SavedState(Parcelable superState, String serializedPattern, int displayMode, boolean inputEnabled, boolean inStealthMode, boolean tactileFeedbackEnabled) { super(superState); mSerializedPattern = serializedPattern; mDisplayMode = displayMode; mInputEnabled = inputEnabled; mInStealthMode = inStealthMode; mTactileFeedbackEnabled = tactileFeedbackEnabled; } /** * Constructor called from {@link #CREATOR} */ private SavedState(Parcel in) { super(in); mSerializedPattern = in.readString(); mDisplayMode = in.readInt(); mInputEnabled = (Boolean) in.readValue(null); mInStealthMode = (Boolean) in.readValue(null); mTactileFeedbackEnabled = (Boolean) in.readValue(null); } public String getSerializedPattern() { return mSerializedPattern; } public int getDisplayMode() { return mDisplayMode; } public boolean isInputEnabled() { return mInputEnabled; } public boolean isInStealthMode() { return mInStealthMode; } public boolean isTactileFeedbackEnabled() { return mTactileFeedbackEnabled; } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeString(mSerializedPattern); dest.writeInt(mDisplayMode); dest.writeValue(mInputEnabled); dest.writeValue(mInStealthMode); dest.writeValue(mTactileFeedbackEnabled); } public static final Parcelable.Creator CREATOR = new Creator() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/pattern/ParseXmlService.java ================================================ package com.cwp.pattern; import java.io.InputStream; import java.util.HashMap; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * @author coolszy * @date 2012-4-26 * @blog http://blog.92coding.com */ public class ParseXmlService { public HashMap parseXml(InputStream inStream) throws Exception { HashMap hashMap = new HashMap(); // 实例化一个文档构建器工厂 DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // 通过文档构建器工厂获取一个文档构建器 DocumentBuilder builder = factory.newDocumentBuilder(); // 通过文档通过文档构建器构建一个文档实例 Document document = builder.parse(inStream); // 获取XML文件根节点 Element root = document.getDocumentElement(); // 获得所有子节点 NodeList childNodes = root.getChildNodes(); for (int j = 0; j < childNodes.getLength(); j++) { // 遍历子节点 Node childNode = (Node) childNodes.item(j); if (childNode.getNodeType() == Node.ELEMENT_NODE) { Element childElement = (Element) childNode; // 版本号 if ("version".equals(childElement.getNodeName())) { hashMap.put("version", childElement.getFirstChild() .getNodeValue()); } // 软件名称 else if (("name".equals(childElement.getNodeName()))) { hashMap.put("name", childElement.getFirstChild() .getNodeValue()); } // 下载地址 else if (("url".equals(childElement.getNodeName()))) { hashMap.put("url", childElement.getFirstChild() .getNodeValue()); } // 更新内容 else if (("text".equals(childElement.getNodeName()))) { hashMap.put("text", childElement.getFirstChild() .getNodeValue()); } } } return hashMap; } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/pattern/UnlockGesturePasswordActivity.java ================================================ package com.cwp.pattern; import java.util.List; import com.cwp.chart.SystemBarTintManager; import com.cwp.cmoneycharge.About; import com.cwp.cmoneycharge.CrashApplication; import com.cwp.cmoneycharge.Description; import com.cwp.cmoneycharge.DialogShowUtil; import com.cwp.cmoneycharge.R; import com.cwp.cmoneycharge.SysApplication; import com.cwp.pattern.LockPatternView.Cell; import android.annotation.TargetApi; import android.app.Activity; import android.content.ContextWrapper; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Build; import android.os.Bundle; import android.os.CountDownTimer; import android.os.Handler; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.TextView; import android.widget.Toast; public class UnlockGesturePasswordActivity extends Activity { private LockPatternView mLockPatternView; private int mFailedPatternAttemptsSinceLastTimeout = 0; private CountDownTimer mCountdownTimer = null; private Handler mHandler = new Handler(); private TextView mHeadTextView, mforgetTextView; private Animation mShakeAnim; String flag = null; private Toast mToast; private void showToast(CharSequence message) { if (null == mToast) { mToast = Toast.makeText(this, message, Toast.LENGTH_SHORT); mToast.setGravity(Gravity.CENTER, 0, 0); } else { mToast.setText(message); } mToast.show(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.gesturepassword_unlock); SystemBarTintManager mTintManager; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { setTranslucentStatus(true); } mTintManager = new SystemBarTintManager(this); mTintManager.setStatusBarTintEnabled(true); mTintManager.setStatusBarTintResource(R.color.statusbar_bg); SysApplication.getInstance().addActivity(this); // 在销毁队列中添加this mLockPatternView = (LockPatternView) this .findViewById(R.id.gesturepwd_unlock_lockview); mLockPatternView.setOnPatternListener(mChooseNewLockPatternListener); mLockPatternView.setTactileFeedbackEnabled(true); mHeadTextView = (TextView) findViewById(R.id.gesturepwd_unlock_text); mforgetTextView = (TextView) findViewById(R.id.gesturepwd_unlock_forget); mShakeAnim = AnimationUtils.loadAnimation(this, R.anim.shake_x); Intent intentr = getIntent(); Bundle bundle = intentr.getExtras();// 获取传入的数据,并使用Bundle记录 if (bundle != null && bundle.containsKey("cwp.pwclear")) { // 清除密码 flag = "clear"; mHeadTextView.setText("请绘制原密码"); mforgetTextView.setVisibility(View.GONE); } if (bundle != null && bundle.containsKey("cwp.md")) { // 修改密码 mHeadTextView.setText("请绘制原密码"); flag = "md"; mforgetTextView.setVisibility(View.GONE); } if (bundle != null && bundle.containsKey("cwp.pwenable")) { // 第一次开启 flag = "enable"; mforgetTextView.setVisibility(View.GONE); } } @Override protected void onResume() { super.onResume(); if (!CrashApplication.getInstance().getLockPatternUtils() .savedPatternExists()) { Intent intent = new Intent(this, GuideGesturePasswordActivity.class); startActivityForResult(intent, 1); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1) { if (resultCode == 3) { this.setResult(3); this.finish(); } } } @Override protected void onDestroy() { super.onDestroy(); if (mCountdownTimer != null) mCountdownTimer.cancel(); } private Runnable mClearPatternRunnable = new Runnable() { public void run() { mLockPatternView.clearPattern(); } }; protected LockPatternView.OnPatternListener mChooseNewLockPatternListener = new LockPatternView.OnPatternListener() { public void onPatternStart() { mLockPatternView.removeCallbacks(mClearPatternRunnable); patternInProgress(); } public void onPatternCleared() { mLockPatternView.removeCallbacks(mClearPatternRunnable); } public void onPatternDetected(List pattern) { if (pattern == null) return; if (CrashApplication.getInstance().getLockPatternUtils() .checkPattern(pattern)) { if (flag == "clear") { CrashApplication.getInstance().getLockPatternUtils() .clearLock(); Intent intent = new Intent(); setResult(2, intent); showToast("清除成功"); finish();// 结束当前的activity的生命周期 } else if (flag == "md") { Intent intent = new Intent( UnlockGesturePasswordActivity.this, GuideGesturePasswordActivity.class); startActivity(intent); showToast("开始重置密码"); finish();// 结束当前的activity的生命周期 } else { mLockPatternView .setDisplayMode(LockPatternView.DisplayMode.Correct); CrashApplication myApplaction = (CrashApplication) getApplication(); myApplaction.isLocked = false; finish(); } } else { mLockPatternView .setDisplayMode(LockPatternView.DisplayMode.Wrong); if (pattern.size() >= LockPatternUtils.MIN_PATTERN_REGISTER_FAIL) { mFailedPatternAttemptsSinceLastTimeout++; int retry = LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT - mFailedPatternAttemptsSinceLastTimeout; if (retry >= 0) { if (retry == 0) showToast("您已5次输错密码,60秒后再试"); mHeadTextView.setText("密码错误,还可以再输入" + retry + "次"); mHeadTextView.setTextColor(Color.RED); mHeadTextView.startAnimation(mShakeAnim); } } else { showToast("输入长度不够,请重试"); } if (mFailedPatternAttemptsSinceLastTimeout >= LockPatternUtils.FAILED_ATTEMPTS_BEFORE_TIMEOUT) { mHandler.postDelayed(attemptLockout, 2000); } else { mLockPatternView.postDelayed(mClearPatternRunnable, 2000); } } } private void patternInProgress() { } @Override public void onPatternCellAdded(List pattern) { // TODO Auto-generated method stub } }; Runnable attemptLockout = new Runnable() { @Override public void run() { mLockPatternView.clearPattern(); mLockPatternView.setEnabled(false); mCountdownTimer = new CountDownTimer( LockPatternUtils.FAILED_ATTEMPT_TIMEOUT_MS + 1, 1000) { @Override public void onTick(long millisUntilFinished) { int secondsRemaining = (int) (millisUntilFinished / 1000) - 1; if (secondsRemaining > 0) { mHeadTextView.setText(secondsRemaining + " 秒后重试"); } else { mHeadTextView.setText("请绘制手势密码"); mHeadTextView.setTextColor(Color.WHITE); } } @Override public void onFinish() { mLockPatternView.setEnabled(true); mFailedPatternAttemptsSinceLastTimeout = 0; } }.start(); } }; @TargetApi(19) private void setTranslucentStatus(boolean on) { Window win = getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; if (on) { winParams.flags |= bits; } else { winParams.flags &= ~bits; } win.setAttributes(winParams); } DialogShowUtil dialogShowUtil = new DialogShowUtil(this, this, null, null, null); public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键 if ((flag == "clear") || (flag == "md") || (flag == "enable")) { finish(); } else { dialogShowUtil.dialogShow("shake", "quit", "", ""); } return true; } return super.onKeyDown(keyCode, event); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/cwp/pattern/UpdateManager.java ================================================ package com.cwp.pattern; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import com.cwp.cmoneycharge.R; import com.zhy.view.RoundProgressBarWidthNumber; import android.app.AlertDialog; import android.app.Dialog; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.content.pm.PackageManager.NameNotFoundException; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Environment; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.widget.ProgressBar; import android.widget.RemoteViews; import android.widget.TextView; import android.widget.Toast; /** * @author coolszy * @date 2012-4-26 * @blog http://blog.92coding.com */ public class UpdateManager extends Service { /* 下载丿 */ private static final int DOWNLOAD = 1; private static final int DOWNLOAD2 = 4; /* 下载结束 */ private static final int DOWNLOAD_FINISH = 2; public static final int IS_FINISH = 0; public static final int DOWNLOAD_FILERR = 3; /* 保存解析的XML信息 */ HashMap mHashMap; /* 下载保存路径 */ private String mSavePath; /* 记录进度条数釿 */ private int progress; /* 是否取消更新 */ private boolean cancelUpdate = false; private static final int down_step = 3; private Context mContext; /* 更新进度板 */ private ProgressBar mProgress; private Dialog mDownloadDialog; public InputStream inputStream; private String show; private RemoteViews contentView; private NotificationManager notificationManager; protected Notification notification; public int updateCount = 0; private TextView update_text; private RoundProgressBarWidthNumber mRoundProgressBar; private Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { // 正在下载 case DOWNLOAD: mRoundProgressBar.setProgress(progress); // 设置进度条位罿 break; case DOWNLOAD_FINISH: // 安装文件 installApk(); break; case DOWNLOAD_FILERR: // 无下载文件 Toast.makeText(mContext, "下载文件出错,请重新下载", Toast.LENGTH_LONG) .show(); break; default: break; } }; }; public Handler handler = new Handler() { // 在Handler中获取消息,重写handleMessage()方法 @Override public void handleMessage(Message msg) { switch (msg.what) { case 1: // 成功建立连接,但无更新 if (show.equals("show")) { Toast.makeText(mContext, "暂无更新", Toast.LENGTH_LONG).show(); } break; case 2: // 有更新 showNoticeDialog(); break; case -1: // 卡住 if (show.equals("show")) { Toast.makeText(mContext, "网络出了点状况", Toast.LENGTH_LONG) .show(); break; } } } }; public UpdateManager(Context context) { this.mContext = context; } /** * 棿?软件更新 */ public void checkUpdate(String show) { this.show = show; if (isWifi(mContext)) { isUpdate(); } else { if (show.equals("show")) { Toast.makeText(mContext, "当前为非WIFI网络!", Toast.LENGTH_LONG) .show(); } } } /** * 棿?软件是否有更新版朿 */ public void isUpdate() { // 获取当前软件版本 // 把version.xml放到网络上,然后获取文件信息 // InputStream inStream = ParseXmlService.class.getClassLoader() // .getResourceAsStream("version.xml"); new Thread() { @Override public void run() { try { double versionCode = getVersionCode(mContext); URL url = new URL( "http://linmp6-wordpress.stor.sinaapp.com/version.xml"); // 建立网络连接 HttpURLConnection conn = (HttpURLConnection) url .openConnection(); conn.setConnectTimeout(1 * 1000); conn.setReadTimeout(1 * 1000); // 必须设置 inputStream = conn.getInputStream(); // 获取图片数据 ParseXmlService service = new ParseXmlService(); // 解析XML文件?由于XML文件比较小,因此使用DOM方式进行解析 mHashMap = service.parseXml(inputStream); Message message = new Message(); message.what = 1; if (null != mHashMap) { Double serviceCode = Double.valueOf(mHashMap .get("version")); // 版本判断 if ((serviceCode - versionCode) > 0) { message.what = 2; } } inputStream.close(); // 发送消息到消息队列中 handler.sendMessage(message); } catch (Exception e) { Message message = new Message(); message.what = -1; handler.sendMessage(message); e.printStackTrace(); } } }.start(); } /** * 获取软件版本叿 * * @param context * @return */ public double getVersionCode(Context context) { double versionCode = 0; try { // 获取软件版本号,对应AndroidManifest.xml下android:versionCode versionCode = Double.valueOf( context.getPackageManager().getPackageInfo( context.getPackageName(), 0).versionName) .doubleValue(); } catch (NameNotFoundException e) { e.printStackTrace(); } return versionCode; } /** * 显示软件更新对话桿 */ private void showNoticeDialog() { // 构??话桿 AlertDialog.Builder builder = new Builder(mContext); builder.setTitle("软件更新"); builder.setMessage("检测到新版本" + mHashMap.get("version") + ",立即更新吗?\n\n" + mHashMap.get("text").replace("\\n", "\n")); // 更新 builder.setPositiveButton("更新", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); // 显示下载对话桿 showDownloadDialog(); } }); // 稍后更新 builder.setNegativeButton("稍后更新", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); Dialog noticeDialog = builder.create(); noticeDialog.show(); } /** * 显示软件下载对话桿 */ private void showDownloadDialog() { // 构??件下载对话桿 AlertDialog.Builder builder = new Builder(mContext); builder.setTitle("正在更新"); // 给下载对话框增加进度板 final LayoutInflater inflater = LayoutInflater.from(mContext); View v = inflater.inflate(R.layout.softupdate_progress, null); mRoundProgressBar = (RoundProgressBarWidthNumber) v .findViewById(R.id.id_progress02); // mProgress = (ProgressBar) v.findViewById(R.id.update_progress); // update_text = (TextView) v.findViewById(R.id.update_text); builder.setView(v); // 取消更新 builder.setNegativeButton("取消", new OnClickListener() { @SuppressWarnings("deprecation") @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); // 设置取消状濍 cancelUpdate = true; notification.flags = Notification.FLAG_AUTO_CANCEL; notification.setLatestEventInfo(mContext, mHashMap.get("name"), "用户已取消下载", null); notificationManager.notify(R.layout.notification_item, notification); } }); mDownloadDialog = builder.create(); mDownloadDialog.show(); // 现在文件 downloadApk(); } /** * 下载apk文件 */ private void downloadApk() { // 启动新线程下载软仿 new downloadApkThread().start(); } /** * 下载文件线程 * * @author coolszy * @date 2012-4-26 * @blog http://blog.92coding.com */ private class downloadApkThread extends Thread { @Override public void run() { try { // 判断SD卡是否存在,并且是否具有读写权限 if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { // 获得存储卡的路径 String sdpath = Environment.getExternalStorageDirectory() + "/"; mSavePath = sdpath + "download"; URL url = new URL(mHashMap.get("url")); // 创建连接 HttpURLConnection conn = (HttpURLConnection) url .openConnection(); conn.connect(); // 获取文件大小 int length = conn.getContentLength(); // 创建输入浿 if (length > -1) { createNotification(); InputStream is = conn.getInputStream(); File file = new File(mSavePath); // 判断文件目录是否存在 if (!file.exists()) { file.mkdir(); } File apkFile = new File(mSavePath, mHashMap.get("name")); FileOutputStream fos = new FileOutputStream(apkFile); int count = 0; // 缓存 byte buf[] = new byte[1024]; // 写入到文件中 do { int numread = is.read(buf); count += numread; progress = (int) (((float) count / length) * 100); // 更新进度 mHandler.sendEmptyMessage(DOWNLOAD); if (numread <= 0) { // 下载完成 mHandler.sendEmptyMessage(DOWNLOAD_FINISH); break; } // 写入文件 fos.write(buf, 0, numread); } while (!cancelUpdate);// 点击取消就停止下轿 fos.close(); is.close(); } else { mHandler.sendEmptyMessage(DOWNLOAD_FILERR); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 取消下载对话框显礿 mDownloadDialog.dismiss(); } }; /** * make true current connect service is wifi * * @param mContext * @return */ private static boolean isWifi(Context mContext) { ConnectivityManager connectivityManager = (ConnectivityManager) mContext .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) { return true; } return false; } /** * 安装APK文件 */ @SuppressWarnings("deprecation") private void installApk() { File apkfile = new File(mSavePath, mHashMap.get("name")); if (!apkfile.exists()) { return; } // 通过Intent安装APK文件 Intent i = new Intent(Intent.ACTION_VIEW); i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive"); mContext.startActivity(i); PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, i, 0); notification.flags = Notification.FLAG_AUTO_CANCEL; notification.setLatestEventInfo(mContext, mHashMap.get("name"), "下载成功", pendingIntent); notificationManager.notify(R.layout.notification_item, notification); /*** stop service *****/ stopSelf(); } /** * 方法描述:createNotification方法 * * @param * @return */ @SuppressWarnings("deprecation") public void createNotification() { String app_name = null; // notification = new Notification(R.drawable.dot_enable,app_name + // getString(R.string.is_downing) ,System.currentTimeMillis()); notification = new Notification( // R.drawable.video_player,//应用的图标 R.drawable.ic_launcher,// 应用的图标 mHashMap.get("name") + "正在下载", System.currentTimeMillis()); notification.flags = Notification.FLAG_ONGOING_EVENT; contentView = new RemoteViews(mContext.getPackageName(), R.layout.notification_item); contentView.setTextViewText(R.id.notificationTitle, mHashMap.get("name") + "正在下载"); contentView.setTextViewText(R.id.notificationPercent, "下载中"); contentView.setProgressBar(R.id.notificationProgress, 100, 0, false); notification.contentView = contentView; // updateIntent = new Intent(this, AboutActivity.class); // updateIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); // //updateIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // pendingIntent = PendingIntent.getActivity(this, 0, updateIntent, 0); // notification.contentIntent = pendingIntent; notificationManager = (NotificationManager) mContext .getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(R.layout.notification_item, notification); } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } } ================================================ FILE: MoneyCharge/app/src/main/java/com/example/testpic/AlbumHelper.java ================================================ package com.example.testpic; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.provider.MediaStore.Audio.Albums; import android.provider.MediaStore.Images.Media; import android.provider.MediaStore.Images.Thumbnails; import android.util.Log; /** * 专辑帮助类 * * @author Administrator * */ public class AlbumHelper { final String TAG = getClass().getSimpleName(); Context context; ContentResolver cr; // 缩略图列表 HashMap thumbnailList = new HashMap(); // 专辑列表 List> albumList = new ArrayList>(); HashMap bucketList = new HashMap(); private static AlbumHelper instance; private AlbumHelper() { } public static AlbumHelper getHelper() { if (instance == null) { instance = new AlbumHelper(); } return instance; } /** * 初始化 * * @param context */ public void init(Context context) { if (this.context == null) { this.context = context; cr = context.getContentResolver(); } } /** * 得到缩略图 */ private void getThumbnail() { String[] projection = { Thumbnails._ID, Thumbnails.IMAGE_ID, Thumbnails.DATA }; Cursor cursor = cr.query(Thumbnails.EXTERNAL_CONTENT_URI, projection, null, null, null); getThumbnailColumnData(cursor); } /** * 从数据库中得到缩略图 * * @param cur */ private void getThumbnailColumnData(Cursor cur) { if (cur.moveToFirst()) { int _id; int image_id; String image_path; int _idColumn = cur.getColumnIndex(Thumbnails._ID); int image_idColumn = cur.getColumnIndex(Thumbnails.IMAGE_ID); int dataColumn = cur.getColumnIndex(Thumbnails.DATA); do { // Get the field values _id = cur.getInt(_idColumn); image_id = cur.getInt(image_idColumn); image_path = cur.getString(dataColumn); // Do something with the values. // Log.i(TAG, _id + " image_id:" + image_id + " path:" // + image_path + "---"); // HashMap hash = new HashMap(); // hash.put("image_id", image_id + ""); // hash.put("path", image_path); // thumbnailList.add(hash); thumbnailList.put("" + image_id, image_path); } while (cur.moveToNext()); } } /** * 得到原图 */ void getAlbum() { String[] projection = { Albums._ID, Albums.ALBUM, Albums.ALBUM_ART, Albums.ALBUM_KEY, Albums.ARTIST, Albums.NUMBER_OF_SONGS }; Cursor cursor = cr.query(Albums.EXTERNAL_CONTENT_URI, projection, null, null, null); getAlbumColumnData(cursor); } /** * 从本地数据库中得到原图 * * @param cur */ private void getAlbumColumnData(Cursor cur) { if (cur.moveToFirst()) { int _id; String album; String albumArt; String albumKey; String artist; int numOfSongs; int _idColumn = cur.getColumnIndex(Albums._ID); int albumColumn = cur.getColumnIndex(Albums.ALBUM); int albumArtColumn = cur.getColumnIndex(Albums.ALBUM_ART); int albumKeyColumn = cur.getColumnIndex(Albums.ALBUM_KEY); int artistColumn = cur.getColumnIndex(Albums.ARTIST); int numOfSongsColumn = cur.getColumnIndex(Albums.NUMBER_OF_SONGS); do { // Get the field values _id = cur.getInt(_idColumn); album = cur.getString(albumColumn); albumArt = cur.getString(albumArtColumn); albumKey = cur.getString(albumKeyColumn); artist = cur.getString(artistColumn); numOfSongs = cur.getInt(numOfSongsColumn); // Do something with the values. Log.i(TAG, _id + " album:" + album + " albumArt:" + albumArt + "albumKey: " + albumKey + " artist: " + artist + " numOfSongs: " + numOfSongs + "---"); HashMap hash = new HashMap(); hash.put("_id", _id + ""); hash.put("album", album); hash.put("albumArt", albumArt); hash.put("albumKey", albumKey); hash.put("artist", artist); hash.put("numOfSongs", numOfSongs + ""); albumList.add(hash); } while (cur.moveToNext()); } } /** * 是否创建了图片集 */ boolean hasBuildImagesBucketList = false; /** * 得到图片集 */ void buildImagesBucketList() { long startTime = System.currentTimeMillis(); // 构造缩略图索引 getThumbnail(); // 构造相册索引 String columns[] = new String[] { Media._ID, Media.BUCKET_ID, Media.PICASA_ID, Media.DATA, Media.DISPLAY_NAME, Media.TITLE, Media.SIZE, Media.BUCKET_DISPLAY_NAME }; // 得到一个游标 Cursor cur = cr.query(Media.EXTERNAL_CONTENT_URI, columns, null, null, null); if (cur.moveToFirst()) { // 获取指定列的索引 int photoIDIndex = cur.getColumnIndexOrThrow(Media._ID); int photoPathIndex = cur.getColumnIndexOrThrow(Media.DATA); int photoNameIndex = cur.getColumnIndexOrThrow(Media.DISPLAY_NAME); int photoTitleIndex = cur.getColumnIndexOrThrow(Media.TITLE); int photoSizeIndex = cur.getColumnIndexOrThrow(Media.SIZE); int bucketDisplayNameIndex = cur .getColumnIndexOrThrow(Media.BUCKET_DISPLAY_NAME); int bucketIdIndex = cur.getColumnIndexOrThrow(Media.BUCKET_ID); int picasaIdIndex = cur.getColumnIndexOrThrow(Media.PICASA_ID); // 获取图片总数 int totalNum = cur.getCount(); do { String _id = cur.getString(photoIDIndex); String name = cur.getString(photoNameIndex); String path = cur.getString(photoPathIndex); String title = cur.getString(photoTitleIndex); String size = cur.getString(photoSizeIndex); String bucketName = cur.getString(bucketDisplayNameIndex); String bucketId = cur.getString(bucketIdIndex); String picasaId = cur.getString(picasaIdIndex); Log.i(TAG, _id + ", bucketId: " + bucketId + ", picasaId: " + picasaId + " name:" + name + " path:" + path + " title: " + title + " size: " + size + " bucket: " + bucketName + "---"); ImageBucket bucket = bucketList.get(bucketId); if (bucket == null) { bucket = new ImageBucket(); bucketList.put(bucketId, bucket); bucket.imageList = new ArrayList(); bucket.bucketName = bucketName; } bucket.count++; ImageItem imageItem = new ImageItem(); imageItem.imageId = _id; imageItem.imagePath = path; imageItem.thumbnailPath = thumbnailList.get(_id); bucket.imageList.add(imageItem); } while (cur.moveToNext()); } Iterator> itr = bucketList.entrySet() .iterator(); while (itr.hasNext()) { Map.Entry entry = (Map.Entry) itr .next(); ImageBucket bucket = entry.getValue(); Log.d(TAG, entry.getKey() + ", " + bucket.bucketName + ", " + bucket.count + " ---------- "); for (int i = 0; i < bucket.imageList.size(); ++i) { ImageItem image = bucket.imageList.get(i); Log.d(TAG, "----- " + image.imageId + ", " + image.imagePath + ", " + image.thumbnailPath); } } hasBuildImagesBucketList = true; long endTime = System.currentTimeMillis(); Log.d(TAG, "use time: " + (endTime - startTime) + " ms"); } /** * 得到图片集 * * @param refresh * @return */ public List getImagesBucketList(boolean refresh) { if (refresh || (!refresh && !hasBuildImagesBucketList)) { buildImagesBucketList(); } List tmpList = new ArrayList(); Iterator> itr = bucketList.entrySet() .iterator(); while (itr.hasNext()) { Map.Entry entry = (Map.Entry) itr .next(); tmpList.add(entry.getValue()); } return tmpList; } /** * 得到原始图像路径 * * @param image_id * @return */ String getOriginalImagePath(String image_id) { String path = null; Log.i(TAG, "---(^o^)----" + image_id); String[] projection = { Media._ID, Media.DATA }; Cursor cursor = cr.query(Media.EXTERNAL_CONTENT_URI, projection, Media._ID + "=" + image_id, null, null); if (cursor != null) { cursor.moveToFirst(); path = cursor.getString(cursor.getColumnIndex(Media.DATA)); } return path; } } ================================================ FILE: MoneyCharge/app/src/main/java/com/example/testpic/Bimp.java ================================================ package com.example.testpic; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.cwp.cmoneycharge.AddPay; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Environment; import android.widget.Toast; public class Bimp { public static int max = 0; public static int flag = 0; public static int flag2 = 0; public static boolean act_bool = true; public static List bmp = new ArrayList(); // 图片sd地址 上传服务器时把图片调用下面方法压缩后 保存到临时文件夹 图片压缩后小于100KB,失真度不明显 public static List drr = new ArrayList(); public static List smdrr = new ArrayList(); public static Bitmap getbitmap(String path) throws IOException { Bitmap bitmap = null; File f = new File(path); if (f.exists()) { /* 产生Bitmap对象,并放入mImageView中 */ bitmap = BitmapFactory.decodeFile(path); } return bitmap; } public static Bitmap revitionImageSize(String path) throws IOException { BufferedInputStream in = new BufferedInputStream(new FileInputStream( new File(path))); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(in, null, options); in.close(); int i = 0; Bitmap bitmap = null; while (true) { if ((options.outWidth >> i <= 1000) && (options.outHeight >> i <= 1000)) { in = new BufferedInputStream( new FileInputStream(new File(path))); options.inSampleSize = (int) Math.pow(2.0D, i); options.inJustDecodeBounds = false; bitmap = BitmapFactory.decodeStream(in, null, options); break; } i += 1; } return bitmap; } } ================================================ FILE: MoneyCharge/app/src/main/java/com/example/testpic/BitmapCache.java ================================================ package com.example.testpic; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.lang.ref.SoftReference; import java.util.HashMap; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Handler; import android.text.TextUtils; import android.util.Log; import android.widget.ImageView; public class BitmapCache extends Activity { public Handler h = new Handler(); public final String TAG = getClass().getSimpleName(); private HashMap> imageCache = new HashMap>(); public void put(String path, Bitmap bmp) { if (!TextUtils.isEmpty(path) && bmp != null) { imageCache.put(path, new SoftReference(bmp)); } } public void displayBmp(final ImageView iv, final String thumbPath, final String sourcePath, final ImageCallback callback) { if (TextUtils.isEmpty(thumbPath) && TextUtils.isEmpty(sourcePath)) { Log.e(TAG, "no paths pass in"); return; } final String path; final boolean isThumbPath; if (!TextUtils.isEmpty(thumbPath)) { path = thumbPath; isThumbPath = true; } else if (!TextUtils.isEmpty(sourcePath)) { path = sourcePath; isThumbPath = false; } else { // iv.setImageBitmap(null); return; } if (imageCache.containsKey(path)) { SoftReference reference = imageCache.get(path); Bitmap bmp = reference.get(); if (bmp != null) { if (callback != null) { callback.imageLoad(iv, bmp, sourcePath); } iv.setImageBitmap(bmp); Log.d(TAG, "hit cache"); return; } } iv.setImageBitmap(null); new Thread() { Bitmap thumb; public void run() { try { if (isThumbPath) { thumb = BitmapFactory.decodeFile(thumbPath); if (thumb == null) { thumb = revitionImageSize(sourcePath); } } else { thumb = revitionImageSize(sourcePath); } } catch (Exception e) { } if (thumb == null) { thumb = TestPicActivity.bimap; } Log.e(TAG, "-------thumb------"+thumb); put(path, thumb); if (callback != null) { h.post(new Runnable() { @Override public void run() { callback.imageLoad(iv, thumb, sourcePath); } }); } } }.start(); } public Bitmap revitionImageSize(String path) throws IOException { BufferedInputStream in = new BufferedInputStream(new FileInputStream( new File(path))); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(in, null, options); in.close(); int i = 0; Bitmap bitmap = null; while (true) { if ((options.outWidth >> i <= 256) && (options.outHeight >> i <= 256)) { in = new BufferedInputStream( new FileInputStream(new File(path))); options.inSampleSize = (int) Math.pow(2.0D, i); options.inJustDecodeBounds = false; bitmap = BitmapFactory.decodeStream(in, null, options); break; } i += 1; } return bitmap; } public interface ImageCallback { public void imageLoad(ImageView imageView, Bitmap bitmap, Object... params); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/example/testpic/FileUtils.java ================================================ package com.example.testpic; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import android.graphics.Bitmap; import android.os.Environment; import android.util.Log; public class FileUtils { public static String SDPATH = Environment.getExternalStorageDirectory() + "/myimage/formats/"; public static void saveBitmap(Bitmap bm, String picName) { Log.e("", "保存图片"); try { if (!isFileExist("")) { File tempf = createSDDir(""); } File f = new File(SDPATH, picName + ".jpg"); if (f.exists()) { f.delete(); } FileOutputStream out = new FileOutputStream(f); bm.compress(Bitmap.CompressFormat.JPEG, 90, out); out.flush(); out.close(); Log.e("", "已经保存"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static File createSDDir(String dirName) throws IOException { File dir = new File(SDPATH + dirName); if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { dir.getAbsolutePath(); dir.mkdir(); // System.out.println("createSDDir:" + dir.getAbsolutePath()); // System.out.println("createSDDir:" + dir.mkdir()); } return dir; } public static boolean isFileExist(String fileName) { File file = new File(SDPATH + fileName); file.isFile(); return file.exists(); } public static void delFile(String fileName) { File file = new File(SDPATH + fileName); if (file.isFile()) { file.delete(); } file.exists(); } public static void deleteDir() { File dir = new File(SDPATH); if (dir == null || !dir.exists() || !dir.isDirectory()) return; for (File file : dir.listFiles()) { if (file.isFile()) file.delete(); // 删除所有文件 else if (file.isDirectory()) deleteDir(); // 递规的方式删除文件夹 } dir.delete();// 删除目录本身 } public static boolean fileIsExists(String path) { try { File f = new File(path); if (!f.exists()) { return false; } } catch (Exception e) { return false; } return true; } } ================================================ FILE: MoneyCharge/app/src/main/java/com/example/testpic/ImageBucket.java ================================================ package com.example.testpic; import java.util.List; /** * 一个目录的相册对象 * * @author Administrator * */ public class ImageBucket { public int count = 0; public String bucketName; public List imageList; } ================================================ FILE: MoneyCharge/app/src/main/java/com/example/testpic/ImageBucketAdapter.java ================================================ package com.example.testpic; import java.util.List; import android.app.Activity; import android.graphics.Bitmap; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.cwp.cmoneycharge.R; import com.example.testpic.BitmapCache.ImageCallback; public class ImageBucketAdapter extends BaseAdapter { final String TAG = getClass().getSimpleName(); Activity act; /** * ????? */ List dataList; BitmapCache cache; ImageCallback callback = new ImageCallback() { @Override public void imageLoad(ImageView imageView, Bitmap bitmap, Object... params) { if (imageView != null && bitmap != null) { String url = (String) params[0]; if (url != null && url.equals((String) imageView.getTag())) { ((ImageView) imageView).setImageBitmap(bitmap); } else { Log.e(TAG, "callback, bmp not match"); } } else { Log.e(TAG, "callback, bmp null"); } } }; public ImageBucketAdapter(Activity act, List list) { this.act = act; dataList = list; cache = new BitmapCache(); } @Override public int getCount() { // TODO Auto-generated method stub int count = 0; if (dataList != null) { count = dataList.size(); } return count; } @Override public Object getItem(int arg0) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int arg0) { // TODO Auto-generated method stub return arg0; } class Holder { private ImageView iv; private ImageView selected; private TextView name; private TextView count; } @Override public View getView(int arg0, View arg1, ViewGroup arg2) { // TODO Auto-generated method stub Holder holder; if (arg1 == null) { holder = new Holder(); arg1 = View.inflate(act, R.layout.item_image_bucket, null); holder.iv = (ImageView) arg1.findViewById(R.id.image); holder.selected = (ImageView) arg1.findViewById(R.id.isselected); holder.name = (TextView) arg1.findViewById(R.id.name); holder.count = (TextView) arg1.findViewById(R.id.count); arg1.setTag(holder); } else { holder = (Holder) arg1.getTag(); } ImageBucket item = dataList.get(arg0); holder.count.setText("" + item.count); holder.name.setText(item.bucketName); holder.selected.setVisibility(View.GONE); if (item.imageList != null && item.imageList.size() > 0) { String thumbPath = item.imageList.get(0).thumbnailPath; String sourcePath = item.imageList.get(0).imagePath; holder.iv.setTag(sourcePath); cache.displayBmp(holder.iv, thumbPath, sourcePath, callback); } else { holder.iv.setImageBitmap(null); Log.e(TAG, "no images in bucket " + item.bucketName); } return arg1; } } ================================================ FILE: MoneyCharge/app/src/main/java/com/example/testpic/ImageGridActivity.java ================================================ package com.example.testpic; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import com.cwp.cmoneycharge.About; import com.cwp.cmoneycharge.MainActivity; import com.cwp.cmoneycharge.R; import com.example.testpic.ImageGridAdapter.TextCallback; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; public class ImageGridActivity extends Activity { public static final String EXTRA_IMAGE_LIST = "imagelist"; // ArrayList dataList;//用来装载数据源的列表 List dataList; GridView gridView; ImageGridAdapter adapter;// 自定义的适配噿 AlbumHelper helper; Button bt; Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: Toast.makeText(ImageGridActivity.this, "最多选择9张图片", 400).show(); break; default: break; } } }; private TextView bt_cancel; private ImageView bt_back; private TextView gridview_cancel; @SuppressWarnings("unchecked") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_image_grid); helper = AlbumHelper.getHelper(); helper.init(getApplicationContext()); dataList = (List) getIntent().getSerializableExtra( EXTRA_IMAGE_LIST); initView(); bt = (Button) findViewById(R.id.bt); bt_cancel = (TextView) findViewById(R.id.bt_cancel); bt_back = (ImageView) findViewById(R.id.bt_back); bt_cancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ImageGridActivity.this, PublishedActivity.class); startActivity(intent); finish(); } }); bt_back.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ImageGridActivity.this, TestPicActivity.class); startActivity(intent); finish(); } }); bt.setOnClickListener(new OnClickListener() { public void onClick(View v) { ArrayList list = new ArrayList(); Collection c = adapter.map.values(); Iterator it = c.iterator(); for (; it.hasNext();) { list.add(it.next()); } if (Bimp.act_bool) { Intent intent = new Intent(ImageGridActivity.this, PublishedActivity.class); startActivity(intent); Bimp.act_bool = false; } for (int i = 0; i < list.size(); i++) { if (Bimp.drr.size() < 9) { Bimp.drr.add(list.get(i)); } } System.out.println("Bimp.flag" + Bimp.flag); if (Bimp.flag2 == 0) { finish(); Bimp.flag2++; } else { Intent intent = new Intent(ImageGridActivity.this, PublishedActivity.class); startActivity(intent); finish(); } } }); } /** * 初妾化view视图 */ private void initView() { gridView = (GridView) findViewById(R.id.gridview); gridView.setSelector(new ColorDrawable(Color.TRANSPARENT)); adapter = new ImageGridAdapter(ImageGridActivity.this, dataList, mHandler); gridView.setAdapter(adapter); adapter.setTextCallback(new TextCallback() { public void onListen(int count) { bt.setText("完成" + " (" + count + ")"); } }); gridView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { /** * 根据position参数,可以获得跟GridView的子View相绑定的实体类,然后根据它的isSelected状捊 * * ?_ 来判断是否显示??效果?至于选中效果的覽则,下面适配器的代码中会有说昿 */ // if(dataList.get(position).isSelected()){ // dataList.get(position).setSelected(false); // }else{ // dataList.get(position).setSelected(true); // } /** * 通知适配器,绑定的数据发生了改变,应当刷新覹囿 */ adapter.notifyDataSetChanged(); } }); } public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键 Intent intent = new Intent(ImageGridActivity.this, TestPicActivity.class); startActivity(intent); finish(); return true; } return super.onKeyDown(keyCode, event); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/example/testpic/ImageGridAdapter.java ================================================ package com.example.testpic; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.graphics.Bitmap; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.cwp.cmoneycharge.R; import com.example.testpic.BitmapCache.ImageCallback; public class ImageGridAdapter extends BaseAdapter { private TextCallback textcallback = null; final String TAG = getClass().getSimpleName(); Activity act; List dataList; Map map = new HashMap(); BitmapCache cache; private Handler mHandler; private int selectTotal = 0; ImageCallback callback = new ImageCallback() { @Override public void imageLoad(ImageView imageView, Bitmap bitmap, Object... params) { if (imageView != null && bitmap != null) { String url = (String) params[0]; if (url != null && url.equals((String) imageView.getTag())) { ((ImageView) imageView).setImageBitmap(bitmap); } else { Log.e(TAG, "callback, bmp not match"); } } else { Log.e(TAG, "callback, bmp null"); } } }; public static interface TextCallback { public void onListen(int count); } public void setTextCallback(TextCallback listener) { textcallback = listener; } public ImageGridAdapter(Activity act, List list, Handler mHandler) { this.act = act; dataList = list; cache = new BitmapCache(); this.mHandler = mHandler; } @Override public int getCount() { int count = 0; if (dataList != null) { count = dataList.size(); } return count; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } class Holder { private ImageView iv; private ImageView selected; private TextView text; } @Override public View getView(final int position, View convertView, ViewGroup parent) { final Holder holder; if (convertView == null) { holder = new Holder(); convertView = View.inflate(act, R.layout.item_image_grid, null); holder.iv = (ImageView) convertView.findViewById(R.id.image); holder.selected = (ImageView) convertView .findViewById(R.id.isselected); holder.text = (TextView) convertView .findViewById(R.id.item_image_grid_text); convertView.setTag(holder); } else { holder = (Holder) convertView.getTag(); } final ImageItem item = dataList.get(position); holder.iv.setTag(item.imagePath); cache.displayBmp(holder.iv, item.thumbnailPath, item.imagePath, callback); if (item.isSelected) { holder.selected.setImageResource(R.drawable.icon_data_select); holder.text.setBackgroundResource(R.drawable.bgd_relatly_line); } else { holder.selected.setImageResource(-1); holder.text.setBackgroundColor(0x00000000); } holder.iv.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String path = dataList.get(position).imagePath; if ((Bimp.drr.size() + selectTotal) < 9) { item.isSelected = !item.isSelected; if (item.isSelected) { holder.selected .setImageResource(R.drawable.icon_data_select); holder.text.setBackgroundResource(R.drawable.bgd_relatly_line); selectTotal++; if (textcallback != null) textcallback.onListen(selectTotal); map.put(path, path); } else if (!item.isSelected) { holder.selected.setImageResource(-1); holder.text.setBackgroundColor(0x00000000); selectTotal--; if (textcallback != null) textcallback.onListen(selectTotal); map.remove(path); } } else if ((Bimp.drr.size() + selectTotal) >= 9) { if (item.isSelected == true) { item.isSelected = !item.isSelected; holder.selected.setImageResource(-1); selectTotal--; map.remove(path); } else { Message message = Message.obtain(mHandler, 0); message.sendToTarget(); } } } }); return convertView; } } ================================================ FILE: MoneyCharge/app/src/main/java/com/example/testpic/ImageItem.java ================================================ package com.example.testpic; import java.io.Serializable; /** * 一个图片对象 * * @author Administrator * */ public class ImageItem implements Serializable { public String imageId; public String thumbnailPath; public String imagePath; public boolean isSelected = false; } ================================================ FILE: MoneyCharge/app/src/main/java/com/example/testpic/NoScrollGridView.java ================================================ package com.example.testpic; import android.content.Context; import android.util.AttributeSet; import android.widget.GridView; public class NoScrollGridView extends GridView { public NoScrollGridView(Context context) { super(context); } public NoScrollGridView(Context context, AttributeSet attrs) { super(context, attrs); } protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/example/testpic/PhotoActivity.java ================================================ package com.example.testpic; import java.util.ArrayList; import java.util.List; import com.cwp.cmoneycharge.R; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.ImageView; import android.widget.RelativeLayout; public class PhotoActivity extends Activity { private ArrayList listViews = null; private ViewPager pager; private MyPageAdapter adapter; private int count; public List bmp = new ArrayList(); public List drr = new ArrayList(); public static List smdrr = new ArrayList(); public List del = new ArrayList(); public int max; RelativeLayout photo_relativeLayout; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_photo); photo_relativeLayout = (RelativeLayout) findViewById(R.id.photo_relativeLayout); photo_relativeLayout.setBackgroundColor(0x70000000); Intent intentr = getIntent(); Bundle bundle = intentr.getExtras();// 获取传入的数据,并使用Bundle记录 if ((bundle != null)) { if ((bundle.containsKey("mian"))) { photo_relativeLayout.setVisibility(View.GONE); } } for (int i = 0; i < Bimp.bmp.size(); i++) { bmp.add(Bimp.bmp.get(i)); } for (int i = 0; i < Bimp.drr.size(); i++) { drr.add(Bimp.drr.get(i)); } max = Bimp.max; Button photo_bt_exit = (Button) findViewById(R.id.photo_bt_exit); photo_bt_exit.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { finish(); } }); Button photo_bt_del = (Button) findViewById(R.id.photo_bt_del); photo_bt_del.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (listViews.size() == 1) { Bimp.bmp.clear(); Bimp.drr.clear(); Bimp.smdrr.clear(); Bimp.max = 0; String newStr = drr.get(count).substring( drr.get(count).lastIndexOf("/") + 1, drr.get(count).lastIndexOf(".")); del.add(newStr); Intent intent = new Intent(PhotoActivity.this, PublishedActivity.class); startActivity(intent); finish(); } else { String newStr = drr.get(count).substring( drr.get(count).lastIndexOf("/") + 1, drr.get(count).lastIndexOf(".")); bmp.remove(count); drr.remove(count); del.add(newStr); max--; pager.removeAllViews(); listViews.remove(count); adapter.setListViews(listViews); adapter.notifyDataSetChanged(); } } }); Button photo_bt_enter = (Button) findViewById(R.id.photo_bt_enter); photo_bt_enter.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Bimp.bmp = bmp; Bimp.drr = drr; Bimp.max = max; for (int i = 0; i < del.size(); i++) { FileUtils.delFile(del.get(i) + ".jpg"); } Intent intent = new Intent(PhotoActivity.this, PublishedActivity.class); startActivity(intent); finish(); } }); pager = (ViewPager) findViewById(R.id.viewpager); pager.setOnPageChangeListener(pageChangeListener); for (int i = 0; i < bmp.size(); i++) { initListViews(bmp.get(i));// } adapter = new MyPageAdapter(listViews);// 构造adapter pager.setAdapter(adapter);// 设置适配器 Intent intent = getIntent(); int id = intent.getIntExtra("ID", 0); pager.setCurrentItem(id); } private void initListViews(Bitmap bm) { if (listViews == null) listViews = new ArrayList(); ImageView img = new ImageView(this);// 构造textView对象 img.setBackgroundColor(0xff000000); img.setImageBitmap(bm); img.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); listViews.add(img);// 添加view } private OnPageChangeListener pageChangeListener = new OnPageChangeListener() { public void onPageSelected(int arg0) {// 页面选择响应函数 count = arg0; } public void onPageScrolled(int arg0, float arg1, int arg2) {// 滑动中。。。 } public void onPageScrollStateChanged(int arg0) {// 滑动状态改变 } }; class MyPageAdapter extends PagerAdapter { private ArrayList listViews;// content private int size;// 页数 public MyPageAdapter(ArrayList listViews) {// 构造函数 // 初始化viewpager的时候给的一个页面 this.listViews = listViews; size = listViews == null ? 0 : listViews.size(); } public void setListViews(ArrayList listViews) {// 自己写的一个方法用来添加数据 this.listViews = listViews; size = listViews == null ? 0 : listViews.size(); } public int getCount() {// 返回数量 return size; } public int getItemPosition(Object object) { return POSITION_NONE; } public void destroyItem(View arg0, int arg1, Object arg2) {// 销毁view对象 ((ViewPager) arg0).removeView(listViews.get(arg1 % size)); } public void finishUpdate(View arg0) { } public Object instantiateItem(View arg0, int arg1) {// 返回view对象 try { ((ViewPager) arg0).addView(listViews.get(arg1 % size), 0); } catch (Exception e) { } return listViews.get(arg1 % size); } public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == arg1; } } } ================================================ FILE: MoneyCharge/app/src/main/java/com/example/testpic/PublishedActivity.java ================================================ package com.example.testpic; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import com.cwp.chart.SystemBarTintManager; import com.cwp.cmoneycharge.AddPay; import com.cwp.cmoneycharge.R; import com.cwp.cmoneycharge.SysApplication; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.TextView; public class PublishedActivity extends Activity { private GridView noScrollgridview; private GridAdapter adapter; private TextView activity_selectimg_send; private int flag = 0; private Bundle bundle; private int userid; private int modifysize; Boolean firstin = true; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_selectimg); Init(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { setTranslucentStatus(true); // findViewById(R.id.top).setVisibility(View.VISIBLE); } SystemBarTintManager mTintManager = new SystemBarTintManager(this); mTintManager.setStatusBarTintEnabled(true); mTintManager.setStatusBarTintResource(R.color.statusbar_bg); SysApplication.getInstance().addActivity(this); // 在销毁队列中添加this } @TargetApi(19) private void setTranslucentStatus(boolean on) { Window win = getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; if (on) { winParams.flags |= bits; } else { winParams.flags &= ~bits; } win.setAttributes(winParams); } public void Init() { Intent intentr = getIntent(); userid = intentr.getIntExtra("cwp.id", 100000001); bundle = intentr.getExtras();// 获取传入的数据,并使用Bundle记录 if ((bundle != null)) { if ((bundle.containsKey("cwp.photo"))) { if (firstin) { photo(); firstin = false; } } } noScrollgridview = (GridView) findViewById(R.id.noScrollgridview); noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT)); adapter = new GridAdapter(this); adapter.update(); noScrollgridview.setAdapter(adapter); noScrollgridview.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) { if (arg2 == Bimp.bmp.size()) { new PopupWindows(PublishedActivity.this, noScrollgridview); } else { Intent intent = new Intent(PublishedActivity.this, PhotoActivity.class); intent.putExtra("ID", arg2); startActivity(intent); finish(); } } }); activity_selectimg_send = (TextView) findViewById(R.id.activity_selectimg_send); activity_selectimg_send.setOnClickListener(new OnClickListener() { public void onClick(View v) { setResult(3);// this.setResult(int resultCode),resultCode 可以自定义 finish(); // 高清的压缩过的图片全部就在 list 路径里面了 // 高清的压缩过的 bmp 对象 都在 Bimp.bmp里面 // 完成上传服务器后 ......... // FileUtils.deleteDir(); } }); } @SuppressLint("HandlerLeak") public class GridAdapter extends BaseAdapter { private LayoutInflater inflater; // 视图容器 private int selectedPosition = -1;// 选中的位置 private boolean shape; public boolean isShape() { return shape; } public void setShape(boolean shape) { this.shape = shape; } public GridAdapter(Context context) { inflater = LayoutInflater.from(context); } public void update() { // if (Bimp.flag == 0) { loading(); // Bimp.flag++; // } } public int getCount() { return (Bimp.bmp.size() + 1); } public Object getItem(int arg0) { return null; } public long getItemId(int arg0) { return 0; } public void setSelectedPosition(int position) { selectedPosition = position; } public int getSelectedPosition() { return selectedPosition; } /** * ListView Item设置 */ public View getView(int position, View convertView, ViewGroup parent) { final int coord = position; ViewHolder holder = null; if (convertView == null) { convertView = inflater.inflate(R.layout.item_published_grida, parent, false); holder = new ViewHolder(); holder.image = (ImageView) convertView .findViewById(R.id.item_grida_image); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } if (position == Bimp.bmp.size()) { holder.image.setImageBitmap(BitmapFactory.decodeResource( getResources(), R.drawable.icon_addpic_unfocused)); if (position == 9) { holder.image.setVisibility(View.GONE); } } else { holder.image.setImageBitmap(Bimp.bmp.get(position)); } return convertView; } public class ViewHolder { public ImageView image; } Handler handler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case 1: adapter.notifyDataSetChanged(); break; } super.handleMessage(msg); } }; public void loading() { new Thread(new Runnable() { public void run() { while (true) { if (Bimp.max == Bimp.drr.size()) { Message message = new Message(); message.what = 1; handler.sendMessage(message); break; } else { Intent intentr = getIntent(); bundle = intentr.getExtras();// 获取传入的数据,并使用Bundle记录 try { if (Bimp.drr.size() >= Bimp.max) { String path = Bimp.drr.get(Bimp.max); Bitmap bm = Bimp.revitionImageSize(path); Bimp.bmp.add(bm); String newStr = path.substring( path.lastIndexOf("/") + 1, path.lastIndexOf(".")); FileUtils.saveBitmap(bm, newStr); Bimp.smdrr.add(FileUtils.SDPATH + newStr + ".jpg"); Bimp.max += 1; Message message = new Message(); message.what = 1; handler.sendMessage(message); } } catch (IOException e) { e.printStackTrace(); } } } } }).start(); } } public String getString(String s) { String path = null; if (s == null) return ""; for (int i = s.length() - 1; i > 0; i++) { s.charAt(i); } return path; } public class PopupWindows extends PopupWindow { // 弹出菜单 public PopupWindows(Context mContext, View parent) { View view = View .inflate(mContext, R.layout.item_popupwindows, null); view.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.fade_ins)); LinearLayout ll_popup = (LinearLayout) view .findViewById(R.id.ll_popup); ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.push_bottom_in_2)); setWidth(LayoutParams.FILL_PARENT); setHeight(LayoutParams.FILL_PARENT); setBackgroundDrawable(new BitmapDrawable()); setFocusable(true); setOutsideTouchable(true); setContentView(view); showAtLocation(parent, Gravity.BOTTOM, 0, 0); update(); Button bt1 = (Button) view .findViewById(R.id.item_popupwindows_camera); // 相机 Button bt2 = (Button) view .findViewById(R.id.item_popupwindows_Photo); // 图库 Button bt3 = (Button) view .findViewById(R.id.item_popupwindows_cancel); // 取消 bt1.setOnClickListener(new OnClickListener() { public void onClick(View v) { photo(); dismiss(); } }); bt2.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(PublishedActivity.this, TestPicActivity.class); startActivity(intent); Bimp.flag = 0; finish(); dismiss(); } }); bt3.setOnClickListener(new OnClickListener() { public void onClick(View v) { dismiss(); } }); } } private static final int TAKE_PICTURE = 0x000000; private String path = ""; public void photo() { Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { File dir = new File(Environment.getExternalStorageDirectory() + "/myimage/"); String fileName = String.valueOf(System.currentTimeMillis()) + ".jpg"; if (!dir.exists()) dir.mkdir(); File file = new File(dir, fileName); path = file.getPath(); Uri imageUri = Uri.fromFile(file); openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(openCameraIntent, TAKE_PICTURE); } } protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case TAKE_PICTURE: if (Bimp.drr.size() < 9 && resultCode == -1) { Bimp.drr.add(path); } Init(); break; } } @Override protected void onDestroy() { super.onDestroy(); } public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键 setResult(3);// this.setResult(int resultCode),resultCode 可以自定义 finish(); return true; } return super.onKeyDown(keyCode, event); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/example/testpic/TestPicActivity.java ================================================ package com.example.testpic; import java.io.Serializable; import java.util.List; import com.cwp.cmoneycharge.R; import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import android.widget.TextView; public class TestPicActivity extends Activity { // ArrayList dataList;//用来装载数据源的列表 List dataList; GridView gridView; ImageBucketAdapter adapter;// 自定义的适配器 AlbumHelper helper; private TextView gridview_cancel; public static final String EXTRA_IMAGE_LIST = "imagelist"; public static Bitmap bimap; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_image_bucket); helper = AlbumHelper.getHelper(); helper.init(getApplicationContext()); initData(); initView(); } /** * 初始化数据 */ private void initData() { // /** // * 这里,我们假设已经从网络或者本地解析好了数据,所以直接在这里模拟了10个实体类,直接装进列表中 // */ // dataList = new ArrayList(); // for(int i=-0;i<10;i++){ // Entity entity = new Entity(R.drawable.picture, false); // dataList.add(entity); // } dataList = helper.getImagesBucketList(false); bimap = BitmapFactory.decodeResource(getResources(), R.drawable.icon_addpic_unfocused); } /** * 初始化view视图 */ private void initView() { gridView = (GridView) findViewById(R.id.gridview); gridview_cancel = (TextView) findViewById(R.id.gridview_cancel); gridview_cancel.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent intent = new Intent(TestPicActivity.this, PublishedActivity.class); startActivity(intent); finish(); } }); adapter = new ImageBucketAdapter(TestPicActivity.this, dataList); gridView.setAdapter(adapter); gridView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { /** * 根据position参数,可以获得跟GridView的子View相绑定的实体类,然后根据它的isSelected状态, * 来判断是否显示选中效果。 至于选中效果的规则,下面适配器的代码中会有说明 */ // if(dataList.get(position).isSelected()){ // dataList.get(position).setSelected(false); // }else{ // dataList.get(position).setSelected(true); // } /** * 通知适配器,绑定的数据发生了改变,应当刷新视图 */ // adapter.notifyDataSetChanged(); Intent intent = new Intent(TestPicActivity.this, ImageGridActivity.class); intent.putExtra(TestPicActivity.EXTRA_IMAGE_LIST, (Serializable) dataList.get(position).imageList); startActivity(intent); finish(); } }); } public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键 Intent intent = new Intent(TestPicActivity.this, PublishedActivity.class); startActivity(intent); finish(); return true; } return super.onKeyDown(keyCode, event); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/slidingmenu/lib/CanvasTransformerBuilder.java ================================================ package com.slidingmenu.lib; import android.graphics.Canvas; import android.view.animation.Interpolator; import com.slidingmenu.lib.SlidingMenu.CanvasTransformer; public class CanvasTransformerBuilder { private CanvasTransformer mTrans; private static Interpolator lin = new Interpolator() { public float getInterpolation(float t) { return t; } }; private void initTransformer() { if (mTrans == null) mTrans = new CanvasTransformer() { public void transformCanvas(Canvas canvas, float percentOpen) { } }; } public CanvasTransformer zoom(final int openedX, final int closedX, final int openedY, final int closedY, final int px, final int py) { return zoom(openedX, closedX, openedY, closedY, px, py, lin); } public CanvasTransformer zoom(final int openedX, final int closedX, final int openedY, final int closedY, final int px, final int py, final Interpolator interp) { initTransformer(); mTrans = new CanvasTransformer() { public void transformCanvas(Canvas canvas, float percentOpen) { mTrans.transformCanvas(canvas, percentOpen); float f = interp.getInterpolation(percentOpen); canvas.scale((openedX - closedX) * f + closedX, (openedY - closedY) * f + closedY, px, py); } }; return mTrans; } public CanvasTransformer rotate(final int openedDeg, final int closedDeg, final int px, final int py) { return rotate(openedDeg, closedDeg, px, py, lin); } public CanvasTransformer rotate(final int openedDeg, final int closedDeg, final int px, final int py, final Interpolator interp) { initTransformer(); mTrans = new CanvasTransformer() { public void transformCanvas(Canvas canvas, float percentOpen) { mTrans.transformCanvas(canvas, percentOpen); float f = interp.getInterpolation(percentOpen); canvas.rotate((openedDeg - closedDeg) * f + closedDeg, px, py); } }; return mTrans; } public CanvasTransformer translate(final int openedX, final int closedX, final int openedY, final int closedY) { return translate(openedX, closedX, openedY, closedY, lin); } public CanvasTransformer translate(final int openedX, final int closedX, final int openedY, final int closedY, final Interpolator interp) { initTransformer(); mTrans = new CanvasTransformer() { public void transformCanvas(Canvas canvas, float percentOpen) { mTrans.transformCanvas(canvas, percentOpen); float f = interp.getInterpolation(percentOpen); canvas.translate((openedX - closedX) * f + closedX, (openedY - closedY) * f + closedY); } }; return mTrans; } public CanvasTransformer concatTransformer(final CanvasTransformer t) { initTransformer(); mTrans = new CanvasTransformer() { public void transformCanvas(Canvas canvas, float percentOpen) { mTrans.transformCanvas(canvas, percentOpen); t.transformCanvas(canvas, percentOpen); } }; return mTrans; } } ================================================ FILE: MoneyCharge/app/src/main/java/com/slidingmenu/lib/CustomViewAbove.java ================================================ package com.slidingmenu.lib; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.graphics.Canvas; import android.graphics.Rect; import android.os.Build; import android.support.v4.view.KeyEventCompat; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.VelocityTrackerCompat; import android.support.v4.view.ViewCompat; import android.support.v4.view.ViewConfigurationCompat; import android.util.AttributeSet; import android.util.FloatMath; import android.util.Log; import android.view.FocusFinder; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SoundEffectConstants; import android.view.VelocityTracker; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.animation.Interpolator; import android.widget.Scroller; import com.slidingmenu.lib.SlidingMenu.OnClosedListener; import com.slidingmenu.lib.SlidingMenu.OnOpenedListener; //import com.slidingmenu.lib.SlidingMenu.OnCloseListener; //import com.slidingmenu.lib.SlidingMenu.OnOpenListener; public class CustomViewAbove extends ViewGroup { private static final String TAG = "CustomViewAbove"; private static final boolean DEBUG = false; private static final boolean USE_CACHE = false; private static final int MAX_SETTLE_DURATION = 600; // ms private static final int MIN_DISTANCE_FOR_FLING = 25; // dips private static final Interpolator sInterpolator = new Interpolator() { public float getInterpolation(float t) { t -= 1.0f; return t * t * t * t * t + 1.0f; } }; private View mContent; private int mCurItem; private Scroller mScroller; private boolean mScrollingCacheEnabled; private boolean mScrolling; private boolean mIsBeingDragged; private boolean mIsUnableToDrag; private int mTouchSlop; private float mInitialMotionX; /** * Position of the last motion event. */ private float mLastMotionX; private float mLastMotionY; /** * ID of the active pointer. This is used to retain consistency during * drags/flings if multiple pointers are used. */ protected int mActivePointerId = INVALID_POINTER; /** * Sentinel value for no current active pointer. * Used by {@link #mActivePointerId}. */ private static final int INVALID_POINTER = -1; /** * Determines speed during touch scrolling */ protected VelocityTracker mVelocityTracker; private int mMinimumVelocity; protected int mMaximumVelocity; private int mFlingDistance; private CustomViewBehind mViewBehind; // private int mMode; private boolean mEnabled = true; private OnPageChangeListener mOnPageChangeListener; private OnPageChangeListener mInternalPageChangeListener; // private OnCloseListener mCloseListener; // private OnOpenListener mOpenListener; private OnClosedListener mClosedListener; private OnOpenedListener mOpenedListener; private List mIgnoredViews = new ArrayList(); // private int mScrollState = SCROLL_STATE_IDLE; /** * Callback interface for responding to changing state of the selected page. */ public interface OnPageChangeListener { /** * This method will be invoked when the current page is scrolled, either as part * of a programmatically initiated smooth scroll or a user initiated touch scroll. * * @param position Position index of the first page currently being displayed. * Page position+1 will be visible if positionOffset is nonzero. * @param positionOffset Value from [0, 1) indicating the offset from the page at position. * @param positionOffsetPixels Value in pixels indicating the offset from position. */ public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels); /** * This method will be invoked when a new page becomes selected. Animation is not * necessarily complete. * * @param position Position index of the new selected page. */ public void onPageSelected(int position); } /** * Simple implementation of the {@link OnPageChangeListener} interface with stub * implementations of each method. Extend this if you do not intend to override * every method of {@link OnPageChangeListener}. */ public static class SimpleOnPageChangeListener implements OnPageChangeListener { public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { // This space for rent } public void onPageSelected(int position) { // This space for rent } public void onPageScrollStateChanged(int state) { // This space for rent } } public CustomViewAbove(Context context) { this(context, null); } public CustomViewAbove(Context context, AttributeSet attrs) { super(context, attrs); initCustomViewAbove(); } void initCustomViewAbove() { setWillNotDraw(false); setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); setFocusable(true); final Context context = getContext(); mScroller = new Scroller(context, sInterpolator); final ViewConfiguration configuration = ViewConfiguration.get(context); mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration); mMinimumVelocity = configuration.getScaledMinimumFlingVelocity(); mMaximumVelocity = configuration.getScaledMaximumFlingVelocity(); setInternalPageChangeListener(new SimpleOnPageChangeListener() { public void onPageSelected(int position) { if (mViewBehind != null) { switch (position) { case 0: case 2: mViewBehind.setChildrenEnabled(true); break; case 1: mViewBehind.setChildrenEnabled(false); break; } } } }); final float density = context.getResources().getDisplayMetrics().density; mFlingDistance = (int) (MIN_DISTANCE_FOR_FLING * density); } /** * Set the currently selected page. If the CustomViewPager has already been through its first * layout there will be a smooth animated transition between the current item and the * specified item. * * @param item Item index to select */ public void setCurrentItem(int item) { setCurrentItemInternal(item, true, false); } /** * Set the currently selected page. * * @param item Item index to select * @param smoothScroll True to smoothly scroll to the new item, false to transition immediately */ public void setCurrentItem(int item, boolean smoothScroll) { setCurrentItemInternal(item, smoothScroll, false); } public int getCurrentItem() { return mCurItem; } void setCurrentItemInternal(int item, boolean smoothScroll, boolean always) { setCurrentItemInternal(item, smoothScroll, always, 0); } void setCurrentItemInternal(int item, boolean smoothScroll, boolean always, int velocity) { if (!always && mCurItem == item) { setScrollingCacheEnabled(false); return; } item = mViewBehind.getMenuPage(item); final boolean dispatchSelected = mCurItem != item; mCurItem = item; final int destX = getDestScrollX(mCurItem); if (dispatchSelected && mOnPageChangeListener != null) { mOnPageChangeListener.onPageSelected(item); } if (dispatchSelected && mInternalPageChangeListener != null) { mInternalPageChangeListener.onPageSelected(item); } if (smoothScroll) { smoothScrollTo(destX, 0, velocity); } else { completeScroll(); scrollTo(destX, 0); } } /** * Set a listener that will be invoked whenever the page changes or is incrementally * scrolled. See {@link OnPageChangeListener}. * * @param listener Listener to set */ public void setOnPageChangeListener(OnPageChangeListener listener) { mOnPageChangeListener = listener; } /* public void setOnOpenListener(OnOpenListener l) { mOpenListener = l; } public void setOnCloseListener(OnCloseListener l) { mCloseListener = l; } */ public void setOnOpenedListener(OnOpenedListener l) { mOpenedListener = l; } public void setOnClosedListener(OnClosedListener l) { mClosedListener = l; } /** * Set a separate OnPageChangeListener for internal use by the support library. * * @param listener Listener to set * @return The old listener that was set, if any. */ OnPageChangeListener setInternalPageChangeListener(OnPageChangeListener listener) { OnPageChangeListener oldListener = mInternalPageChangeListener; mInternalPageChangeListener = listener; return oldListener; } public void addIgnoredView(View v) { if (!mIgnoredViews.contains(v)) { mIgnoredViews.add(v); } } public void removeIgnoredView(View v) { mIgnoredViews.remove(v); } public void clearIgnoredViews() { mIgnoredViews.clear(); } // We want the duration of the page snap animation to be influenced by the distance that // the screen has to travel, however, we don't want this duration to be effected in a // purely linear fashion. Instead, we use this method to moderate the effect that the distance // of travel has on the overall snap duration. float distanceInfluenceForSnapDuration(float f) { f -= 0.5f; // center the values about 0. f *= 0.3f * Math.PI / 2.0f; return (float) FloatMath.sin(f); } public int getDestScrollX(int page) { switch (page) { case 0: case 2: return mViewBehind.getMenuLeft(mContent, page); case 1: return mContent.getLeft(); } return 0; } private int getLeftBound() { return mViewBehind.getAbsLeftBound(mContent); } private int getRightBound() { return mViewBehind.getAbsRightBound(mContent); } public int getContentLeft() { return mContent.getLeft() + mContent.getPaddingLeft(); } public boolean isMenuOpen() { return mCurItem == 0 || mCurItem == 2; } private boolean isInIgnoredView(MotionEvent ev) { Rect rect = new Rect(); for (View v : mIgnoredViews) { v.getHitRect(rect); if (rect.contains((int)ev.getX(), (int)ev.getY())) return true; } return false; } public int getBehindWidth() { if (mViewBehind == null) { return 0; } else { return mViewBehind.getBehindWidth(); } } public int getChildWidth(int i) { switch (i) { case 0: return getBehindWidth(); case 1: return mContent.getWidth(); default: return 0; } } public boolean isSlidingEnabled() { return mEnabled; } public void setSlidingEnabled(boolean b) { mEnabled = b; } /** * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. * * @param x the number of pixels to scroll by on the X axis * @param y the number of pixels to scroll by on the Y axis */ void smoothScrollTo(int x, int y) { smoothScrollTo(x, y, 0); } /** * Like {@link View#scrollBy}, but scroll smoothly instead of immediately. * * @param x the number of pixels to scroll by on the X axis * @param y the number of pixels to scroll by on the Y axis * @param velocity the velocity associated with a fling, if applicable. (0 otherwise) */ void smoothScrollTo(int x, int y, int velocity) { if (getChildCount() == 0) { // Nothing to do. setScrollingCacheEnabled(false); return; } int sx = getScrollX(); int sy = getScrollY(); int dx = x - sx; int dy = y - sy; if (dx == 0 && dy == 0) { completeScroll(); if (isMenuOpen()) { if (mOpenedListener != null) mOpenedListener.onOpened(); } else { if (mClosedListener != null) mClosedListener.onClosed(); } return; } setScrollingCacheEnabled(true); mScrolling = true; final int width = getBehindWidth(); final int halfWidth = width / 2; final float distanceRatio = Math.min(1f, 1.0f * Math.abs(dx) / width); final float distance = halfWidth + halfWidth * distanceInfluenceForSnapDuration(distanceRatio); int duration = 0; velocity = Math.abs(velocity); if (velocity > 0) { duration = 4 * Math.round(1000 * Math.abs(distance / velocity)); } else { final float pageDelta = (float) Math.abs(dx) / width; duration = (int) ((pageDelta + 1) * 100); duration = MAX_SETTLE_DURATION; } duration = Math.min(duration, MAX_SETTLE_DURATION); mScroller.startScroll(sx, sy, dx, dy, duration); invalidate(); } public void setContent(View v) { if (mContent != null) this.removeView(mContent); mContent = v; addView(mContent); } public View getContent() { return mContent; } public void setCustomViewBehind(CustomViewBehind cvb) { mViewBehind = cvb; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = getDefaultSize(0, widthMeasureSpec); int height = getDefaultSize(0, heightMeasureSpec); setMeasuredDimension(width, height); final int contentWidth = getChildMeasureSpec(widthMeasureSpec, 0, width); final int contentHeight = getChildMeasureSpec(heightMeasureSpec, 0, height); mContent.measure(contentWidth, contentHeight); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); // Make sure scroll position is set correctly. if (w != oldw) { // [ChrisJ] - This fixes the onConfiguration change for orientation issue.. // maybe worth having a look why the recomputeScroll pos is screwing // up? completeScroll(); scrollTo(getDestScrollX(mCurItem), getScrollY()); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int width = r - l; final int height = b - t; mContent.layout(0, 0, width, height); } public void setAboveOffset(int i) { // RelativeLayout.LayoutParams params = ((RelativeLayout.LayoutParams)mContent.getLayoutParams()); // params.setMargins(i, params.topMargin, params.rightMargin, params.bottomMargin); mContent.setPadding(i, mContent.getPaddingTop(), mContent.getPaddingRight(), mContent.getPaddingBottom()); } @Override public void computeScroll() { if (!mScroller.isFinished()) { if (mScroller.computeScrollOffset()) { int oldX = getScrollX(); int oldY = getScrollY(); int x = mScroller.getCurrX(); int y = mScroller.getCurrY(); if (oldX != x || oldY != y) { scrollTo(x, y); pageScrolled(x); } // Keep on drawing until the animation has finished. invalidate(); return; } } // Done with scroll, clean up state. completeScroll(); } private void pageScrolled(int xpos) { final int widthWithMargin = getWidth(); final int position = xpos / widthWithMargin; final int offsetPixels = xpos % widthWithMargin; final float offset = (float) offsetPixels / widthWithMargin; onPageScrolled(position, offset, offsetPixels); } /** * This method will be invoked when the current page is scrolled, either as part * of a programmatically initiated smooth scroll or a user initiated touch scroll. * If you override this method you must call through to the superclass implementation * (e.g. super.onPageScrolled(position, offset, offsetPixels)) before onPageScrolled * returns. * * @param position Position index of the first page currently being displayed. * Page position+1 will be visible if positionOffset is nonzero. * @param offset Value from [0, 1) indicating the offset from the page at position. * @param offsetPixels Value in pixels indicating the offset from position. */ protected void onPageScrolled(int position, float offset, int offsetPixels) { if (mOnPageChangeListener != null) { mOnPageChangeListener.onPageScrolled(position, offset, offsetPixels); } if (mInternalPageChangeListener != null) { mInternalPageChangeListener.onPageScrolled(position, offset, offsetPixels); } } private void completeScroll() { boolean needPopulate = mScrolling; if (needPopulate) { // Done with scroll, no longer want to cache view drawing. setScrollingCacheEnabled(false); mScroller.abortAnimation(); int oldX = getScrollX(); int oldY = getScrollY(); int x = mScroller.getCurrX(); int y = mScroller.getCurrY(); if (oldX != x || oldY != y) { scrollTo(x, y); } if (isMenuOpen()) { if (mOpenedListener != null) mOpenedListener.onOpened(); } else { if (mClosedListener != null) mClosedListener.onClosed(); } } mScrolling = false; } protected int mTouchMode = SlidingMenu.TOUCHMODE_MARGIN; public void setTouchMode(int i) { mTouchMode = i; } public int getTouchMode() { return mTouchMode; } private boolean thisTouchAllowed(MotionEvent ev) { int x = (int) (ev.getX() + mScrollX); if (isMenuOpen()) { return mViewBehind.menuOpenTouchAllowed(mContent, mCurItem, x); } else { switch (mTouchMode) { case SlidingMenu.TOUCHMODE_FULLSCREEN: return !isInIgnoredView(ev); case SlidingMenu.TOUCHMODE_NONE: return false; case SlidingMenu.TOUCHMODE_MARGIN: return mViewBehind.marginTouchAllowed(mContent, x); } } return false; } private boolean thisSlideAllowed(float dx) { boolean allowed = false; if (isMenuOpen()) { allowed = mViewBehind.menuOpenSlideAllowed(dx); } else { allowed = mViewBehind.menuClosedSlideAllowed(dx); } if (DEBUG) Log.v(TAG, "this slide allowed " + allowed + " dx: " + dx); return allowed; } private int getPointerIndex(MotionEvent ev, int id) { int activePointerIndex = MotionEventCompat.findPointerIndex(ev, id); if (activePointerIndex == -1) mActivePointerId = INVALID_POINTER; return activePointerIndex; } private boolean mQuickReturn = false; @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if (!mEnabled) return false; final int action = ev.getAction() & MotionEventCompat.ACTION_MASK; if (DEBUG) if (action == MotionEvent.ACTION_DOWN) Log.v(TAG, "Received ACTION_DOWN"); if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP || (action != MotionEvent.ACTION_DOWN && mIsUnableToDrag)) { endDrag(); return false; } switch (action) { case MotionEvent.ACTION_MOVE: determineDrag(ev); break; case MotionEvent.ACTION_DOWN: int index = MotionEventCompat.getActionIndex(ev); mActivePointerId = MotionEventCompat.getPointerId(ev, index); if (mActivePointerId == INVALID_POINTER) break; mLastMotionX = mInitialMotionX = MotionEventCompat.getX(ev, index); mLastMotionY = MotionEventCompat.getY(ev, index); if (thisTouchAllowed(ev)) { mIsBeingDragged = false; mIsUnableToDrag = false; if (isMenuOpen() && mViewBehind.menuTouchInQuickReturn(mContent, mCurItem, ev.getX() + mScrollX)) { mQuickReturn = true; } } else { mIsUnableToDrag = true; } break; case MotionEventCompat.ACTION_POINTER_UP: onSecondaryPointerUp(ev); break; } if (!mIsBeingDragged) { if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); } return mIsBeingDragged || mQuickReturn; } @Override public boolean onTouchEvent(MotionEvent ev) { if (!mEnabled) return false; if (!mIsBeingDragged && !thisTouchAllowed(ev)) return false; // if (!mIsBeingDragged && !mQuickReturn) // return false; final int action = ev.getAction(); if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); switch (action & MotionEventCompat.ACTION_MASK) { case MotionEvent.ACTION_DOWN: /* * If being flinged and user touches, stop the fling. isFinished * will be false if being flinged. */ completeScroll(); // Remember where the motion event started int index = MotionEventCompat.getActionIndex(ev); mActivePointerId = MotionEventCompat.getPointerId(ev, index); mLastMotionX = mInitialMotionX = ev.getX(); break; case MotionEvent.ACTION_MOVE: if (!mIsBeingDragged) { determineDrag(ev); if (mIsUnableToDrag) return false; } if (mIsBeingDragged) { // Scroll to follow the motion event final int activePointerIndex = getPointerIndex(ev, mActivePointerId); if (mActivePointerId == INVALID_POINTER) break; final float x = MotionEventCompat.getX(ev, activePointerIndex); final float deltaX = mLastMotionX - x; mLastMotionX = x; float oldScrollX = getScrollX(); float scrollX = oldScrollX + deltaX; final float leftBound = getLeftBound(); final float rightBound = getRightBound(); if (scrollX < leftBound) { scrollX = leftBound; } else if (scrollX > rightBound) { scrollX = rightBound; } // Don't lose the rounded component mLastMotionX += scrollX - (int) scrollX; scrollTo((int) scrollX, getScrollY()); pageScrolled((int) scrollX); } break; case MotionEvent.ACTION_UP: if (mIsBeingDragged) { final VelocityTracker velocityTracker = mVelocityTracker; velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity); int initialVelocity = (int) VelocityTrackerCompat.getXVelocity( velocityTracker, mActivePointerId); final int scrollX = getScrollX(); // final int widthWithMargin = getWidth(); // final float pageOffset = (float) (scrollX % widthWithMargin) / widthWithMargin; // TODO test this. should get better flinging behavior final float pageOffset = (float) (scrollX - getDestScrollX(mCurItem)) / getBehindWidth(); final int activePointerIndex = getPointerIndex(ev, mActivePointerId); if (mActivePointerId != INVALID_POINTER) { final float x = MotionEventCompat.getX(ev, activePointerIndex); final int totalDelta = (int) (x - mInitialMotionX); int nextPage = determineTargetPage(pageOffset, initialVelocity, totalDelta); setCurrentItemInternal(nextPage, true, true, initialVelocity); } else { setCurrentItemInternal(mCurItem, true, true, initialVelocity); } mActivePointerId = INVALID_POINTER; endDrag(); } else if (mQuickReturn && mViewBehind.menuTouchInQuickReturn(mContent, mCurItem, ev.getX() + mScrollX)) { // close the menu setCurrentItem(1); endDrag(); } break; case MotionEvent.ACTION_CANCEL: if (mIsBeingDragged) { setCurrentItemInternal(mCurItem, true, true); mActivePointerId = INVALID_POINTER; endDrag(); } break; case MotionEventCompat.ACTION_POINTER_DOWN: { final int indexx = MotionEventCompat.getActionIndex(ev); mLastMotionX = MotionEventCompat.getX(ev, indexx); mActivePointerId = MotionEventCompat.getPointerId(ev, indexx); break; } case MotionEventCompat.ACTION_POINTER_UP: onSecondaryPointerUp(ev); int pointerIndex = getPointerIndex(ev, mActivePointerId); if (mActivePointerId == INVALID_POINTER) break; mLastMotionX = MotionEventCompat.getX(ev, pointerIndex); break; } return true; } private void determineDrag(MotionEvent ev) { final int activePointerId = mActivePointerId; final int pointerIndex = getPointerIndex(ev, activePointerId); if (activePointerId == INVALID_POINTER) return; final float x = MotionEventCompat.getX(ev, pointerIndex); final float dx = x - mLastMotionX; final float xDiff = Math.abs(dx); final float y = MotionEventCompat.getY(ev, pointerIndex); final float dy = y - mLastMotionY; final float yDiff = Math.abs(dy); if (xDiff > (isMenuOpen()?mTouchSlop/2:mTouchSlop) && xDiff > yDiff && thisSlideAllowed(dx)) { startDrag(); mLastMotionX = x; mLastMotionY = y; setScrollingCacheEnabled(true); // TODO add back in touch slop check } else if (xDiff > mTouchSlop) { mIsUnableToDrag = true; } } @Override public void scrollTo(int x, int y) { super.scrollTo(x, y); mScrollX = x; if (mEnabled) mViewBehind.scrollBehindTo(mContent, x, y); ((SlidingMenu)getParent()).manageLayers(getPercentOpen()); } private int determineTargetPage(float pageOffset, int velocity, int deltaX) { int targetPage = mCurItem; if (Math.abs(deltaX) > mFlingDistance && Math.abs(velocity) > mMinimumVelocity) { if (velocity > 0 && deltaX > 0) { targetPage -= 1; } else if (velocity < 0 && deltaX < 0){ targetPage += 1; } } else { targetPage = (int) Math.round(mCurItem + pageOffset); } return targetPage; } protected float getPercentOpen() { return Math.abs(mScrollX-mContent.getLeft()) / getBehindWidth(); } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); // Draw the margin drawable if needed. mViewBehind.drawShadow(mContent, canvas); mViewBehind.drawFade(mContent, canvas, getPercentOpen()); mViewBehind.drawSelector(mContent, canvas, getPercentOpen()); } // variables for drawing private float mScrollX = 0.0f; private void onSecondaryPointerUp(MotionEvent ev) { if (DEBUG) Log.v(TAG, "onSecondaryPointerUp called"); final int pointerIndex = MotionEventCompat.getActionIndex(ev); final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex); if (pointerId == mActivePointerId) { // This was our active pointer going up. Choose a new // active pointer and adjust accordingly. final int newPointerIndex = pointerIndex == 0 ? 1 : 0; mLastMotionX = MotionEventCompat.getX(ev, newPointerIndex); mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex); if (mVelocityTracker != null) { mVelocityTracker.clear(); } } } private void startDrag() { mIsBeingDragged = true; mQuickReturn = false; } private void endDrag() { mQuickReturn = false; mIsBeingDragged = false; mIsUnableToDrag = false; mActivePointerId = INVALID_POINTER; if (mVelocityTracker != null) { mVelocityTracker.recycle(); mVelocityTracker = null; } } private void setScrollingCacheEnabled(boolean enabled) { if (mScrollingCacheEnabled != enabled) { mScrollingCacheEnabled = enabled; if (USE_CACHE) { final int size = getChildCount(); for (int i = 0; i < size; ++i) { final View child = getChildAt(i); if (child.getVisibility() != GONE) { child.setDrawingCacheEnabled(enabled); } } } } } /** * Tests scrollability within child views of v given a delta of dx. * * @param v View to test for horizontal scrollability * @param checkV Whether the view v passed should itself be checked for scrollability (true), * or just its children (false). * @param dx Delta scrolled in pixels * @param x X coordinate of the active touch point * @param y Y coordinate of the active touch point * @return true if child views of v can be scrolled by delta of dx. */ protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) { if (v instanceof ViewGroup) { final ViewGroup group = (ViewGroup) v; final int scrollX = v.getScrollX(); final int scrollY = v.getScrollY(); final int count = group.getChildCount(); // Count backwards - let topmost views consume scroll distance first. for (int i = count - 1; i >= 0; i--) { final View child = group.getChildAt(i); if (x + scrollX >= child.getLeft() && x + scrollX < child.getRight() && y + scrollY >= child.getTop() && y + scrollY < child.getBottom() && canScroll(child, true, dx, x + scrollX - child.getLeft(), y + scrollY - child.getTop())) { return true; } } } return checkV && ViewCompat.canScrollHorizontally(v, -dx); } @Override public boolean dispatchKeyEvent(KeyEvent event) { // Let the focused view and/or our descendants get the key first return super.dispatchKeyEvent(event) || executeKeyEvent(event); } /** * You can call this function yourself to have the scroll view perform * scrolling from a key event, just as if the event had been dispatched to * it by the view hierarchy. * * @param event The key event to execute. * @return Return true if the event was handled, else false. */ public boolean executeKeyEvent(KeyEvent event) { boolean handled = false; if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (event.getKeyCode()) { case KeyEvent.KEYCODE_DPAD_LEFT: handled = arrowScroll(FOCUS_LEFT); break; case KeyEvent.KEYCODE_DPAD_RIGHT: handled = arrowScroll(FOCUS_RIGHT); break; case KeyEvent.KEYCODE_TAB: if (Build.VERSION.SDK_INT >= 11) { // The focus finder had a bug handling FOCUS_FORWARD and FOCUS_BACKWARD // before Android 3.0. Ignore the tab key on those devices. if (KeyEventCompat.hasNoModifiers(event)) { handled = arrowScroll(FOCUS_FORWARD); } else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_SHIFT_ON)) { handled = arrowScroll(FOCUS_BACKWARD); } } break; } } return handled; } public boolean arrowScroll(int direction) { View currentFocused = findFocus(); if (currentFocused == this) currentFocused = null; boolean handled = false; View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, direction); if (nextFocused != null && nextFocused != currentFocused) { if (direction == View.FOCUS_LEFT) { handled = nextFocused.requestFocus(); } else if (direction == View.FOCUS_RIGHT) { // If there is nothing to the right, or this is causing us to // jump to the left, then what we really want to do is page right. if (currentFocused != null && nextFocused.getLeft() <= currentFocused.getLeft()) { handled = pageRight(); } else { handled = nextFocused.requestFocus(); } } } else if (direction == FOCUS_LEFT || direction == FOCUS_BACKWARD) { // Trying to move left and nothing there; try to page. handled = pageLeft(); } else if (direction == FOCUS_RIGHT || direction == FOCUS_FORWARD) { // Trying to move right and nothing there; try to page. handled = pageRight(); } if (handled) { playSoundEffect(SoundEffectConstants.getContantForFocusDirection(direction)); } return handled; } boolean pageLeft() { if (mCurItem > 0) { setCurrentItem(mCurItem-1, true); return true; } return false; } boolean pageRight() { if (mCurItem < 1) { setCurrentItem(mCurItem+1, true); return true; } return false; } } ================================================ FILE: MoneyCharge/app/src/main/java/com/slidingmenu/lib/CustomViewBehind.java ================================================ package com.slidingmenu.lib; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import com.cwp.cmoneycharge.R; import com.slidingmenu.lib.SlidingMenu.CanvasTransformer; public class CustomViewBehind extends ViewGroup { private static final String TAG = "CustomViewBehind"; private static final int MARGIN_THRESHOLD = 48; // dips private int mTouchMode = SlidingMenu.TOUCHMODE_MARGIN; private CustomViewAbove mViewAbove; private View mContent; private View mSecondaryContent; private int mMarginThreshold; private int mWidthOffset; private CanvasTransformer mTransformer; private boolean mChildrenEnabled; public CustomViewBehind(Context context) { this(context, null); } public CustomViewBehind(Context context, AttributeSet attrs) { super(context, attrs); mMarginThreshold = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, MARGIN_THRESHOLD, getResources().getDisplayMetrics()); } public void setCustomViewAbove(CustomViewAbove customViewAbove) { mViewAbove = customViewAbove; } public void setCanvasTransformer(CanvasTransformer t) { mTransformer = t; } public void setWidthOffset(int i) { mWidthOffset = i; requestLayout(); } public int getBehindWidth() { return mContent.getWidth(); } public void setContent(View v) { if (mContent != null) removeView(mContent); mContent = v; addView(mContent); } public View getContent() { return mContent; } /** * Sets the secondary (right) menu for use when setMode is called with SlidingMenu.LEFT_RIGHT. * @param v the right menu */ public void setSecondaryContent(View v) { if (mSecondaryContent != null) removeView(mSecondaryContent); mSecondaryContent = v; addView(mSecondaryContent); } public View getSecondaryContent() { return mSecondaryContent; } public void setChildrenEnabled(boolean enabled) { mChildrenEnabled = enabled; } @Override public void scrollTo(int x, int y) { super.scrollTo(x, y); if (mTransformer != null) invalidate(); } @Override public boolean onInterceptTouchEvent(MotionEvent e) { return !mChildrenEnabled; } @Override public boolean onTouchEvent(MotionEvent e) { return !mChildrenEnabled; } @Override protected void dispatchDraw(Canvas canvas) { if (mTransformer != null) { canvas.save(); mTransformer.transformCanvas(canvas, mViewAbove.getPercentOpen()); super.dispatchDraw(canvas); canvas.restore(); } else super.dispatchDraw(canvas); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int width = r - l; final int height = b - t; mContent.layout(0, 0, width-mWidthOffset, height); if (mSecondaryContent != null) mSecondaryContent.layout(0, 0, width-mWidthOffset, height); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = getDefaultSize(0, widthMeasureSpec); int height = getDefaultSize(0, heightMeasureSpec); setMeasuredDimension(width, height); final int contentWidth = getChildMeasureSpec(widthMeasureSpec, 0, width-mWidthOffset); final int contentHeight = getChildMeasureSpec(heightMeasureSpec, 0, height); mContent.measure(contentWidth, contentHeight); if (mSecondaryContent != null) mSecondaryContent.measure(contentWidth, contentHeight); } private int mMode; private boolean mFadeEnabled; private final Paint mFadePaint = new Paint(); private float mScrollScale; private Drawable mShadowDrawable; private Drawable mSecondaryShadowDrawable; private int mShadowWidth; private float mFadeDegree; public void setMode(int mode) { if (mode == SlidingMenu.LEFT || mode == SlidingMenu.RIGHT) { if (mContent != null) mContent.setVisibility(View.VISIBLE); if (mSecondaryContent != null) mSecondaryContent.setVisibility(View.INVISIBLE); } mMode = mode; } public int getMode() { return mMode; } public void setScrollScale(float scrollScale) { mScrollScale = scrollScale; } public float getScrollScale() { return mScrollScale; } public void setShadowDrawable(Drawable shadow) { mShadowDrawable = shadow; invalidate(); } public void setSecondaryShadowDrawable(Drawable shadow) { mSecondaryShadowDrawable = shadow; invalidate(); } public void setShadowWidth(int width) { mShadowWidth = width; invalidate(); } public void setFadeEnabled(boolean b) { mFadeEnabled = b; } public void setFadeDegree(float degree) { if (degree > 1.0f || degree < 0.0f) throw new IllegalStateException("The BehindFadeDegree must be between 0.0f and 1.0f"); mFadeDegree = degree; } public int getMenuPage(int page) { page = (page > 1) ? 2 : ((page < 1) ? 0 : page); if (mMode == SlidingMenu.LEFT && page > 1) { return 0; } else if (mMode == SlidingMenu.RIGHT && page < 1) { return 2; } else { return page; } } public void scrollBehindTo(View content, int x, int y) { int vis = View.VISIBLE; if (mMode == SlidingMenu.LEFT) { if (x >= content.getLeft()) vis = View.INVISIBLE; scrollTo((int)((x + getBehindWidth())*mScrollScale), y); } else if (mMode == SlidingMenu.RIGHT) { if (x <= content.getLeft()) vis = View.INVISIBLE; scrollTo((int)(getBehindWidth() - getWidth() + (x-getBehindWidth())*mScrollScale), y); } else if (mMode == SlidingMenu.LEFT_RIGHT) { mContent.setVisibility(x >= content.getLeft() ? View.INVISIBLE : View.VISIBLE); mSecondaryContent.setVisibility(x <= content.getLeft() ? View.INVISIBLE : View.VISIBLE); vis = x == 0 ? View.INVISIBLE : View.VISIBLE; if (x <= content.getLeft()) { scrollTo((int)((x + getBehindWidth())*mScrollScale), y); } else { scrollTo((int)(getBehindWidth() - getWidth() + (x-getBehindWidth())*mScrollScale), y); } } if (vis == View.INVISIBLE) Log.v(TAG, "behind INVISIBLE"); setVisibility(vis); } public int getMenuLeft(View content, int page) { if (mMode == SlidingMenu.LEFT) { switch (page) { case 0: return content.getLeft() - getBehindWidth(); case 2: return content.getLeft(); } } else if (mMode == SlidingMenu.RIGHT) { switch (page) { case 0: return content.getLeft(); case 2: return content.getLeft() + getBehindWidth(); } } else if (mMode == SlidingMenu.LEFT_RIGHT) { switch (page) { case 0: return content.getLeft() - getBehindWidth(); case 2: return content.getLeft() + getBehindWidth(); } } return content.getLeft(); } public int getAbsLeftBound(View content) { if (mMode == SlidingMenu.LEFT || mMode == SlidingMenu.LEFT_RIGHT) { return content.getLeft() - getBehindWidth(); } else if (mMode == SlidingMenu.RIGHT) { return content.getLeft(); } return 0; } public int getAbsRightBound(View content) { if (mMode == SlidingMenu.LEFT) { return content.getLeft(); } else if (mMode == SlidingMenu.RIGHT || mMode == SlidingMenu.LEFT_RIGHT) { return content.getLeft() + getBehindWidth(); } return 0; } public boolean marginTouchAllowed(View content, int x) { int left = content.getLeft(); int right = content.getRight(); if (mMode == SlidingMenu.LEFT) { return (x >= left && x <= mMarginThreshold + left); } else if (mMode == SlidingMenu.RIGHT) { return (x <= right && x >= right - mMarginThreshold); } else if (mMode == SlidingMenu.LEFT_RIGHT) { return (x >= left && x <= mMarginThreshold + left) || (x <= right && x >= right - mMarginThreshold); } return false; } public void setTouchMode(int i) { mTouchMode = i; } public boolean menuOpenTouchAllowed(View content, int currPage, float x) { switch (mTouchMode) { case SlidingMenu.TOUCHMODE_FULLSCREEN: return true; case SlidingMenu.TOUCHMODE_MARGIN: return menuTouchInQuickReturn(content, currPage, x); } return false; } public boolean menuTouchInQuickReturn(View content, int currPage, float x) { if (mMode == SlidingMenu.LEFT || (mMode == SlidingMenu.LEFT_RIGHT && currPage == 0)) { return x >= content.getLeft(); } else if (mMode == SlidingMenu.RIGHT || (mMode == SlidingMenu.LEFT_RIGHT && currPage == 2)) { return x <= content.getRight(); } return false; } public boolean menuClosedSlideAllowed(float dx) { if (mMode == SlidingMenu.LEFT) { return dx > 0; } else if (mMode == SlidingMenu.RIGHT) { return dx < 0; } else if (mMode == SlidingMenu.LEFT_RIGHT) { return true; } return false; } public boolean menuOpenSlideAllowed(float dx) { if (mMode == SlidingMenu.LEFT) { return dx < 0; } else if (mMode == SlidingMenu.RIGHT) { return dx > 0; } else if (mMode == SlidingMenu.LEFT_RIGHT) { return true; } return false; } public void drawShadow(View content, Canvas canvas) { if (mShadowDrawable == null || mShadowWidth <= 0) return; int left = 0; if (mMode == SlidingMenu.LEFT) { left = content.getLeft() - mShadowWidth; } else if (mMode == SlidingMenu.RIGHT) { left = content.getRight(); } else if (mMode == SlidingMenu.LEFT_RIGHT) { if (mSecondaryShadowDrawable != null) { left = content.getRight(); mSecondaryShadowDrawable.setBounds(left, 0, left + mShadowWidth, getHeight()); mSecondaryShadowDrawable.draw(canvas); } left = content.getLeft() - mShadowWidth; } mShadowDrawable.setBounds(left, 0, left + mShadowWidth, getHeight()); mShadowDrawable.draw(canvas); } public void drawFade(View content, Canvas canvas, float openPercent) { if (!mFadeEnabled) return; final int alpha = (int) (mFadeDegree * 255 * Math.abs(1-openPercent)); mFadePaint.setColor(Color.argb(alpha, 0, 0, 0)); int left = 0; int right = 0; if (mMode == SlidingMenu.LEFT) { left = content.getLeft() - getBehindWidth(); right = content.getLeft(); } else if (mMode == SlidingMenu.RIGHT) { left = content.getRight(); right = content.getRight() + getBehindWidth(); } else if (mMode == SlidingMenu.LEFT_RIGHT) { left = content.getLeft() - getBehindWidth(); right = content.getLeft(); canvas.drawRect(left, 0, right, getHeight(), mFadePaint); left = content.getRight(); right = content.getRight() + getBehindWidth(); } canvas.drawRect(left, 0, right, getHeight(), mFadePaint); } private boolean mSelectorEnabled = true; private Bitmap mSelectorDrawable; private View mSelectedView; public void drawSelector(View content, Canvas canvas, float openPercent) { if (!mSelectorEnabled) return; if (mSelectorDrawable != null && mSelectedView != null) { String tag = (String) mSelectedView.getTag(R.id.selected_view); if (tag.equals(TAG+"SelectedView")) { canvas.save(); int left, right, offset; offset = (int) (mSelectorDrawable.getWidth() * openPercent); if (mMode == SlidingMenu.LEFT) { right = content.getLeft(); left = right - offset; canvas.clipRect(left, 0, right, getHeight()); canvas.drawBitmap(mSelectorDrawable, left, getSelectorTop(), null); } else if (mMode == SlidingMenu.RIGHT) { left = content.getRight(); right = left + offset; canvas.clipRect(left, 0, right, getHeight()); canvas.drawBitmap(mSelectorDrawable, right - mSelectorDrawable.getWidth(), getSelectorTop(), null); } canvas.restore(); } } } public void setSelectorEnabled(boolean b) { mSelectorEnabled = b; } public void setSelectedView(View v) { if (mSelectedView != null) { mSelectedView.setTag(R.id.selected_view, null); mSelectedView = null; } if (v != null && v.getParent() != null) { mSelectedView = v; mSelectedView.setTag(R.id.selected_view, TAG+"SelectedView"); invalidate(); } } private int getSelectorTop() { int y = mSelectedView.getTop(); y += (mSelectedView.getHeight() - mSelectorDrawable.getHeight()) / 2; return y; } public void setSelectorBitmap(Bitmap b) { mSelectorDrawable = b; refreshDrawableState(); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/slidingmenu/lib/MenuInterface.java ================================================ package com.slidingmenu.lib; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.view.View; public interface MenuInterface { public abstract void scrollBehindTo(int x, int y, CustomViewBehind cvb, float scrollScale); public abstract int getMenuLeft(CustomViewBehind cvb, View content); public abstract int getAbsLeftBound(CustomViewBehind cvb, View content); public abstract int getAbsRightBound(CustomViewBehind cvb, View content); public abstract boolean marginTouchAllowed(View content, int x, int threshold); public abstract boolean menuOpenTouchAllowed(View content, int currPage, int x); public abstract boolean menuTouchInQuickReturn(View content, int currPage, int x); public abstract boolean menuClosedSlideAllowed(int x); public abstract boolean menuOpenSlideAllowed(int x); public abstract void drawShadow(Canvas canvas, Drawable shadow, int width); public abstract void drawFade(Canvas canvas, int alpha, CustomViewBehind cvb, View content); public abstract void drawSelector(View content, Canvas canvas, float percentOpen); } ================================================ FILE: MoneyCharge/app/src/main/java/com/slidingmenu/lib/SlidingMenu.java ================================================ package com.slidingmenu.lib; import java.lang.reflect.Method; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Point; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Handler; import android.os.Parcel; import android.os.Parcelable; import android.util.AttributeSet; import android.util.Log; import android.view.Display; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.FrameLayout; import android.widget.RelativeLayout; import com.cwp.cmoneycharge.R; import com.slidingmenu.lib.CustomViewAbove.OnPageChangeListener; public class SlidingMenu extends RelativeLayout { private static final String TAG = "SlidingMenu"; public static final int SLIDING_WINDOW = 0; public static final int SLIDING_CONTENT = 1; private boolean mActionbarOverlay = false; /** Constant value for use with setTouchModeAbove(). Allows the SlidingMenu to be opened with a swipe * gesture on the screen's margin */ public static final int TOUCHMODE_MARGIN = 0; /** Constant value for use with setTouchModeAbove(). Allows the SlidingMenu to be opened with a swipe * gesture anywhere on the screen */ public static final int TOUCHMODE_FULLSCREEN = 1; /** Constant value for use with setTouchModeAbove(). Denies the SlidingMenu to be opened with a swipe * gesture */ public static final int TOUCHMODE_NONE = 2; /** Constant value for use with setMode(). Puts the menu to the left of the content. */ public static final int LEFT = 0; /** Constant value for use with setMode(). Puts the menu to the right of the content. */ public static final int RIGHT = 1; /** Constant value for use with setMode(). Puts menus to the left and right of the content. */ public static final int LEFT_RIGHT = 2; private CustomViewAbove mViewAbove; private CustomViewBehind mViewBehind; private OnOpenListener mOpenListener; private OnCloseListener mCloseListener; /** * The listener interface for receiving onOpen events. * The class that is interested in processing a onOpen * event implements this interface, and the object created * with that class is registered with a component using the * component's addOnOpenListener method. When * the onOpen event occurs, that object's appropriate * method is invoked */ public interface OnOpenListener { /** * On open. */ public void onOpen(); } /** * The listener interface for receiving onOpened events. * The class that is interested in processing a onOpened * event implements this interface, and the object created * with that class is registered with a component using the * component's addOnOpenedListener method. When * the onOpened event occurs, that object's appropriate * method is invoked. * * @see OnOpenedEvent */ public interface OnOpenedListener { /** * On opened. */ public void onOpened(); } /** * The listener interface for receiving onClose events. * The class that is interested in processing a onClose * event implements this interface, and the object created * with that class is registered with a component using the * component's addOnCloseListener method. When * the onClose event occurs, that object's appropriate * method is invoked. * * @see OnCloseEvent */ public interface OnCloseListener { /** * On close. */ public void onClose(); } /** * The listener interface for receiving onClosed events. * The class that is interested in processing a onClosed * event implements this interface, and the object created * with that class is registered with a component using the * component's addOnClosedListener method. When * the onClosed event occurs, that object's appropriate * method is invoked. * * @see OnClosedEvent */ public interface OnClosedListener { /** * On closed. */ public void onClosed(); } /** * The Interface CanvasTransformer. */ public interface CanvasTransformer { /** * Transform canvas. * * @param canvas the canvas * @param percentOpen the percent open */ public void transformCanvas(Canvas canvas, float percentOpen); } /** * Instantiates a new SlidingMenu. * * @param context the associated Context */ public SlidingMenu(Context context) { this(context, null); } /** * Instantiates a new SlidingMenu and attach to Activity. * * @param activity the activity to attach slidingmenu * @param slideStyle the slidingmenu style */ public SlidingMenu(Activity activity, int slideStyle) { this(activity, null); this.attachToActivity(activity, slideStyle); } /** * Instantiates a new SlidingMenu. * * @param context the associated Context * @param attrs the attrs */ public SlidingMenu(Context context, AttributeSet attrs) { this(context, attrs, 0); } /** * Instantiates a new SlidingMenu. * * @param context the associated Context * @param attrs the attrs * @param defStyle the def style */ public SlidingMenu(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); LayoutParams behindParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); mViewBehind = new CustomViewBehind(context); addView(mViewBehind, behindParams); LayoutParams aboveParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); mViewAbove = new CustomViewAbove(context); addView(mViewAbove, aboveParams); // register the CustomViewBehind with the CustomViewAbove mViewAbove.setCustomViewBehind(mViewBehind); mViewBehind.setCustomViewAbove(mViewAbove); mViewAbove.setOnPageChangeListener(new OnPageChangeListener() { public static final int POSITION_OPEN = 0; public static final int POSITION_CLOSE = 1; public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } public void onPageSelected(int position) { if (position == POSITION_OPEN && mOpenListener != null) { mOpenListener.onOpen(); } else if (position == POSITION_CLOSE && mCloseListener != null) { mCloseListener.onClose(); } } }); // now style everything! TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.SlidingMenu); // set the above and behind views if defined in xml int mode = ta.getInt(R.styleable.SlidingMenu_mode, LEFT); setMode(mode); int viewAbove = ta.getResourceId(R.styleable.SlidingMenu_viewAbove, -1); if (viewAbove != -1) { setContent(viewAbove); } else { setContent(new FrameLayout(context)); } int viewBehind = ta.getResourceId(R.styleable.SlidingMenu_viewBehind, -1); if (viewBehind != -1) { setMenu(viewBehind); } else { setMenu(new FrameLayout(context)); } int touchModeAbove = ta.getInt(R.styleable.SlidingMenu_touchModeAbove, TOUCHMODE_MARGIN); setTouchModeAbove(touchModeAbove); int touchModeBehind = ta.getInt(R.styleable.SlidingMenu_touchModeBehind, TOUCHMODE_MARGIN); setTouchModeBehind(touchModeBehind); int offsetBehind = (int) ta.getDimension(R.styleable.SlidingMenu_behindOffset, -1); int widthBehind = (int) ta.getDimension(R.styleable.SlidingMenu_behindWidth, -1); if (offsetBehind != -1 && widthBehind != -1) throw new IllegalStateException("Cannot set both behindOffset and behindWidth for a SlidingMenu"); else if (offsetBehind != -1) setBehindOffset(offsetBehind); else if (widthBehind != -1) setBehindWidth(widthBehind); else setBehindOffset(0); float scrollOffsetBehind = ta.getFloat(R.styleable.SlidingMenu_behindScrollScale, 0.33f); setBehindScrollScale(scrollOffsetBehind); int shadowRes = ta.getResourceId(R.styleable.SlidingMenu_shadowDrawable, -1); if (shadowRes != -1) { setShadowDrawable(shadowRes); } int shadowWidth = (int) ta.getDimension(R.styleable.SlidingMenu_shadowWidth, 0); setShadowWidth(shadowWidth); boolean fadeEnabled = ta.getBoolean(R.styleable.SlidingMenu_fadeEnabled, true); setFadeEnabled(fadeEnabled); float fadeDeg = ta.getFloat(R.styleable.SlidingMenu_fadeDegree, 0.33f); setFadeDegree(fadeDeg); boolean selectorEnabled = ta.getBoolean(R.styleable.SlidingMenu_selectorEnabled, false); setSelectorEnabled(selectorEnabled); int selectorRes = ta.getResourceId(R.styleable.SlidingMenu_selectorDrawable, -1); if (selectorRes != -1) setSelectorDrawable(selectorRes); ta.recycle(); } /** * Attaches the SlidingMenu to an entire Activity * * @param activity the Activity * @param slideStyle either SLIDING_CONTENT or SLIDING_WINDOW */ public void attachToActivity(Activity activity, int slideStyle) { attachToActivity(activity, slideStyle, false); } /** * Attaches the SlidingMenu to an entire Activity * * @param activity the Activity * @param slideStyle either SLIDING_CONTENT or SLIDING_WINDOW * @param actionbarOverlay whether or not the ActionBar is overlaid */ public void attachToActivity(Activity activity, int slideStyle, boolean actionbarOverlay) { if (slideStyle != SLIDING_WINDOW && slideStyle != SLIDING_CONTENT) throw new IllegalArgumentException("slideStyle must be either SLIDING_WINDOW or SLIDING_CONTENT"); if (getParent() != null) throw new IllegalStateException("This SlidingMenu appears to already be attached"); // get the window background TypedArray a = activity.getTheme().obtainStyledAttributes(new int[] {android.R.attr.windowBackground}); int background = a.getResourceId(0, 0); a.recycle(); switch (slideStyle) { case SLIDING_WINDOW: mActionbarOverlay = false; ViewGroup decor = (ViewGroup) activity.getWindow().getDecorView(); ViewGroup decorChild = (ViewGroup) decor.getChildAt(0); // save ActionBar themes that have transparent assets decorChild.setBackgroundResource(background); decor.removeView(decorChild); decor.addView(this); setContent(decorChild); break; case SLIDING_CONTENT: mActionbarOverlay = actionbarOverlay; // take the above view out of ViewGroup contentParent = (ViewGroup)activity.findViewById(android.R.id.content); View content = contentParent.getChildAt(0); contentParent.removeView(content); contentParent.addView(this); setContent(content); // save people from having transparent backgrounds if (content.getBackground() == null) content.setBackgroundResource(background); break; } } /** * Set the above view content from a layout resource. The resource will be inflated, adding all top-level views * to the above view. * * @param res the new content */ public void setContent(int res) { setContent(LayoutInflater.from(getContext()).inflate(res, null)); } /** * Set the above view content to the given View. * * @param view The desired content to display. */ public void setContent(View view) { mViewAbove.setContent(view); showContent(); } /** * Retrieves the current content. * @return the current content */ public View getContent() { return mViewAbove.getContent(); } /** * Set the behind view (menu) content from a layout resource. The resource will be inflated, adding all top-level views * to the behind view. * * @param res the new content */ public void setMenu(int res) { setMenu(LayoutInflater.from(getContext()).inflate(res, null)); } /** * Set the behind view (menu) content to the given View. * * @param view The desired content to display. */ public void setMenu(View v) { mViewBehind.setContent(v); } /** * Retrieves the main menu. * @return the main menu */ public View getMenu() { return mViewBehind.getContent(); } /** * Set the secondary behind view (right menu) content from a layout resource. The resource will be inflated, adding all top-level views * to the behind view. * * @param res the new content */ public void setSecondaryMenu(int res) { setSecondaryMenu(LayoutInflater.from(getContext()).inflate(res, null)); } /** * Set the secondary behind view (right menu) content to the given View. * * @param view The desired content to display. */ public void setSecondaryMenu(View v) { mViewBehind.setSecondaryContent(v); // mViewBehind.invalidate(); } /** * Retrieves the current secondary menu (right). * @return the current menu */ public View getSecondaryMenu() { return mViewBehind.getSecondaryContent(); } /** * Sets the sliding enabled. * * @param b true to enable sliding, false to disable it. */ public void setSlidingEnabled(boolean b) { mViewAbove.setSlidingEnabled(b); } /** * Checks if is sliding enabled. * * @return true, if is sliding enabled */ public boolean isSlidingEnabled() { return mViewAbove.isSlidingEnabled(); } /** * Sets which side the SlidingMenu should appear on. * @param mode must be either SlidingMenu.LEFT or SlidingMenu.RIGHT */ public void setMode(int mode) { if (mode != LEFT && mode != RIGHT && mode != LEFT_RIGHT) { throw new IllegalStateException("SlidingMenu mode must be LEFT, RIGHT, or LEFT_RIGHT"); } mViewBehind.setMode(mode); } /** * Returns the current side that the SlidingMenu is on. * @return the current mode, either SlidingMenu.LEFT or SlidingMenu.RIGHT */ public int getMode() { return mViewBehind.getMode(); } /** * Sets whether or not the SlidingMenu is in static mode (i.e. nothing is moving and everything is showing) * * @param b true to set static mode, false to disable static mode. */ public void setStatic(boolean b) { if (b) { setSlidingEnabled(false); mViewAbove.setCustomViewBehind(null); mViewAbove.setCurrentItem(1); // mViewBehind.setCurrentItem(0); } else { mViewAbove.setCurrentItem(1); // mViewBehind.setCurrentItem(1); mViewAbove.setCustomViewBehind(mViewBehind); setSlidingEnabled(true); } } /** * Opens the menu and shows the menu view. */ public void showMenu() { showMenu(true); } /** * Opens the menu and shows the menu view. * * @param animate true to animate the transition, false to ignore animation */ public void showMenu(boolean animate) { mViewAbove.setCurrentItem(0, animate); } /** * Opens the menu and shows the secondary menu view. Will default to the regular menu * if there is only one. */ public void showSecondaryMenu() { showSecondaryMenu(true); } /** * Opens the menu and shows the secondary (right) menu view. Will default to the regular menu * if there is only one. * * @param animate true to animate the transition, false to ignore animation */ public void showSecondaryMenu(boolean animate) { mViewAbove.setCurrentItem(2, animate); } /** * Closes the menu and shows the above view. */ public void showContent() { showContent(true); } /** * Closes the menu and shows the above view. * * @param animate true to animate the transition, false to ignore animation */ public void showContent(boolean animate) { mViewAbove.setCurrentItem(1, animate); } /** * Toggle the SlidingMenu. If it is open, it will be closed, and vice versa. */ public void toggle() { toggle(true); } /** * Toggle the SlidingMenu. If it is open, it will be closed, and vice versa. * * @param animate true to animate the transition, false to ignore animation */ public void toggle(boolean animate) { if (isMenuShowing()) { showContent(animate); } else { showMenu(animate); } } /** * Checks if is the behind view showing. * * @return Whether or not the behind view is showing */ public boolean isMenuShowing() { return mViewAbove.getCurrentItem() == 0 || mViewAbove.getCurrentItem() == 2; } /** * Checks if is the behind view showing. * * @return Whether or not the behind view is showing */ public boolean isSecondaryMenuShowing() { return mViewAbove.getCurrentItem() == 2; } /** * Gets the behind offset. * * @return The margin on the right of the screen that the behind view scrolls to */ public int getBehindOffset() { return ((RelativeLayout.LayoutParams)mViewBehind.getLayoutParams()).rightMargin; } /** * Sets the behind offset. * * @param i The margin, in pixels, on the right of the screen that the behind view scrolls to. */ public void setBehindOffset(int i) { // RelativeLayout.LayoutParams params = ((RelativeLayout.LayoutParams)mViewBehind.getLayoutParams()); // int bottom = params.bottomMargin; // int top = params.topMargin; // int left = params.leftMargin; // params.setMargins(left, top, i, bottom); mViewBehind.setWidthOffset(i); } /** * Sets the behind offset. * * @param resID The dimension resource id to be set as the behind offset. * The menu, when open, will leave this width margin on the right of the screen. */ public void setBehindOffsetRes(int resID) { int i = (int) getContext().getResources().getDimension(resID); setBehindOffset(i); } /** * Sets the above offset. * * @param i the new above offset, in pixels */ public void setAboveOffset(int i) { mViewAbove.setAboveOffset(i); } /** * Sets the above offset. * * @param resID The dimension resource id to be set as the above offset. */ public void setAboveOffsetRes(int resID) { int i = (int) getContext().getResources().getDimension(resID); setAboveOffset(i); } /** * Sets the behind width. * * @param i The width the Sliding Menu will open to, in pixels */ @SuppressWarnings("deprecation") public void setBehindWidth(int i) { int width; Display display = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay(); try { Class cls = Display.class; Class[] parameterTypes = {Point.class}; Point parameter = new Point(); Method method = cls.getMethod("getSize", parameterTypes); method.invoke(display, parameter); width = parameter.x; } catch (Exception e) { width = display.getWidth(); } setBehindOffset(width-i); } /** * Sets the behind width. * * @param res The dimension resource id to be set as the behind width offset. * The menu, when open, will open this wide. */ public void setBehindWidthRes(int res) { int i = (int) getContext().getResources().getDimension(res); setBehindWidth(i); } /** * Gets the behind scroll scale. * * @return The scale of the parallax scroll */ public float getBehindScrollScale() { return mViewBehind.getScrollScale(); } /** * Sets the behind scroll scale. * * @param f The scale of the parallax scroll (i.e. 1.0f scrolls 1 pixel for every * 1 pixel that the above view scrolls and 0.0f scrolls 0 pixels) */ public void setBehindScrollScale(float f) { if (f < 0 && f > 1) throw new IllegalStateException("ScrollScale must be between 0 and 1"); mViewBehind.setScrollScale(f); } /** * Sets the behind canvas transformer. * * @param t the new behind canvas transformer */ public void setBehindCanvasTransformer(CanvasTransformer t) { mViewBehind.setCanvasTransformer(t); } /** * Gets the touch mode above. * * @return the touch mode above */ public int getTouchModeAbove() { return mViewAbove.getTouchMode(); } /** * Controls whether the SlidingMenu can be opened with a swipe gesture. * Options are {@link #TOUCHMODE_MARGIN TOUCHMODE_MARGIN}, {@link #TOUCHMODE_FULLSCREEN TOUCHMODE_FULLSCREEN}, * or {@link #TOUCHMODE_NONE TOUCHMODE_NONE} * * @param i the new touch mode */ public void setTouchModeAbove(int i) { if (i != TOUCHMODE_FULLSCREEN && i != TOUCHMODE_MARGIN && i != TOUCHMODE_NONE) { throw new IllegalStateException("TouchMode must be set to either" + "TOUCHMODE_FULLSCREEN or TOUCHMODE_MARGIN or TOUCHMODE_NONE."); } mViewAbove.setTouchMode(i); } /** * Controls whether the SlidingMenu can be opened with a swipe gesture. * Options are {@link #TOUCHMODE_MARGIN TOUCHMODE_MARGIN}, {@link #TOUCHMODE_FULLSCREEN TOUCHMODE_FULLSCREEN}, * or {@link #TOUCHMODE_NONE TOUCHMODE_NONE} * * @param i the new touch mode */ public void setTouchModeBehind(int i) { if (i != TOUCHMODE_FULLSCREEN && i != TOUCHMODE_MARGIN && i != TOUCHMODE_NONE) { throw new IllegalStateException("TouchMode must be set to either" + "TOUCHMODE_FULLSCREEN or TOUCHMODE_MARGIN or TOUCHMODE_NONE."); } mViewBehind.setTouchMode(i); } /** * Sets the shadow drawable. * * @param resId the resource ID of the new shadow drawable */ public void setShadowDrawable(int resId) { setShadowDrawable(getContext().getResources().getDrawable(resId)); } /** * Sets the shadow drawable. * * @param d the new shadow drawable */ public void setShadowDrawable(Drawable d) { mViewBehind.setShadowDrawable(d); } /** * Sets the secondary (right) shadow drawable. * * @param resId the resource ID of the new shadow drawable */ public void setSecondaryShadowDrawable(int resId) { setSecondaryShadowDrawable(getContext().getResources().getDrawable(resId)); } /** * Sets the secondary (right) shadow drawable. * * @param d the new shadow drawable */ public void setSecondaryShadowDrawable(Drawable d) { mViewBehind.setSecondaryShadowDrawable(d); } /** * Sets the shadow width. * * @param resId The dimension resource id to be set as the shadow width. */ public void setShadowWidthRes(int resId) { setShadowWidth((int)getResources().getDimension(resId)); } /** * Sets the shadow width. * * @param pixels the new shadow width, in pixels */ public void setShadowWidth(int pixels) { mViewBehind.setShadowWidth(pixels); } /** * Enables or disables the SlidingMenu's fade in and out * * @param b true to enable fade, false to disable it */ public void setFadeEnabled(boolean b) { mViewBehind.setFadeEnabled(b); } /** * Sets how much the SlidingMenu fades in and out. Fade must be enabled, see * {@link #setFadeEnabled(boolean) setFadeEnabled(boolean)} * * @param f the new fade degree, between 0.0f and 1.0f */ public void setFadeDegree(float f) { mViewBehind.setFadeDegree(f); } /** * Enables or disables whether the selector is drawn * * @param b true to draw the selector, false to not draw the selector */ public void setSelectorEnabled(boolean b) { mViewBehind.setSelectorEnabled(true); } /** * Sets the selected view. The selector will be drawn here * * @param v the new selected view */ public void setSelectedView(View v) { mViewBehind.setSelectedView(v); } /** * Sets the selector drawable. * * @param res a resource ID for the selector drawable */ public void setSelectorDrawable(int res) { mViewBehind.setSelectorBitmap(BitmapFactory.decodeResource(getResources(), res)); } /** * Sets the selector drawable. * * @param b the new selector bitmap */ public void setSelectorBitmap(Bitmap b) { mViewBehind.setSelectorBitmap(b); } /** * Add a View ignored by the Touch Down event when mode is Fullscreen * * @param v a view to be ignored */ public void addIgnoredView(View v) { mViewAbove.addIgnoredView(v); } /** * Remove a View ignored by the Touch Down event when mode is Fullscreen * * @param v a view not wanted to be ignored anymore */ public void removeIgnoredView(View v) { mViewAbove.removeIgnoredView(v); } /** * Clear the list of Views ignored by the Touch Down event when mode is Fullscreen */ public void clearIgnoredViews() { mViewAbove.clearIgnoredViews(); } /** * Sets the OnOpenListener. {@link OnOpenListener#onOpen() OnOpenListener.onOpen()} will be called when the SlidingMenu is opened * * @param listener the new OnOpenListener */ public void setOnOpenListener(OnOpenListener listener) { //mViewAbove.setOnOpenListener(listener); mOpenListener = listener; } /** * Sets the OnCloseListener. {@link OnCloseListener#onClose() OnCloseListener.onClose()} will be called when the SlidingMenu is closed * * @param listener the new setOnCloseListener */ public void setOnCloseListener(OnCloseListener listener) { //mViewAbove.setOnCloseListener(listener); mCloseListener = listener; } /** * Sets the OnOpenedListener. {@link OnOpenedListener#onOpened() OnOpenedListener.onOpened()} will be called after the SlidingMenu is opened * * @param listener the new OnOpenedListener */ public void setOnOpenedListener(OnOpenedListener listener) { mViewAbove.setOnOpenedListener(listener); } /** * Sets the OnClosedListener. {@link OnClosedListener#onClosed() OnClosedListener.onClosed()} will be called after the SlidingMenu is closed * * @param listener the new OnClosedListener */ public void setOnClosedListener(OnClosedListener listener) { mViewAbove.setOnClosedListener(listener); } public static class SavedState extends BaseSavedState { private final int mItem; public SavedState(Parcelable superState, int item) { super(superState); mItem = item; } private SavedState(Parcel in) { super(in); mItem = in.readInt(); } public int getItem() { return mItem; } /* (non-Javadoc) * @see android.view.AbsSavedState#writeToParcel(android.os.Parcel, int) */ public void writeToParcel(Parcel out, int flags) { super.writeToParcel(out, flags); out.writeInt(mItem); } public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { public SavedState createFromParcel(Parcel in) { return new SavedState(in); } public SavedState[] newArray(int size) { return new SavedState[size]; } }; } /* (non-Javadoc) * @see android.view.View#onSaveInstanceState() */ @Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); SavedState ss = new SavedState(superState, mViewAbove.getCurrentItem()); return ss; } /* (non-Javadoc) * @see android.view.View#onRestoreInstanceState(android.os.Parcelable) */ @Override protected void onRestoreInstanceState(Parcelable state) { SavedState ss = (SavedState)state; super.onRestoreInstanceState(ss.getSuperState()); mViewAbove.setCurrentItem(ss.getItem()); } /* (non-Javadoc) * @see android.view.ViewGroup#fitSystemWindows(android.graphics.Rect) */ @SuppressLint("NewApi") @Override protected boolean fitSystemWindows(Rect insets) { int leftPadding = insets.left; int rightPadding = insets.right; int topPadding = insets.top; int bottomPadding = insets.bottom; if (!mActionbarOverlay) { Log.v(TAG, "setting padding!"); setPadding(leftPadding, topPadding, rightPadding, bottomPadding); } return true; } private Handler mHandler = new Handler(); @TargetApi(Build.VERSION_CODES.HONEYCOMB) public void manageLayers(float percentOpen) { if (Build.VERSION.SDK_INT < 11) return; boolean layer = percentOpen > 0.0f && percentOpen < 1.0f; final int layerType = layer ? View.LAYER_TYPE_HARDWARE : View.LAYER_TYPE_NONE; if (layerType != getContent().getLayerType()) { mHandler.post(new Runnable() { public void run() { Log.v(TAG, "changing layerType. hardware? " + (layerType == View.LAYER_TYPE_HARDWARE)); getContent().setLayerType(layerType, null); getMenu().setLayerType(layerType, null); if (getSecondaryMenu() != null) { getSecondaryMenu().setLayerType(layerType, null); } } }); } } } ================================================ FILE: MoneyCharge/app/src/main/java/com/slidingmenu/lib/app/SlidingActivity.java ================================================ package com.slidingmenu.lib.app; import android.annotation.TargetApi; import android.app.Activity; import android.os.Build; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.ViewGroup.LayoutParams; import com.slidingmenu.lib.SlidingMenu; public class SlidingActivity extends Activity implements SlidingActivityBase { private SlidingActivityHelper mHelper; /* * (non-Javadoc) * * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHelper = new SlidingActivityHelper(this); mHelper.onCreate(savedInstanceState); } /* * (non-Javadoc) * * @see android.app.Activity#onPostCreate(android.os.Bundle) */ @Override public void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mHelper.onPostCreate(savedInstanceState); } /* * (non-Javadoc) * * @see android.app.Activity#findViewById(int) */ @Override public View findViewById(int id) { View v = super.findViewById(id); if (v != null) return v; return mHelper.findViewById(id); } /* * (non-Javadoc) * * @see android.app.Activity#onSaveInstanceState(android.os.Bundle) */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mHelper.onSaveInstanceState(outState); } /* * (non-Javadoc) * * @see android.app.Activity#setContentView(int) */ @Override public void setContentView(int id) { setContentView(getLayoutInflater().inflate(id, null)); } /* * (non-Javadoc) * * @see android.app.Activity#setContentView(android.view.View) */ @Override public void setContentView(View v) { setContentView(v, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); } /* * (non-Javadoc) * * @see android.app.Activity#setContentView(android.view.View, * android.view.ViewGroup.LayoutParams) */ @Override public void setContentView(View v, LayoutParams params) { super.setContentView(v, params); mHelper.registerAboveContentView(v, params); } /* * (non-Javadoc) * * @see * com.slidingmenu.lib.app.SlidingActivityBase#setBehindContentView(int) */ public void setBehindContentView(int id) { setBehindContentView(getLayoutInflater().inflate(id, null)); } /* * (non-Javadoc) * * @see * com.slidingmenu.lib.app.SlidingActivityBase#setBehindContentView(android * .view.View) */ public void setBehindContentView(View v) { setBehindContentView(v, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); } /* * (non-Javadoc) * * @see * com.slidingmenu.lib.app.SlidingActivityBase#setBehindContentView(android * .view.View, android.view.ViewGroup.LayoutParams) */ public void setBehindContentView(View v, LayoutParams params) { mHelper.setBehindContentView(v, params); } /* * (non-Javadoc) * * @see com.slidingmenu.lib.app.SlidingActivityBase#getSlidingMenu() */ public SlidingMenu getSlidingMenu() { return mHelper.getSlidingMenu(); } /* * (non-Javadoc) * * @see com.slidingmenu.lib.app.SlidingActivityBase#toggle() */ public void toggle() { mHelper.toggle(); } /* * (non-Javadoc) * * @see com.slidingmenu.lib.app.SlidingActivityBase#showAbove() */ public void showContent() { mHelper.showContent(); } /* * (non-Javadoc) * * @see com.slidingmenu.lib.app.SlidingActivityBase#showBehind() */ public void showMenu() { mHelper.showMenu(); } /* * (non-Javadoc) * * @see com.slidingmenu.lib.app.SlidingActivityBase#showSecondaryMenu() */ public void showSecondaryMenu() { mHelper.showSecondaryMenu(); } /* * (non-Javadoc) * * @see * com.slidingmenu.lib.app.SlidingActivityBase#setSlidingActionBarEnabled * (boolean) */ public void setSlidingActionBarEnabled(boolean b) { mHelper.setSlidingActionBarEnabled(b); } /* * (non-Javadoc) * * @see android.app.Activity#onKeyUp(int, android.view.KeyEvent) */ @Override public boolean onKeyUp(int keyCode, KeyEvent event) { boolean b = mHelper.onKeyUp(keyCode, event); if (b) return b; return super.onKeyUp(keyCode, event); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/slidingmenu/lib/app/SlidingActivityBase.java ================================================ package com.slidingmenu.lib.app; import android.view.View; import android.view.ViewGroup.LayoutParams; import com.slidingmenu.lib.SlidingMenu; public interface SlidingActivityBase { /** * Set the behind view content to an explicit view. This view is placed directly into the behind view 's view hierarchy. * It can itself be a complex view hierarchy. * * @param view The desired content to display. * @param layoutParams Layout parameters for the view. */ public void setBehindContentView(View view, LayoutParams layoutParams); /** * Set the behind view content to an explicit view. This view is placed directly into the behind view 's view hierarchy. * It can itself be a complex view hierarchy. When calling this method, the layout parameters of the specified * view are ignored. Both the width and the height of the view are set by default to MATCH_PARENT. To use your * own layout parameters, invoke setContentView(android.view.View, android.view.ViewGroup.LayoutParams) instead. * * @param view The desired content to display. */ public void setBehindContentView(View view); /** * Set the behind view content from a layout resource. The resource will be inflated, adding all top-level views * to the behind view. * * @param layoutResID Resource ID to be inflated. */ public void setBehindContentView(int layoutResID); /** * Gets the SlidingMenu associated with this activity. * * @return the SlidingMenu associated with this activity. */ public SlidingMenu getSlidingMenu(); /** * Toggle the SlidingMenu. If it is open, it will be closed, and vice versa. */ public void toggle(); /** * Close the SlidingMenu and show the content view. */ public void showContent(); /** * Open the SlidingMenu and show the menu view. */ public void showMenu(); /** * Open the SlidingMenu and show the secondary (right) menu view. Will default to the regular menu * if there is only one. */ public void showSecondaryMenu(); /** * Controls whether the ActionBar slides along with the above view when the menu is opened, * or if it stays in place. * * @param slidingActionBarEnabled True if you want the ActionBar to slide along with the SlidingMenu, * false if you want the ActionBar to stay in place */ public void setSlidingActionBarEnabled(boolean slidingActionBarEnabled); } ================================================ FILE: MoneyCharge/app/src/main/java/com/slidingmenu/lib/app/SlidingActivityHelper.java ================================================ package com.slidingmenu.lib.app; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup.LayoutParams; import com.cwp.cmoneycharge.R; import com.slidingmenu.lib.SlidingMenu; public class SlidingActivityHelper { private Activity mActivity; private SlidingMenu mSlidingMenu; private View mViewAbove; private View mViewBehind; private boolean mBroadcasting = false; private boolean mOnPostCreateCalled = false; private boolean mEnableSlide = true; /** * Instantiates a new SlidingActivityHelper. * * @param activity the associated activity */ public SlidingActivityHelper(Activity activity) { mActivity = activity; } /** * Sets mSlidingMenu as a newly inflated SlidingMenu. Should be called within the activitiy's onCreate() * * @param savedInstanceState the saved instance state (unused) */ public void onCreate(Bundle savedInstanceState) { mSlidingMenu = (SlidingMenu) LayoutInflater.from(mActivity).inflate(R.layout.slidingmenumain, null); } /** * Further SlidingMenu initialization. Should be called within the activitiy's onPostCreate() * * @param savedInstanceState the saved instance state (unused) */ public void onPostCreate(Bundle savedInstanceState) { if (mViewBehind == null || mViewAbove == null) { throw new IllegalStateException("Both setBehindContentView must be called " + "in onCreate in addition to setContentView."); } mOnPostCreateCalled = true; mSlidingMenu.attachToActivity(mActivity, mEnableSlide ? SlidingMenu.SLIDING_WINDOW : SlidingMenu.SLIDING_CONTENT); final boolean open; final boolean secondary; if (savedInstanceState != null) { open = savedInstanceState.getBoolean("SlidingActivityHelper.open"); secondary = savedInstanceState.getBoolean("SlidingActivityHelper.secondary"); } else { open = false; secondary = false; } new Handler().post(new Runnable() { public void run() { if (open) { if (secondary) { mSlidingMenu.showSecondaryMenu(false); } else { mSlidingMenu.showMenu(false); } } else { mSlidingMenu.showContent(false); } } }); } /** * Controls whether the ActionBar slides along with the above view when the menu is opened, * or if it stays in place. * * @param slidingActionBarEnabled True if you want the ActionBar to slide along with the SlidingMenu, * false if you want the ActionBar to stay in place */ public void setSlidingActionBarEnabled(boolean slidingActionBarEnabled) { if (mOnPostCreateCalled) throw new IllegalStateException("enableSlidingActionBar must be called in onCreate."); mEnableSlide = slidingActionBarEnabled; } /** * Finds a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle). * * @param id the resource id of the desired view * @return The view if found or null otherwise. */ public View findViewById(int id) { View v; if (mSlidingMenu != null) { v = mSlidingMenu.findViewById(id); if (v != null) return v; } return null; } /** * Called to retrieve per-instance state from an activity before being killed so that the state can be * restored in onCreate(Bundle) or onRestoreInstanceState(Bundle) (the Bundle populated by this method * will be passed to both). * * @param outState Bundle in which to place your saved state. */ public void onSaveInstanceState(Bundle outState) { outState.putBoolean("SlidingActivityHelper.open", mSlidingMenu.isMenuShowing()); outState.putBoolean("SlidingActivityHelper.secondary", mSlidingMenu.isSecondaryMenuShowing()); } /** * Register the above content view. * * @param v the above content view to register * @param params LayoutParams for that view (unused) */ public void registerAboveContentView(View v, LayoutParams params) { if (!mBroadcasting) mViewAbove = v; } /** * Set the activity content to an explicit view. This view is placed directly into the activity's view * hierarchy. It can itself be a complex view hierarchy. When calling this method, the layout parameters * of the specified view are ignored. Both the width and the height of the view are set by default to * MATCH_PARENT. To use your own layout parameters, invoke setContentView(android.view.View, * android.view.ViewGroup.LayoutParams) instead. * * @param v The desired content to display. */ public void setContentView(View v) { mBroadcasting = true; mActivity.setContentView(v); } /** * Set the behind view content to an explicit view. This view is placed directly into the behind view 's view hierarchy. * It can itself be a complex view hierarchy. * * @param view The desired content to display. * @param layoutParams Layout parameters for the view. (unused) */ public void setBehindContentView(View view, LayoutParams layoutParams) { mViewBehind = view; mSlidingMenu.setMenu(mViewBehind); } /** * Gets the SlidingMenu associated with this activity. * * @return the SlidingMenu associated with this activity. */ public SlidingMenu getSlidingMenu() { return mSlidingMenu; } /** * Toggle the SlidingMenu. If it is open, it will be closed, and vice versa. */ public void toggle() { mSlidingMenu.toggle(); } /** * Close the SlidingMenu and show the content view. */ public void showContent() { mSlidingMenu.showContent(); } /** * Open the SlidingMenu and show the menu view. */ public void showMenu() { mSlidingMenu.showMenu(); } /** * Open the SlidingMenu and show the secondary menu view. Will default to the regular menu * if there is only one. */ public void showSecondaryMenu() { mSlidingMenu.showSecondaryMenu(); } /** * On key up. * * @param keyCode the key code * @param event the event * @return true, if successful */ public boolean onKeyUp(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && mSlidingMenu.isMenuShowing()) { showContent(); return true; } return false; } } ================================================ FILE: MoneyCharge/app/src/main/java/com/slidingmenu/lib/app/SlidingFragmentActivity.java ================================================ package com.slidingmenu.lib.app; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup.LayoutParams; import com.slidingmenu.lib.SlidingMenu; public class SlidingFragmentActivity extends FragmentActivity implements SlidingActivityBase { private SlidingActivityHelper mHelper; /* (non-Javadoc) * @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle) */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHelper = new SlidingActivityHelper(this); mHelper.onCreate(savedInstanceState); } /* (non-Javadoc) * @see android.app.Activity#onPostCreate(android.os.Bundle) */ @Override public void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mHelper.onPostCreate(savedInstanceState); } /* (non-Javadoc) * @see android.app.Activity#findViewById(int) */ @Override public View findViewById(int id) { View v = super.findViewById(id); if (v != null) return v; return mHelper.findViewById(id); } /* (non-Javadoc) * @see android.support.v4.app.FragmentActivity#onSaveInstanceState(android.os.Bundle) */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mHelper.onSaveInstanceState(outState); } /* (non-Javadoc) * @see android.app.Activity#setContentView(int) */ @Override public void setContentView(int id) { setContentView(getLayoutInflater().inflate(id, null)); } /* (non-Javadoc) * @see android.app.Activity#setContentView(android.view.View) */ @Override public void setContentView(View v) { setContentView(v, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); } /* (non-Javadoc) * @see android.app.Activity#setContentView(android.view.View, android.view.ViewGroup.LayoutParams) */ @Override public void setContentView(View v, LayoutParams params) { super.setContentView(v, params); mHelper.registerAboveContentView(v, params); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#setBehindContentView(int) */ public void setBehindContentView(int id) { setBehindContentView(getLayoutInflater().inflate(id, null)); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#setBehindContentView(android.view.View) */ public void setBehindContentView(View v) { setBehindContentView(v, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#setBehindContentView(android.view.View, android.view.ViewGroup.LayoutParams) */ public void setBehindContentView(View v, LayoutParams params) { mHelper.setBehindContentView(v, params); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#getSlidingMenu() */ public SlidingMenu getSlidingMenu() { return mHelper.getSlidingMenu(); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#toggle() */ public void toggle() { mHelper.toggle(); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#showAbove() */ public void showContent() { mHelper.showContent(); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#showBehind() */ public void showMenu() { mHelper.showMenu(); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#showSecondaryMenu() */ public void showSecondaryMenu() { mHelper.showSecondaryMenu(); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#setSlidingActionBarEnabled(boolean) */ public void setSlidingActionBarEnabled(boolean b) { mHelper.setSlidingActionBarEnabled(b); } /* (non-Javadoc) * @see android.app.Activity#onKeyUp(int, android.view.KeyEvent) */ @Override public boolean onKeyUp(int keyCode, KeyEvent event) { boolean b = mHelper.onKeyUp(keyCode, event); if (b) return b; return super.onKeyUp(keyCode, event); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/slidingmenu/lib/app/SlidingListActivity.java ================================================ package com.slidingmenu.lib.app; import android.app.ListActivity; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.ListView; import com.slidingmenu.lib.SlidingMenu; public class SlidingListActivity extends ListActivity implements SlidingActivityBase { private SlidingActivityHelper mHelper; /* (non-Javadoc) * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHelper = new SlidingActivityHelper(this); mHelper.onCreate(savedInstanceState); ListView listView = new ListView(this); listView.setId(android.R.id.list); setContentView(listView); } /* (non-Javadoc) * @see android.app.Activity#onPostCreate(android.os.Bundle) */ @Override public void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mHelper.onPostCreate(savedInstanceState); } /* (non-Javadoc) * @see android.app.Activity#findViewById(int) */ @Override public View findViewById(int id) { View v = super.findViewById(id); if (v != null) return v; return mHelper.findViewById(id); } /* (non-Javadoc) * @see android.app.Activity#onSaveInstanceState(android.os.Bundle) */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mHelper.onSaveInstanceState(outState); } /* (non-Javadoc) * @see android.app.Activity#setContentView(int) */ @Override public void setContentView(int id) { setContentView(getLayoutInflater().inflate(id, null)); } /* (non-Javadoc) * @see android.app.Activity#setContentView(android.view.View) */ @Override public void setContentView(View v) { setContentView(v, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); } /* (non-Javadoc) * @see android.app.Activity#setContentView(android.view.View, android.view.ViewGroup.LayoutParams) */ @Override public void setContentView(View v, LayoutParams params) { super.setContentView(v, params); mHelper.registerAboveContentView(v, params); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#setBehindContentView(int) */ public void setBehindContentView(int id) { setBehindContentView(getLayoutInflater().inflate(id, null)); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#setBehindContentView(android.view.View) */ public void setBehindContentView(View v) { setBehindContentView(v, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#setBehindContentView(android.view.View, android.view.ViewGroup.LayoutParams) */ public void setBehindContentView(View v, LayoutParams params) { mHelper.setBehindContentView(v, params); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#getSlidingMenu() */ public SlidingMenu getSlidingMenu() { return mHelper.getSlidingMenu(); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#toggle() */ public void toggle() { mHelper.toggle(); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#showAbove() */ public void showContent() { mHelper.showContent(); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#showBehind() */ public void showMenu() { mHelper.showMenu(); } /* * (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#showSecondaryMenu() */ public void showSecondaryMenu() { mHelper.showSecondaryMenu(); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#setSlidingActionBarEnabled(boolean) */ public void setSlidingActionBarEnabled(boolean b) { mHelper.setSlidingActionBarEnabled(b); } /* (non-Javadoc) * @see android.app.Activity#onKeyUp(int, android.view.KeyEvent) */ @Override public boolean onKeyUp(int keyCode, KeyEvent event) { boolean b = mHelper.onKeyUp(keyCode, event); if (b) return b; return super.onKeyUp(keyCode, event); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/slidingmenu/lib/app/SlidingMapActivity.java ================================================ //package com.slidingmenu.lib.app; // //import android.os.Bundle; //import android.view.KeyEvent; //import android.view.View; //import android.view.ViewGroup.LayoutParams; // //import com.google.android.maps.MapActivity; //import com.slidingmenu.lib.SlidingMenu; // //public abstract class SlidingMapActivity extends MapActivity implements SlidingActivityBase { // // private SlidingActivityHelper mHelper; // // /* (non-Javadoc) // * @see com.google.android.maps.MapActivity#onCreate(android.os.Bundle) // */ // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // mHelper = new SlidingActivityHelper(this); // mHelper.onCreate(savedInstanceState); // } // // /* (non-Javadoc) // * @see android.app.Activity#onPostCreate(android.os.Bundle) // */ // @Override // public void onPostCreate(Bundle savedInstanceState) { // super.onPostCreate(savedInstanceState); // mHelper.onPostCreate(savedInstanceState); // } // // /* (non-Javadoc) // * @see android.app.Activity#findViewById(int) // */ // @Override // public View findViewById(int id) { // View v = super.findViewById(id); // if (v != null) // return v; // return mHelper.findViewById(id); // } // // /* (non-Javadoc) // * @see android.app.Activity#onSaveInstanceState(android.os.Bundle) // */ // @Override // protected void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); // mHelper.onSaveInstanceState(outState); // } // // /* (non-Javadoc) // * @see android.app.Activity#setContentView(int) // */ // @Override // public void setContentView(int id) { // setContentView(getLayoutInflater().inflate(id, null)); // } // // /* (non-Javadoc) // * @see android.app.Activity#setContentView(android.view.View) // */ // @Override // public void setContentView(View v) { // setContentView(v, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); // } // // /* (non-Javadoc) // * @see android.app.Activity#setContentView(android.view.View, android.view.ViewGroup.LayoutParams) // */ // @Override // public void setContentView(View v, LayoutParams params) { // super.setContentView(v, params); // mHelper.registerAboveContentView(v, params); // } // // /* (non-Javadoc) // * @see com.slidingmenu.lib.app.SlidingActivityBase#setBehindContentView(int) // */ // public void setBehindContentView(int id) { // setBehindContentView(getLayoutInflater().inflate(id, null)); // } // // /* (non-Javadoc) // * @see com.slidingmenu.lib.app.SlidingActivityBase#setBehindContentView(android.view.View) // */ // public void setBehindContentView(View v) { // setBehindContentView(v, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); // } // // /* (non-Javadoc) // * @see com.slidingmenu.lib.app.SlidingActivityBase#setBehindContentView(android.view.View, android.view.ViewGroup.LayoutParams) // */ // public void setBehindContentView(View v, LayoutParams params) { // mHelper.setBehindContentView(v, params); // } // // /* (non-Javadoc) // * @see com.slidingmenu.lib.app.SlidingActivityBase#getSlidingMenu() // */ // public SlidingMenu getSlidingMenu() { // return mHelper.getSlidingMenu(); // } // // /* (non-Javadoc) // * @see com.slidingmenu.lib.app.SlidingActivityBase#toggle() // */ // public void toggle() { // mHelper.toggle(); // } // // /* (non-Javadoc) // * @see com.slidingmenu.lib.app.SlidingActivityBase#showAbove() // */ // public void showContent() { // mHelper.showContent(); // } // // /* (non-Javadoc) // * @see com.slidingmenu.lib.app.SlidingActivityBase#showBehind() // */ // public void showMenu() { // mHelper.showMenu(); // } // // /* (non-Javadoc) // * @see com.slidingmenu.lib.app.SlidingActivityBase#showSecondaryMenu() // */ // public void showSecondaryMenu() { // mHelper.showSecondaryMenu(); // } // // /* (non-Javadoc) // * @see com.slidingmenu.lib.app.SlidingActivityBase#setSlidingActionBarEnabled(boolean) // */ // public void setSlidingActionBarEnabled(boolean b) { // mHelper.setSlidingActionBarEnabled(b); // } // // /* (non-Javadoc) // * @see android.app.Activity#onKeyUp(int, android.view.KeyEvent) // */ // @Override // public boolean onKeyUp(int keyCode, KeyEvent event) { // boolean b = mHelper.onKeyUp(keyCode, event); // if (b) return b; // return super.onKeyUp(keyCode, event); // } // //} ================================================ FILE: MoneyCharge/app/src/main/java/com/slidingmenu/lib/app/SlidingPreferenceActivity.java ================================================ package com.slidingmenu.lib.app; import com.slidingmenu.lib.SlidingMenu; import android.os.Bundle; import android.preference.PreferenceActivity; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup.LayoutParams; public class SlidingPreferenceActivity extends PreferenceActivity implements SlidingActivityBase { private SlidingActivityHelper mHelper; /* (non-Javadoc) * @see android.app.Activity#onCreate(android.os.Bundle) */ @Override public void onCreate(Bundle savedInstanceState) { mHelper = new SlidingActivityHelper(this); super.onCreate(savedInstanceState); mHelper.onCreate(savedInstanceState); } /* (non-Javadoc) * @see android.app.Activity#onPostCreate(android.os.Bundle) */ @Override public void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mHelper.onPostCreate(savedInstanceState); } /* (non-Javadoc) * @see android.app.Activity#findViewById(int) */ @Override public View findViewById(int id) { View v = super.findViewById(id); if (v != null) return v; return mHelper.findViewById(id); } /* (non-Javadoc) * @see android.app.Activity#onSaveInstanceState(android.os.Bundle) */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); mHelper.onSaveInstanceState(outState); } /* (non-Javadoc) * @see android.app.Activity#setContentView(int) */ @Override public void setContentView(int id) { setContentView(getLayoutInflater().inflate(id, null)); } /* (non-Javadoc) * @see android.app.Activity#setContentView(android.view.View) */ @Override public void setContentView(View v) { setContentView(v, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); } /* (non-Javadoc) * @see android.app.Activity#setContentView(android.view.View, android.view.ViewGroup.LayoutParams) */ @Override public void setContentView(View v, LayoutParams params) { super.setContentView(v, params); mHelper.registerAboveContentView(v, params); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#setBehindContentView(int) */ public void setBehindContentView(int id) { setBehindContentView(getLayoutInflater().inflate(id, null)); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#setBehindContentView(android.view.View) */ public void setBehindContentView(View v) { setBehindContentView(v, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#setBehindContentView(android.view.View, android.view.ViewGroup.LayoutParams) */ public void setBehindContentView(View v, LayoutParams params) { mHelper.setBehindContentView(v, params); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#getSlidingMenu() */ public SlidingMenu getSlidingMenu() { return mHelper.getSlidingMenu(); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#toggle() */ public void toggle() { mHelper.toggle(); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#showAbove() */ public void showContent() { mHelper.showContent(); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#showBehind() */ public void showMenu() { mHelper.showMenu(); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#showSecondaryMenu() */ public void showSecondaryMenu() { mHelper.showSecondaryMenu(); } /* (non-Javadoc) * @see com.slidingmenu.lib.app.SlidingActivityBase#setSlidingActionBarEnabled(boolean) */ public void setSlidingActionBarEnabled(boolean b) { mHelper.setSlidingActionBarEnabled(b); } /* (non-Javadoc) * @see android.app.Activity#onKeyUp(int, android.view.KeyEvent) */ @Override public boolean onKeyUp(int keyCode, KeyEvent event) { boolean b = mHelper.onKeyUp(keyCode, event); if (b) return b; return super.onKeyUp(keyCode, event); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/slidingmenu/lib/app/SystemBarTintManager.java ================================================ /* * Copyright (C) 2013 readyState Software Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.slidingmenu.lib.app; import java.lang.reflect.Field; import java.lang.reflect.Method; import android.annotation.SuppressLint; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.os.Build; import android.util.DisplayMetrics; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.FrameLayout.LayoutParams; /** * Class to manage status and navigation bar tint effects when using KitKat * translucent system UI modes. * */ public class SystemBarTintManager { /** * The default system bar tint color value. */ public static final int DEFAULT_TINT_COLOR = 0x99000000; private final SystemBarConfig mConfig; private boolean mStatusBarAvailable; private boolean mNavBarAvailable; private boolean mStatusBarTintEnabled; private boolean mNavBarTintEnabled; private View mStatusBarTintView; private View mNavBarTintView; private static boolean sIsMiuiV6; static { try { Class sysClass = Class.forName("android.os.SystemProperties"); Method getStringMethod = sysClass.getDeclaredMethod("get", String.class); sIsMiuiV6 = "V6".equals((String) getStringMethod.invoke(sysClass, "ro.miui.ui.version.name")); } catch (Exception e) { e.printStackTrace(); } } /** * Constructor. Call this in the host activity onCreate method after its * content view has been set. You should always create new instances when * the host activity is recreated. * * @param activity The host activity. */ @TargetApi(19) public SystemBarTintManager(Activity activity) { Window win = activity.getWindow(); ViewGroup decorViewGroup = (ViewGroup) win.getDecorView(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // check theme attrs int[] attrs = {android.R.attr.windowTranslucentStatus, android.R.attr.windowTranslucentNavigation}; TypedArray a = activity.obtainStyledAttributes(attrs); try { mStatusBarAvailable = a.getBoolean(0, false); mNavBarAvailable = a.getBoolean(1, false); } finally { a.recycle(); } // check window flags WindowManager.LayoutParams winParams = win.getAttributes(); int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; if ((winParams.flags & bits) != 0) { mStatusBarAvailable = true; } bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION; if ((winParams.flags & bits) != 0) { mNavBarAvailable = true; } } mConfig = new SystemBarConfig(activity, mStatusBarAvailable, mNavBarAvailable); // device might not have virtual navigation keys if (!mConfig.hasNavigtionBar()) { mNavBarAvailable = false; } if (mStatusBarAvailable) { setupStatusBarView(activity, decorViewGroup); } if (mNavBarAvailable) { setupNavBarView(activity, decorViewGroup); } } /** * Enable tinting of the system status bar. * * If the platform is running Jelly Bean or earlier, or translucent system * UI modes have not been enabled in either the theme or via window flags, * then this method does nothing. * * @param enabled True to enable tinting, false to disable it (default). */ public void setStatusBarTintEnabled(boolean enabled) { mStatusBarTintEnabled = enabled; if (mStatusBarAvailable) { mStatusBarTintView.setVisibility(enabled ? View.VISIBLE : View.GONE); } } /** * set status bar darkmode * @param darkmode * @param activity */ public void setStatusBarDarkMode(boolean darkmode, Activity activity) { if (sIsMiuiV6) { Class clazz = activity.getWindow().getClass(); try { int darkModeFlag = 0; Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams"); Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE"); darkModeFlag = field.getInt(layoutParams); Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class); extraFlagField.invoke(activity.getWindow(), darkmode ? darkModeFlag : 0, darkModeFlag); } catch (Exception e) { e.printStackTrace(); } } } /** * Enable tinting of the system navigation bar. * * If the platform does not have soft navigation keys, is running Jelly Bean * or earlier, or translucent system UI modes have not been enabled in either * the theme or via window flags, then this method does nothing. * * @param enabled True to enable tinting, false to disable it (default). */ public void setNavigationBarTintEnabled(boolean enabled) { mNavBarTintEnabled = enabled; if (mNavBarAvailable) { mNavBarTintView.setVisibility(enabled ? View.VISIBLE : View.GONE); } } /** * Apply the specified color tint to all system UI bars. * * @param color The color of the background tint. */ public void setTintColor(int color) { setStatusBarTintColor(color); setNavigationBarTintColor(color); } /** * Apply the specified drawable or color resource to all system UI bars. * * @param res The identifier of the resource. */ public void setTintResource(int res) { setStatusBarTintResource(res); setNavigationBarTintResource(res); } /** * Apply the specified drawable to all system UI bars. * * @param drawable The drawable to use as the background, or null to remove it. */ public void setTintDrawable(Drawable drawable) { setStatusBarTintDrawable(drawable); setNavigationBarTintDrawable(drawable); } /** * Apply the specified alpha to all system UI bars. * * @param alpha The alpha to use */ public void setTintAlpha(float alpha) { setStatusBarAlpha(alpha); setNavigationBarAlpha(alpha); } /** * Apply the specified color tint to the system status bar. * * @param color The color of the background tint. */ public void setStatusBarTintColor(int color) { if (mStatusBarAvailable) { mStatusBarTintView.setBackgroundColor(color); } } /** * Apply the specified drawable or color resource to the system status bar. * * @param res The identifier of the resource. */ public void setStatusBarTintResource(int res) { if (mStatusBarAvailable) { mStatusBarTintView.setBackgroundResource(res); } } /** * Apply the specified drawable to the system status bar. * * @param drawable The drawable to use as the background, or null to remove it. */ @SuppressWarnings("deprecation") public void setStatusBarTintDrawable(Drawable drawable) { if (mStatusBarAvailable) { mStatusBarTintView.setBackgroundDrawable(drawable); } } /** * Apply the specified alpha to the system status bar. * * @param alpha The alpha to use */ @TargetApi(11) public void setStatusBarAlpha(float alpha) { if (mStatusBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mStatusBarTintView.setAlpha(alpha); } } /** * Apply the specified color tint to the system navigation bar. * * @param color The color of the background tint. */ public void setNavigationBarTintColor(int color) { if (mNavBarAvailable) { mNavBarTintView.setBackgroundColor(color); } } /** * Apply the specified drawable or color resource to the system navigation bar. * * @param res The identifier of the resource. */ public void setNavigationBarTintResource(int res) { if (mNavBarAvailable) { mNavBarTintView.setBackgroundResource(res); } } /** * Apply the specified drawable to the system navigation bar. * * @param drawable The drawable to use as the background, or null to remove it. */ @SuppressWarnings("deprecation") public void setNavigationBarTintDrawable(Drawable drawable) { if (mNavBarAvailable) { mNavBarTintView.setBackgroundDrawable(drawable); } } /** * Apply the specified alpha to the system navigation bar. * * @param alpha The alpha to use */ @TargetApi(11) public void setNavigationBarAlpha(float alpha) { if (mNavBarAvailable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { mNavBarTintView.setAlpha(alpha); } } /** * Get the system bar configuration. * * @return The system bar configuration for the current device configuration. */ public SystemBarConfig getConfig() { return mConfig; } /** * Is tinting enabled for the system status bar? * * @return True if enabled, False otherwise. */ public boolean isStatusBarTintEnabled() { return mStatusBarTintEnabled; } /** * Is tinting enabled for the system navigation bar? * * @return True if enabled, False otherwise. */ public boolean isNavBarTintEnabled() { return mNavBarTintEnabled; } private void setupStatusBarView(Context context, ViewGroup decorViewGroup) { mStatusBarTintView = new View(context); LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, mConfig.getStatusBarHeight()); params.gravity = Gravity.TOP; if (mNavBarAvailable && !mConfig.isNavigationAtBottom()) { params.rightMargin = mConfig.getNavigationBarWidth(); } mStatusBarTintView.setLayoutParams(params); mStatusBarTintView.setBackgroundColor(DEFAULT_TINT_COLOR); mStatusBarTintView.setVisibility(View.GONE); decorViewGroup.addView(mStatusBarTintView); } private void setupNavBarView(Context context, ViewGroup decorViewGroup) { mNavBarTintView = new View(context); LayoutParams params; if (mConfig.isNavigationAtBottom()) { params = new LayoutParams(LayoutParams.MATCH_PARENT, mConfig.getNavigationBarHeight()); params.gravity = Gravity.BOTTOM; } else { params = new LayoutParams(mConfig.getNavigationBarWidth(), LayoutParams.MATCH_PARENT); params.gravity = Gravity.RIGHT; } mNavBarTintView.setLayoutParams(params); mNavBarTintView.setBackgroundColor(DEFAULT_TINT_COLOR); mNavBarTintView.setVisibility(View.GONE); decorViewGroup.addView(mNavBarTintView); } /** * Class which describes system bar sizing and other characteristics for the current * device configuration. * */ public static class SystemBarConfig { private static final String STATUS_BAR_HEIGHT_RES_NAME = "status_bar_height"; private static final String NAV_BAR_HEIGHT_RES_NAME = "navigation_bar_height"; private static final String NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME = "navigation_bar_height_landscape"; private static final String NAV_BAR_WIDTH_RES_NAME = "navigation_bar_width"; private final boolean mTranslucentStatusBar; private final boolean mTranslucentNavBar; private final int mStatusBarHeight; private final int mActionBarHeight; private final boolean mHasNavigationBar; private final int mNavigationBarHeight; private final int mNavigationBarWidth; private final boolean mInPortrait; private final float mSmallestWidthDp; private SystemBarConfig(Activity activity, boolean translucentStatusBar, boolean traslucentNavBar) { Resources res = activity.getResources(); mInPortrait = (res.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT); mSmallestWidthDp = getSmallestWidthDp(activity); mStatusBarHeight = getInternalDimensionSize(res, STATUS_BAR_HEIGHT_RES_NAME); mActionBarHeight = getActionBarHeight(activity); mNavigationBarHeight = getNavigationBarHeight(activity); mNavigationBarWidth = getNavigationBarWidth(activity); mHasNavigationBar = (mNavigationBarHeight > 0); mTranslucentStatusBar = translucentStatusBar; mTranslucentNavBar = traslucentNavBar; } @TargetApi(14) private int getActionBarHeight(Context context) { int result = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { TypedValue tv = new TypedValue(); context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true); result = context.getResources().getDimensionPixelSize(tv.resourceId); } return result; } @TargetApi(14) private int getNavigationBarHeight(Context context) { Resources res = context.getResources(); int result = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { if (!ViewConfiguration.get(context).hasPermanentMenuKey()) { String key; if (mInPortrait) { key = NAV_BAR_HEIGHT_RES_NAME; } else { key = NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME; } return getInternalDimensionSize(res, key); } } return result; } @TargetApi(14) private int getNavigationBarWidth(Context context) { Resources res = context.getResources(); int result = 0; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { if (!ViewConfiguration.get(context).hasPermanentMenuKey()) { return getInternalDimensionSize(res, NAV_BAR_WIDTH_RES_NAME); } } return result; } private int getInternalDimensionSize(Resources res, String key) { int result = 0; int resourceId = res.getIdentifier(key, "dimen", "android"); if (resourceId > 0) { result = res.getDimensionPixelSize(resourceId); } return result; } @SuppressLint("NewApi") private float getSmallestWidthDp(Activity activity) { DisplayMetrics metrics = new DisplayMetrics(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { activity.getWindowManager().getDefaultDisplay().getRealMetrics(metrics); } else { // TODO this is not correct, but we don't really care pre-kitkat activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); } float widthDp = metrics.widthPixels / metrics.density; float heightDp = metrics.heightPixels / metrics.density; return Math.min(widthDp, heightDp); } /** * Should a navigation bar appear at the bottom of the screen in the current * device configuration? A navigation bar may appear on the right side of * the screen in certain configurations. * * @return True if navigation should appear at the bottom of the screen, False otherwise. */ public boolean isNavigationAtBottom() { return (mSmallestWidthDp >= 600 || mInPortrait); } /** * Get the height of the system status bar. * * @return The height of the status bar (in pixels). */ public int getStatusBarHeight() { return mStatusBarHeight; } /** * Get the height of the action bar. * * @return The height of the action bar (in pixels). */ public int getActionBarHeight() { return mActionBarHeight; } /** * Does this device have a system navigation bar? * * @return True if this device uses soft key navigation, False otherwise. */ public boolean hasNavigtionBar() { return mHasNavigationBar; } /** * Get the height of the system navigation bar. * * @return The height of the navigation bar (in pixels). If the device does not have * soft navigation keys, this will always return 0. */ public int getNavigationBarHeight() { return mNavigationBarHeight; } /** * Get the width of the system navigation bar when it is placed vertically on the screen. * * @return The width of the navigation bar (in pixels). If the device does not have * soft navigation keys, this will always return 0. */ public int getNavigationBarWidth() { return mNavigationBarWidth; } /** * Get the layout inset for any system UI that appears at the top of the screen. * * @param withActionBar True to include the height of the action bar, False otherwise. * @return The layout inset (in pixels). */ public int getPixelInsetTop(boolean withActionBar) { return (mTranslucentStatusBar ? mStatusBarHeight : 0) + (withActionBar ? mActionBarHeight : 0); } /** * Get the layout inset for any system UI that appears at the bottom of the screen. * * @return The layout inset (in pixels). */ public int getPixelInsetBottom() { if (mTranslucentNavBar && isNavigationAtBottom()) { return mNavigationBarHeight; } else { return 0; } } /** * Get the layout inset for any system UI that appears at the right of the screen. * * @return The layout inset (in pixels). */ public int getPixelInsetRight() { if (mTranslucentNavBar && !isNavigationAtBottom()) { return mNavigationBarWidth; } else { return 0; } } } } ================================================ FILE: MoneyCharge/app/src/main/java/com/umeng/fb/example/AppApplication.java ================================================ package com.umeng.fb.example; import android.app.Application; import com.umeng.fb.push.FeedbackPush; /** * Created by user on 2014/10/13. */ public class AppApplication extends Application { @Override public void onCreate() { FeedbackPush.getInstance(this).init(false); // AppPush.getInstance(this).init(); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/umeng/fb/example/AppPush.java ================================================ package com.umeng.fb.example; import android.content.Context; import com.umeng.fb.push.FBMessage; import com.umeng.fb.push.FeedbackPush; import com.umeng.message.PushAgent; import com.umeng.message.UmengMessageHandler; import com.umeng.message.entity.UMessage; public class AppPush { public UmengMessageHandler mMessageHandler; private static AppPush mAppPush; private Context context; public static AppPush getInstance(Context context) { if (mAppPush == null) mAppPush = new AppPush(context); return mAppPush; } public AppPush(Context context) { this.context = context; } public void init() { mMessageHandler = new UmengMessageHandler() { @Override public void dealWithCustomMessage(Context context, UMessage msg) { if (FeedbackPush.getInstance(context).dealFBMessage(new FBMessage(msg.custom))) { //The push message is reply from developer. return; } //The push message is not reply from developer. /*************** other code ***************/ } }; PushAgent.getInstance(context).setMessageHandler(mMessageHandler); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/umeng/fb/example/CustomActivity.java ================================================ package com.umeng.fb.example; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import com.cwp.chart.SystemBarTintManager; import com.cwp.cmoneycharge.R; import com.cwp.cmoneycharge.SysApplication; import com.umeng.fb.FeedbackAgent; import com.umeng.fb.SyncListener; import com.umeng.fb.model.Conversation; import com.umeng.fb.model.Reply; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; public class CustomActivity extends Activity { private ListView mListView; private FeedbackAgent mAgent; private Conversation mComversation; private Context mContext; private ReplyAdapter adapter; private Button sendBtn; private EditText inputEdit; private SwipeRefreshLayout mSwipeRefreshLayout; private final int VIEW_TYPE_COUNT = 2; private final int VIEW_TYPE_USER = 0; private final int VIEW_TYPE_DEV = 1; private final String TAG = CustomActivity.class.getName(); String firstfb = "true"; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { adapter.notifyDataSetChanged(); } }; private ImageView example_left2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_custom); SysApplication.getInstance().addActivity(this); // 在销毁队列中添加this if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { setTranslucentStatus(true); findViewById(R.id.fb_top).setVisibility(View.VISIBLE); } SystemBarTintManager mTintManager = new SystemBarTintManager(this); mTintManager.setStatusBarTintEnabled(true); mTintManager.setStatusBarTintResource(R.color.statusbar_bg); mContext = this; SharedPreferences sp = this.getSharedPreferences("preferences", MODE_WORLD_READABLE); Editor edit = sp.edit(); initView(); Intent intentr = getIntent(); Bundle bundle = intentr.getExtras();// 获取传入的数据,并使用Bundle记录 if (bundle != null) { if (bundle.containsKey("cwp.md")) { String error = (String) bundle.getString("cwp.md");// 获取Bundle中记录的信息 inputEdit.setText(error); } } mAgent = new FeedbackAgent(this); mComversation = new FeedbackAgent(this).getDefaultConversation(); if (!firstfb.equals(sp.getString("firstfb", ""))) { mComversation.addUserReply("您好,欢迎使用快速记,请反馈使用产品的感受和建议"); edit.putString("firstfb", "true"); // 一天只检查一次 edit.commit(); } adapter = new ReplyAdapter(); mListView.setAdapter(adapter); sync(); } @TargetApi(19) private void setTranslucentStatus(boolean on) { Window win = getWindow(); WindowManager.LayoutParams winParams = win.getAttributes(); final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS; if (on) { winParams.flags |= bits; } else { winParams.flags &= ~bits; } win.setAttributes(winParams); } private void initView() { mListView = (ListView) findViewById(R.id.fb_reply_list); sendBtn = (Button) findViewById(R.id.fb_send_btn); inputEdit = (EditText) findViewById(R.id.fb_send_content); example_left2 = (ImageView) findViewById(R.id.example_left2); // 下拉刷新组件 mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.fb_reply_refresh); example_left2.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); sendBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { String content = inputEdit.getText().toString(); inputEdit.getEditableText().clear(); if (!TextUtils.isEmpty(content)) { // 将内容添加到会话列表 mComversation.addUserReply(content); // 刷新新ListView mHandler.sendMessage(new Message()); // 数据同步 sync(); } } }); // 下拉刷新 mSwipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() { @Override public void onRefresh() { sync(); } }); } // 数据同步 private void sync() { mComversation.sync(new SyncListener() { @Override public void onSendUserReply(List replyList) { } @Override public void onReceiveDevReply(List replyList) { // SwipeRefreshLayout停止刷新 mSwipeRefreshLayout.setRefreshing(false); // 发送消息,刷新ListView mHandler.sendMessage(new Message()); // 如果开发者没有新的回复数据,则返回 if (replyList == null || replyList.size() < 1) { return; } } }); // 更新adapter,刷新ListView adapter.notifyDataSetChanged(); } // adapter class ReplyAdapter extends BaseAdapter { @Override public int getCount() { return mComversation.getReplyList().size(); } @Override public Object getItem(int arg0) { return mComversation.getReplyList().get(arg0); } @Override public long getItemId(int arg0) { return arg0; } @Override public int getViewTypeCount() { // 两种不同的Tiem布局 return VIEW_TYPE_COUNT; } @Override public int getItemViewType(int position) { // 获取单条回复 Reply reply = mComversation.getReplyList().get(position); if (Reply.TYPE_DEV_REPLY.equals(reply.type)) { // 开发者回复Item布局 return VIEW_TYPE_DEV; } else { // 用户反馈、回复Item布局 return VIEW_TYPE_USER; } } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; // 获取单条回复 Reply reply = mComversation.getReplyList().get(position); if (convertView == null) { // 根据Type的类型来加载不同的Item布局 if (Reply.TYPE_DEV_REPLY.equals(reply.type)) { // 开发者的回复 convertView = LayoutInflater.from(mContext).inflate( R.layout.custom_fb_user_reply, null); } else { // 用户的反馈、回复 convertView = LayoutInflater.from(mContext).inflate( R.layout.custom_fb_dev_reply, null); if (position == 0) { convertView = LayoutInflater.from(mContext).inflate( R.layout.custom_fb_user_reply, null); } } // 创建ViewHolder并获取各种View holder = new ViewHolder(); holder.replyContent = (TextView) convertView .findViewById(R.id.fb_reply_content); holder.replyProgressBar = (ProgressBar) convertView .findViewById(R.id.fb_reply_progressBar); holder.replyStateFailed = (ImageView) convertView .findViewById(R.id.fb_reply_state_failed); holder.replyData = (TextView) convertView .findViewById(R.id.fb_reply_date); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } // 以下是填充数据 // 设置Reply的内容 holder.replyContent.setText(reply.content); // 在App应用界面,对于开发者的Reply来讲status没有意义 if (!Reply.TYPE_DEV_REPLY.equals(reply.type)) { // 根据Reply的状态来设置replyStateFailed的状态 if (Reply.STATUS_NOT_SENT.equals(reply.status)) { holder.replyStateFailed.setVisibility(View.VISIBLE); } else { holder.replyStateFailed.setVisibility(View.GONE); } // 根据Reply的状态来设置replyProgressBar的状态 if (Reply.STATUS_SENDING.equals(reply.status)) { holder.replyProgressBar.setVisibility(View.VISIBLE); } else { holder.replyProgressBar.setVisibility(View.GONE); } } // 回复的时间数据,这里仿照QQ两条Reply之间相差100000ms则展示时间 if ((position + 1) < mComversation.getReplyList().size()) { Reply nextReply = mComversation.getReplyList() .get(position + 1); if (nextReply.created_at - reply.created_at > 100000) { Date replyTime = new Date(reply.created_at); SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); holder.replyData.setText(sdf.format(replyTime)); holder.replyData.setVisibility(View.VISIBLE); } } return convertView; } class ViewHolder { TextView replyContent; ProgressBar replyProgressBar; ImageView replyStateFailed; TextView replyData; } } } ================================================ FILE: MoneyCharge/app/src/main/java/com/umeng/fb/example/MyPushIntentService.java ================================================ package com.umeng.fb.example; import org.android.agoo.client.BaseConstants; import org.json.JSONObject; import android.content.Context; import android.content.Intent; import android.util.Log; import com.umeng.fb.ConversationActivity; import com.umeng.fb.push.FeedbackPush; import com.umeng.message.UmengBaseIntentService; import com.umeng.message.entity.UMessage; public class MyPushIntentService extends UmengBaseIntentService{ private static final String TAG = MyPushIntentService.class.getName(); @Override protected void onMessage(Context context, Intent intent) { super.onMessage(context, intent); FeedbackPush.getInstance(context).init(ConversationActivity.class,true); if(FeedbackPush.getInstance(context).onFBMessage(intent)){ //The push message is reply from developer. return; } //The push message is not reply from developer. /*************** other code ***************/ } } ================================================ FILE: MoneyCharge/app/src/main/java/com/zhy/view/HorizontalProgressBarWithNumber.java ================================================ package com.zhy.view; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.util.AttributeSet; import android.util.TypedValue; import android.widget.ProgressBar; import com.cwp.cmoneycharge.R; public class HorizontalProgressBarWithNumber extends ProgressBar { private static final int DEFAULT_TEXT_SIZE = 10; private static final int DEFAULT_TEXT_COLOR = 0XFFFC00D1; private static final int DEFAULT_COLOR_UNREACHED_COLOR = 0xFFd3d6da; private static final int DEFAULT_HEIGHT_REACHED_PROGRESS_BAR = 2; private static final int DEFAULT_HEIGHT_UNREACHED_PROGRESS_BAR = 2; private static final int DEFAULT_SIZE_TEXT_OFFSET = 10; /** * painter of all drawing things */ protected Paint mPaint = new Paint(); /** * color of progress number */ protected int mTextColor = DEFAULT_TEXT_COLOR; /** * size of text (sp) */ protected int mTextSize = sp2px(DEFAULT_TEXT_SIZE); /** * offset of draw progress */ protected int mTextOffset = dp2px(DEFAULT_SIZE_TEXT_OFFSET); /** * height of reached progress bar */ protected int mReachedProgressBarHeight = dp2px(DEFAULT_HEIGHT_REACHED_PROGRESS_BAR); /** * color of reached bar */ protected int mReachedBarColor = DEFAULT_TEXT_COLOR; /** * color of unreached bar */ protected int mUnReachedBarColor = DEFAULT_COLOR_UNREACHED_COLOR; /** * height of unreached progress bar */ protected int mUnReachedProgressBarHeight = dp2px(DEFAULT_HEIGHT_UNREACHED_PROGRESS_BAR); /** * view width except padding */ protected int mRealWidth; protected boolean mIfDrawText = true; protected static final int VISIBLE = 0; public HorizontalProgressBarWithNumber(Context context, AttributeSet attrs) { this(context, attrs, 0); } public HorizontalProgressBarWithNumber(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); obtainStyledAttributes(attrs); mPaint.setTextSize(mTextSize); mPaint.setColor(mTextColor); } @Override protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = MeasureSpec.getSize(widthMeasureSpec); int height = measureHeight(heightMeasureSpec); setMeasuredDimension(width, height); mRealWidth = getMeasuredWidth() - getPaddingRight() - getPaddingLeft(); } private int measureHeight(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { result = specSize; } else { float textHeight = (mPaint.descent() - mPaint.ascent()); result = (int) (getPaddingTop() + getPaddingBottom() + Math.max( Math.max(mReachedProgressBarHeight, mUnReachedProgressBarHeight), Math.abs(textHeight))); if (specMode == MeasureSpec.AT_MOST) { result = Math.min(result, specSize); } } return result; } /** * get the styled attributes * * @param attrs */ private void obtainStyledAttributes(AttributeSet attrs) { // init values from custom attributes final TypedArray attributes = getContext().obtainStyledAttributes( attrs, R.styleable.HorizontalProgressBarWithNumber); mTextColor = attributes .getColor( R.styleable.HorizontalProgressBarWithNumber_progress_text_color, DEFAULT_TEXT_COLOR); mTextSize = (int) attributes.getDimension( R.styleable.HorizontalProgressBarWithNumber_progress_text_size, mTextSize); mReachedBarColor = attributes .getColor( R.styleable.HorizontalProgressBarWithNumber_progress_reached_color, mTextColor); mUnReachedBarColor = attributes .getColor( R.styleable.HorizontalProgressBarWithNumber_progress_unreached_color, DEFAULT_COLOR_UNREACHED_COLOR); mReachedProgressBarHeight = (int) attributes .getDimension( R.styleable.HorizontalProgressBarWithNumber_progress_reached_bar_height, mReachedProgressBarHeight); mUnReachedProgressBarHeight = (int) attributes .getDimension( R.styleable.HorizontalProgressBarWithNumber_progress_unreached_bar_height, mUnReachedProgressBarHeight); mTextOffset = (int) attributes .getDimension( R.styleable.HorizontalProgressBarWithNumber_progress_text_offset, mTextOffset); int textVisible = attributes .getInt(R.styleable.HorizontalProgressBarWithNumber_progress_text_visibility, VISIBLE); if (textVisible != VISIBLE) { mIfDrawText = false; } attributes.recycle(); } @Override protected synchronized void onDraw(Canvas canvas) { canvas.save(); canvas.translate(getPaddingLeft(), getHeight() / 2); boolean noNeedBg = false; float radio = getProgress() * 1.0f / getMax(); float progressPosX = (int) (mRealWidth * radio); String text = getProgress() + "%"; // mPaint.getTextBounds(text, 0, text.length(), mTextBound); float textWidth = mPaint.measureText(text); float textHeight = (mPaint.descent() + mPaint.ascent()) / 2; if (progressPosX + textWidth > mRealWidth) { progressPosX = mRealWidth - textWidth; noNeedBg = true; } // draw reached bar float endX = progressPosX - mTextOffset / 2; if (endX > 0) { mPaint.setColor(mReachedBarColor); mPaint.setStrokeWidth(mReachedProgressBarHeight); canvas.drawLine(0, 0, endX, 0, mPaint); } // draw progress bar // measure text bound if (mIfDrawText) { mPaint.setColor(mTextColor); canvas.drawText(text, progressPosX, -textHeight, mPaint); } // draw unreached bar if (!noNeedBg) { float start = progressPosX + mTextOffset / 2 + textWidth; mPaint.setColor(mUnReachedBarColor); mPaint.setStrokeWidth(mUnReachedProgressBarHeight); canvas.drawLine(start, 0, mRealWidth, 0, mPaint); } canvas.restore(); } /** * dp 2 px * * @param dpVal */ protected int dp2px(int dpVal) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpVal, getResources().getDisplayMetrics()); } /** * sp 2 px * * @param spVal * @return */ protected int sp2px(int spVal) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spVal, getResources().getDisplayMetrics()); } } ================================================ FILE: MoneyCharge/app/src/main/java/com/zhy/view/RoundProgressBarWidthNumber.java ================================================ package com.zhy.view; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint.Cap; import android.graphics.Paint.Style; import android.graphics.RectF; import android.util.AttributeSet; import com.cwp.cmoneycharge.R; public class RoundProgressBarWidthNumber extends HorizontalProgressBarWithNumber { /** * mRadius of view */ private int mRadius = dp2px(30); private int mMaxPaintWidth; public RoundProgressBarWidthNumber(Context context) { this(context, null); } public RoundProgressBarWidthNumber(Context context, AttributeSet attrs) { super(context, attrs); mReachedProgressBarHeight = (int) (mUnReachedProgressBarHeight * 2.5f); TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.RoundProgressBarWidthNumber); mRadius = (int) ta.getDimension( R.styleable.RoundProgressBarWidthNumber_radius, mRadius); ta.recycle(); mPaint.setStyle(Style.STROKE); mPaint.setAntiAlias(true); mPaint.setDither(true); mPaint.setStrokeCap(Cap.ROUND); } /** * 这里默认在布局中padding值要么不设置,要么全部设置 */ @Override protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { mMaxPaintWidth = Math.max(mReachedProgressBarHeight, mUnReachedProgressBarHeight); int expect = mRadius * 2 + mMaxPaintWidth + getPaddingLeft() + getPaddingRight(); int width = resolveSize(expect, widthMeasureSpec); int height = resolveSize(expect, heightMeasureSpec); int realWidth = Math.min(width, height); mRadius = (realWidth - getPaddingLeft() - getPaddingRight() - mMaxPaintWidth) / 2; setMeasuredDimension(realWidth, realWidth); } @Override protected synchronized void onDraw(Canvas canvas) { String text = getProgress() + "%"; float textWidth = mPaint.measureText(text); float textHeight = (mPaint.descent() + mPaint.ascent()) / 2; canvas.save(); canvas.translate(getPaddingLeft() + mMaxPaintWidth / 2, getPaddingTop() + mMaxPaintWidth / 2); mPaint.setStyle(Style.STROKE); // draw unreaded bar mPaint.setColor(mUnReachedBarColor); mPaint.setStrokeWidth(mUnReachedProgressBarHeight); canvas.drawCircle(mRadius, mRadius, mRadius, mPaint); // draw reached bar mPaint.setColor(mReachedBarColor); mPaint.setStrokeWidth(mReachedProgressBarHeight); float sweepAngle = getProgress() * 1.0f / getMax() * 360; canvas.drawArc(new RectF(0, 0, mRadius * 2, mRadius * 2), 0, sweepAngle, false, mPaint); // draw text mPaint.setStyle(Style.FILL); canvas.drawText(text, mRadius - textWidth / 2, mRadius - textHeight, mPaint); canvas.restore(); } } ================================================ FILE: MoneyCharge/app/src/main/java/cwp/moneycharge/dao/AccountDAO.java ================================================ package cwp.moneycharge.dao; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import cwp.moneycharge.model.*; public class AccountDAO { private DBOpenHelper helper;// 创建DBOpenHelper对象 private SQLiteDatabase db;// 创建SQLiteDatabase对象 public AccountDAO(Context context)// 定义构造函数 { helper = new DBOpenHelper(context);// 初始化DBOpenHelper对象 } /** * 添加密码信息 * * @param tb_account */ public int add(Tb_account tb_account) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 // 执行添加密码操作 if (tb_account.get_id() == 0) { db.execSQL( "insert into tb_account (username,pwd) values (?,?)", new Object[] { tb_account.getUsername(),tb_account.getPwd() }); } else { db.execSQL( "insert into tb_account (_id,username,pwd) values (?,?,?)", new Object[] { tb_account.get_id(),tb_account.getUsername(), tb_account.getPwd() }); } Cursor cursor = db.rawQuery( "select _id from tb_account where username=? and pwd=?", new String[] { tb_account.getUsername(), tb_account.getPwd() }); if (cursor.moveToNext())// 遍历查找到的密码信息 { // 将密码存储到Tb_account类中 return cursor.getInt(cursor.getColumnIndex("_id")); } else return 100000001; } /** * 设置密码信息 * * @param tb_account */ public void update(int id, String username, String pwd) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 // 执行修改密码操作 db.execSQL("update tb_account set username=? , pwd = ? where _id=? ", new String[] { username, pwd, String.valueOf(id) }); } public void deleteById(int id) { db = helper.getWritableDatabase();// 创建SQLiteDatabase对象 // 执行删除便签信息操作 db.execSQL("delete from tb_account where _id =? ", new Object[] { id }); } /** * 查找密码信息 * * @return */ public Tb_account find(String username, String pwd) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 // 查找密码并存储到Cursor类中 Cursor cursor = db .rawQuery( "select _id, username, pwd from tb_account where pwd=? and username=? ", new String[] { pwd, username }); if (cursor.moveToNext())// 遍历查找到的密码信息 { // 将密码存储到Tb_account类中 return new Tb_account(cursor.getInt(cursor.getColumnIndex("_id")), cursor.getString(cursor.getColumnIndex("username")), cursor.getString(cursor.getColumnIndex("pwd"))); } return null;// 如果没有信息,则返回null } public String find(int id) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 // 查找密码并存储到Cursor类中 Cursor cursor = db.rawQuery( "select username from tb_account where _id=? ", new String[] { String.valueOf(id) }); if (cursor.moveToNext())// 遍历查找到的密码信息 { // 将密码存储到Tb_account类中 return cursor.getString(cursor.getColumnIndex("username")); } else return "无名氏";// 如果没有信息,则返回null } public long getCount() { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery("select count(_id) from tb_account ", null);// 获取密码信息的记录数 if (cursor.moveToNext())// 判断Cursor中是否有数据 { return cursor.getLong(0);// 返回总记录数 } return 0;// 如果没有数据,则返回0 } } ================================================ FILE: MoneyCharge/app/src/main/java/cwp/moneycharge/dao/DBOpenHelper.java ================================================ package cwp.moneycharge.dao; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DBOpenHelper extends SQLiteOpenHelper { private static final int VERSION=2; //已经做出更新 private static final String DBNAME="cmoneycharge.db"; public DBOpenHelper(Context context){ super(context,DBNAME,null,VERSION); } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub //用户表 db.execSQL("create table tb_account (_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,username varchar(20) ,pwd VARCHAR(50) DEFAULT '000000' NOT NULL)"); //支出类型表 db.execSQL("create table tb_ptype(_id INTEGER NOT NULL ,no integer not null,typename varchar(50) )"); //收入类型表 db.execSQL("create table tb_itype(_id INTEGER NOT NULL,no integer not null ,typename varchar(50) )"); // 支出信息表 db.execSQL("create table tb_pay (_id INTEGER NOT NULL,no INTEGER NOT NULL ,money decimal,time varchar(10)," + "type integer,address varchar(100),mark varchar(200),photo varchar(200),kind varchar(10))"); // 收入信息表 db.execSQL("create table tb_income (_id INTEGER NOT NULL,no INTEGER NOT NULL ,money decimal,time varchar(10)," + "type integer ,handler varchar(100),mark varchar(200),photo varchar(200),kind varchar(10))"); // 便签信息表 db.execSQL("create table tb_note (_id integer ,no integer ,note varchar(200))"); db.execSQL("insert into tb_account(_id,username,pwd) values(100000001,\"默认用户\",\"000000\")"); //初始化数据 收入类型表格 db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"1","工资"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"2","还款"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"3","股票"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"4","还款"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"5","基金"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"6","分红"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"7","利息"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"8","兼职"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"9","奖金"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"10","租金"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"11","销售款"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"12","应收款"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"13","报销款"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"14","其他"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"15","礼金"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"16","语音识别"}); //初始化数据 支出类型表格 db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"1","早餐"}); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"2","午餐"}); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"3","晚餐"}); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"4","夜宵"}); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"5","生活用品"}); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"6","工作用品"}); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"7","衣服"}); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"8","应酬"}); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"9","电子产品"}); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"10","食品"}); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"11","租金"}); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"12","股票"}); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"13","打的"}); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"14","基金"}); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"15","其他"}); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(100000001),"16","语音识别"}); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if(oldVersion < 2) { //更新数据库 db.execSQL("ALTER TABLE tb_income ADD photo varchar(200)"); db.execSQL("ALTER TABLE tb_pay ADD photo varchar(200)"); } } public void droptable(SQLiteDatabase db){ db.execSQL("drop table tb_itype"); db.execSQL("drop table tb_ptype"); db.execSQL("drop table tb_account"); db.execSQL("drop table tb_income"); db.execSQL("drop table tb_pay"); db.execSQL("drop table tb_note"); } } ================================================ FILE: MoneyCharge/app/src/main/java/cwp/moneycharge/dao/IncomeDAO.java ================================================ /** * */ package cwp.moneycharge.dao; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import cwp.moneycharge.model.*; import android.annotation.SuppressLint; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import android.widget.Toast; /** * @author cwpcc * */ public class IncomeDAO { private DBOpenHelper helper;// 创建DBOpenHelper对象 private SQLiteDatabase db;// 创建SQLiteDatabase对象 private int no = 1;// 编号 private int userid = 100000001; public IncomeDAO(Context context) { // TODO Auto-generated constructor stub helper = new DBOpenHelper(context);// 初始化DBOpenHelper对象 } /** * 添加收入信息 * * @param tb_income */ public void add(Tb_income tb_income) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 // 执行添加收入信息操作 db.execSQL( "insert into tb_income (_id,no,money,time,type,handler,mark,photo,kind) values (?,?,?,?,?,?,?,?,?)", new Object[] { tb_income.get_id(), tb_income.getNo(), tb_income.getMoney(), tb_income.getTime(), tb_income.getType(), tb_income.getHandler(), tb_income.getMark(), tb_income.getPhoto(), "收入" }); } /** * 更新收入信息 * * @param Tb_income */ public void update(Tb_income tb_income) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 // 执行修改收入信息操作 db.execSQL( "update Tb_income set money = ?,time = ?,type = ?,handler = ?,mark = ?,photo = ? where _id = ? and no=?", new Object[] { tb_income.getMoney(), tb_income.getTime(), tb_income.getType(), tb_income.getHandler(), tb_income.getMark(), tb_income.getPhoto(), tb_income.get_id(), tb_income.getNo() }); } /** * 查找收入信息 * * @param id * ,no * @return */ public Tb_income find(int id, int no) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db .rawQuery( "select _id, no, money,time,type,handler,mark,photo,kind from Tb_income where _id = ? and no=?", new String[] { String.valueOf(id), String.valueOf(no) });// 根据用户和编号查找收入信息,并存储到Cursor类中 if (cursor.moveToFirst())// 遍历查找到的收入信息 { // 将遍历到的收入信息存储到Tb_income类中 return new Tb_income(cursor.getInt(cursor.getColumnIndex("_id")), cursor.getInt(cursor.getColumnIndex("no")), cursor.getDouble(cursor.getColumnIndex("money")), cursor.getString(cursor.getColumnIndex("time")), cursor.getInt(cursor.getColumnIndex("type")), cursor.getString(cursor.getColumnIndex("handler")), cursor.getString(cursor.getColumnIndex("mark")), cursor.getString(cursor.getColumnIndex("photo")), "收入"); } return null;// 如果没有信息,则返回null } /** * 刪除收入信息 * * @param ids */ public void detele(Integer... ids) { if (ids.length > 0)// 判断是否存在要删除的id { StringBuffer sb = new StringBuffer();// 创建StringBuffer对象 for (int i = 0; i < ids.length - 1; i++)// 遍历要删除的id集合 { sb.append('?').append(',');// 将删除条件添加到StringBuffer对象中 } sb.deleteCharAt(sb.length() - 1);// 去掉最后一个“,“字符 db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 // 执行删除收入信息操作 db.execSQL("delete from Tb_income where _id in (?) and no in (" + sb + ")", (Object[]) ids); } } /** * 获取收入信息 * * @param start * 起始位置 * @param count * 每页显示数量 * @return */ public List getScrollData(int id, int start, int count) { List tb_income = new ArrayList();// 创建集合对象 db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 // 获取所有收入信息 Cursor cursor = db.rawQuery( "select * from Tb_income where _id=? order by no limit ?,?", new String[] { String.valueOf(id), String.valueOf(start), String.valueOf(count) }); while (cursor.moveToNext())// 遍历所有的收入信息 { // 将遍历到的收入信息添加到集合中 tb_income.add(new Tb_income(cursor.getInt(cursor .getColumnIndex("_id")), cursor.getInt(cursor .getColumnIndex("no")), cursor.getDouble(cursor .getColumnIndex("money")), cursor.getString(cursor .getColumnIndex("time")), cursor.getInt(cursor .getColumnIndex("type")), cursor.getString(cursor .getColumnIndex("handler")), cursor.getString(cursor .getColumnIndex("mark")), cursor.getString(cursor .getColumnIndex("photo")), null)); } return tb_income;// 返回集合 } public List getScrollData(int id, int start, int count, String date1, String date2) { List tb_income = new ArrayList();// 创建集合对象 db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 // 获取所有收入信息 Cursor cursor = db .rawQuery( "select * from Tb_income where _id=? and time >= ? and time <= ? order by time DESC", new String[] { String.valueOf(id), date1, date2 }); while (cursor.moveToNext())// 遍历所有的收入信息 { // 将遍历到的收入信息添加到集合中 tb_income.add(new Tb_income(cursor.getInt(cursor .getColumnIndex("_id")), cursor.getInt(cursor .getColumnIndex("no")), cursor.getDouble(cursor .getColumnIndex("money")), cursor.getString(cursor .getColumnIndex("time")), cursor.getInt(cursor .getColumnIndex("type")), cursor.getString(cursor .getColumnIndex("handler")), cursor.getString(cursor .getColumnIndex("mark")), cursor.getString(cursor .getColumnIndex("photo")), null)); } return tb_income;// 返回集合 } public List getScrollDataTotal(int id, int start, int count, String date1, String date2) { List tb_income = new ArrayList();// 创建集合对象 db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 // 获取所有收入信息 Cursor cursor = db .rawQuery( "select * from Tb_income where _id=? and time >= ? and time <= ? UNION select * from Tb_pay where _id=? and time >= ? and time <= ? order by time DESC", new String[] { String.valueOf(id), date1, date2, String.valueOf(id), date1, date2 }); while (cursor.moveToNext())// 遍历所有的收入信息 { // 将遍历到的收入信息添加到集合中 tb_income.add(new Tb_income(cursor.getInt(cursor .getColumnIndex("_id")), cursor.getInt(cursor .getColumnIndex("no")), cursor.getDouble(cursor .getColumnIndex("money")), cursor.getString(cursor .getColumnIndex("time")), cursor.getInt(cursor .getColumnIndex("type")), cursor.getString(cursor .getColumnIndex("handler")), cursor.getString(cursor .getColumnIndex("mark")), cursor.getString(cursor .getColumnIndex("photo")), cursor.getString(cursor .getColumnIndex("kind")))); } return tb_income;// 返回集合 } public List search(int id, String string) { List tb_income = new ArrayList();// 创建集合对象 db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 // 获取所有收入信息 Cursor cursor = db .rawQuery( "select * from Tb_income where _id=? and money like ? union " + "select * from Tb_income where _id=? and time like ? union " + "select * from Tb_income where _id=? and handler like ? union " + "select * from Tb_income where _id=? and mark like ? union " + "select * from Tb_income where _id=? and kind like ? union " + "select Tb_income.* from Tb_income,tb_itype where Tb_income._id=? and Tb_income.type=tb_itype.no and tb_itype.typename like ? union " + "select tb_pay.* from tb_pay,tb_ptype where tb_pay._id=? and tb_pay.type=tb_ptype.no and tb_ptype.typename like ? union " + "select * from tb_pay where _id=? and money like ? union " + "select * from tb_pay where _id=? and time like ? union " + "select * from tb_pay where _id=? and address like ? union " + "select * from tb_pay where _id=? and mark like ? union " + "select * from tb_pay where _id=? and kind like ? " + "order by time DESC ", new String[] { String.valueOf(id), "%" + string + "%", String.valueOf(id), "%" + string + "%", String.valueOf(id), "%" + string + "%", String.valueOf(id), "%" + string + "%", String.valueOf(id), "%" + string + "%", String.valueOf(id), "%" + string + "%", String.valueOf(id), "%" + string + "%", String.valueOf(id), "%" + string + "%", String.valueOf(id), "%" + string + "%", String.valueOf(id), "%" + string + "%", String.valueOf(id), "%" + string + "%", String.valueOf(id), "%" + string + "%", }); while (cursor.moveToNext())// 遍历所有的收入信息 { // 将遍历到的收入信息添加到集合中 tb_income.add(new Tb_income(cursor.getInt(cursor .getColumnIndex("_id")), cursor.getInt(cursor .getColumnIndex("no")), cursor.getDouble(cursor .getColumnIndex("money")), cursor.getString(cursor .getColumnIndex("time")), cursor.getInt(cursor .getColumnIndex("type")), cursor.getString(cursor .getColumnIndex("handler")), cursor.getString(cursor .getColumnIndex("mark")), cursor.getString(cursor .getColumnIndex("photo")), cursor.getString(cursor .getColumnIndex("kind")))); } return tb_income;// 返回集合 } /* * 高级搜索 */ public List searchALL(int id, String date1, String date2, String[] sp, String[] sin, String string) { List tb_income = new ArrayList();// 创建集合对象 db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 String[] paytype = { "money", "address", "mark" }; String[] incometype = { "money", "handler", "mark" }; // 获取所有收入信息 StringBuffer sql = new StringBuffer();// 拼接sql for (int i = 0; i < sin.length; i++) { for (int j = 0; j < 3; j++) { sql.append("select Tb_income.* from Tb_income,tb_itype where Tb_income._id=" + "'" + String.valueOf(id) + "'" + " and time >= " + "'" + date1 + "'" + " and time <= " + "'" + date2 + "'" + " and Tb_income.type=tb_itype.no and tb_itype.typename=" + "'" + sin[i] + "'" + " and Tb_income." + incometype[j] + " like " + "'%" + string + "%'" + " union "); } } for (int i = 0; i < sp.length; i++) { for (int j = 0; j < 3; j++) { sql.append("select tb_pay.* from tb_pay,tb_ptype where tb_pay._id=" + "'" + String.valueOf(id) + "'" + " and time >= " + "'" + date1 + "'" + " and time <= " + "'" + date2 + "'" + " and tb_pay.type=tb_ptype.no and tb_ptype.typename=" + "'" + sp[i] + "'" + " and tb_pay." + paytype[j] + " like " + "'%" + string + "%'" + " union "); } } sql.delete(sql.length() - 6, sql.length()); // 删除最后一个uniom sql.append("order by time DESC"); // System.out.println("sql" + sql); Cursor cursor = db.rawQuery(sql.toString(), null); while (cursor.moveToNext())// 遍历所有的收入信息 { // 将遍历到的收入信息添加到集合中 tb_income.add(new Tb_income(cursor.getInt(cursor .getColumnIndex("_id")), cursor.getInt(cursor .getColumnIndex("no")), cursor.getDouble(cursor .getColumnIndex("money")), cursor.getString(cursor .getColumnIndex("time")), cursor.getInt(cursor .getColumnIndex("type")), cursor.getString(cursor .getColumnIndex("handler")), cursor.getString(cursor .getColumnIndex("mark")), cursor.getString(cursor .getColumnIndex("photo")), cursor.getString(cursor .getColumnIndex("kind")))); } return tb_income;// 返回集合 } /** * 获取总记录数 * * @return */ public long getCount() { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery("select count(no) from tb_income", null);// 获取收入信息的记录数 if (cursor.moveToNext())// 判断Cursor中是否有数据 { return cursor.getLong(0);// 返回总记录数 } return 0;// 如果没有数据,则返回0 } public long getCount(int id) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery( "select count(no) from tb_income where _id=?", new String[] { String.valueOf(id) });// 获取收入信息的记录数 if (cursor.moveToNext())// 判断Cursor中是否有数据 { return cursor.getLong(0);// 返回总记录数 } return 0;// 如果没有数据,则返回0 } /** * 获取收入最大编号 * * @return */ public int getMaxNo(int id) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery( "select max(no) from tb_income where _id=?", new String[] { String.valueOf(id) });// 获取收入信息表中的最大编号 while (cursor.moveToLast()) {// 访问Cursor中的最后一条数据 return cursor.getInt(0);// 获取访问到的数据,即最大编号 } return 0;// 如果没有数据,则返回0 } @SuppressLint("SimpleDateFormat") public String addDays(String sdate, int days) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(); try { date = (Date) sdf.parse(sdate); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DATE, days); // minus number would decrement the days date = cal.getTime(); String result = sdf.format(date); return result; } public Double getamountData(int userid2) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Double data = 0.0; Cursor cursor = db.rawQuery( "select sum(money) from tb_income where _id=?", new String[] { String.valueOf(userid) }); // 获取支出信息表中的最大编号 while (cursor.moveToNext())// 遍历所有的支出信息 { // 将遍历到的支出信息添加到集合中 data = cursor.getDouble(0); } cursor.close(); return data; } public Datapicker getDataOnDay(String date1, String date2) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Double data = 0.0; Datapicker datapicker; Cursor cursor = db .rawQuery( "select total(money) as tmoney from tb_income where time >= ? and time <= ? and _id =?", new String[] { date1, date2, String.valueOf(userid) });// 获取支出信息表中的最大编号 while (cursor.moveToNext())// 遍历所有的支出信息 { // 将遍历到的支出信息添加到集合中 data = data + cursor.getDouble(cursor.getColumnIndex("tmoney")); } cursor.close(); datapicker = new Datapicker(no, data, date1); no++; return datapicker;// 返回集合 // 将遍历到的支出信息添加到集合中 } // 返回集合 public List getDataMonth(int id, int year, int month) { String d1, d2; d1 = String.valueOf(year) + "-"; d2 = String.valueOf(year) + "-"; userid = id; no = 1; switch (month) { case 1: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-31"; break; case 2: if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-29"; } else { d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-28"; } break; case 3: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-31"; break; case 4: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-30"; break; case 5: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-31"; break; case 6: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-30"; break; case 7: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-31"; break; case 8: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-31"; break; case 9: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-30"; break; case 10: d1 += String.valueOf(month) + "-01"; d2 += String.valueOf(month) + "-31"; break; case 11: d1 += String.valueOf(month) + "-01"; d2 += String.valueOf(month) + "-30"; break; case 12: d1 += String.valueOf(month) + "-01"; d2 += String.valueOf(month) + "-31"; break; } List datapickerlist = new ArrayList(); Datapicker datapicker; for (String temp = d1; temp.compareTo(d2) <= 0;) { // 创建集合对象 datapicker = getDataOnDay(temp, temp); datapickerlist.add(datapicker); Log.i("cwp", "===========pay" + temp + datapicker.getMoney().toString()); temp = addDays(temp, 1); } return datapickerlist; } public List getDataAnytime(int id, String date1, String date2) { userid = id; no = 1; List datapickerlist = new ArrayList(); Datapicker datapicker; for (String temp = date1; temp.compareTo(date2) <= 0;) { // 创建集合对象 datapicker = getDataOnDay(temp, temp); datapickerlist.add(datapicker); temp = addDays(temp, 1); } return datapickerlist; } public void deleteUserData(int id) {// 清空用户数据 db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 db.execSQL("delete from tb_income where _id=?", new Object[] { id }); } public List getKDataOnDay(int id, String date1, String date2) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 List kinddatalist = new ArrayList(); Cursor cursor = db .rawQuery( "select type, total(money) as tmoney from tb_income where time >= ? and time <= ? and _id =? group by type", new String[] { date1, date2, String.valueOf(id) });// 获取支出信息表中的最大编号 while (cursor.moveToNext())// 遍历所有的支出信息 { // 将遍历到的支出信息添加到集合中 kinddatalist.add(new KindData(cursor.getInt(cursor .getColumnIndex("type")), cursor.getDouble(cursor .getColumnIndex("tmoney")))); } cursor.close(); return kinddatalist;// 返回集合 // 将遍历到的支出信息添加到集合中 } // 返回集合 public List getKDataOnMonth(int id, int year, int month) { String d1, d2; d1 = String.valueOf(year) + "-"; d2 = String.valueOf(year) + "-"; switch (month) { case 1: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-31"; break; case 2: if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-29"; } else { d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-28"; } break; case 3: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-31"; break; case 4: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-30"; break; case 5: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-31"; break; case 6: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-30"; break; case 7: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-31"; break; case 8: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-31"; break; case 9: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-30"; break; case 10: d1 += String.valueOf(month) + "-01"; d2 += String.valueOf(month) + "-31"; break; case 11: d1 += String.valueOf(month) + "-01"; d2 += String.valueOf(month) + "-30"; break; case 12: d1 += String.valueOf(month) + "-01"; d2 += String.valueOf(month) + "-31"; break; } return getKDataOnDay(id, d1, d2); } public String gettime(int mYear, int defaultMonth, int defaultDay, boolean first, boolean end) { String dall, dmonth, dday; if (first || end) { String d1, d2; d1 = String.valueOf(mYear) + "-"; d2 = String.valueOf(mYear) + "-"; switch (defaultMonth) { case 1: d1 += "0" + String.valueOf(defaultMonth) + "-01"; d2 += "0" + String.valueOf(defaultMonth) + "-31"; break; case 2: if (mYear % 4 == 0 && mYear % 100 != 0 || mYear % 400 == 0) { d1 += "0" + String.valueOf(defaultMonth) + "-01"; d2 += "0" + String.valueOf(defaultMonth) + "-29"; } else { d1 += "0" + String.valueOf(defaultMonth) + "-01"; d2 += "0" + String.valueOf(defaultMonth) + "-28"; } break; case 3: d1 += "0" + String.valueOf(defaultMonth) + "-01"; d2 += "0" + String.valueOf(defaultMonth) + "-31"; break; case 4: d1 += "0" + String.valueOf(defaultMonth) + "-01"; d2 += "0" + String.valueOf(defaultMonth) + "-30"; break; case 5: d1 += "0" + String.valueOf(defaultMonth) + "-01"; d2 += "0" + String.valueOf(defaultMonth) + "-31"; break; case 6: d1 += "0" + String.valueOf(defaultMonth) + "-01"; d2 += "0" + String.valueOf(defaultMonth) + "-30"; break; case 7: d1 += "0" + String.valueOf(defaultMonth) + "-01"; d2 += "0" + String.valueOf(defaultMonth) + "-31"; break; case 8: d1 += "0" + String.valueOf(defaultMonth) + "-01"; d2 += "0" + String.valueOf(defaultMonth) + "-31"; break; case 9: d1 += "0" + String.valueOf(defaultMonth) + "-01"; d2 += "0" + String.valueOf(defaultMonth) + "-30"; break; case 10: d1 += String.valueOf(defaultMonth) + "-01"; d2 += String.valueOf(defaultMonth) + "-31"; break; case 11: d1 += String.valueOf(defaultMonth) + "-01"; d2 += String.valueOf(defaultMonth) + "-30"; break; case 12: d1 += String.valueOf(defaultMonth) + "-01"; d2 += String.valueOf(defaultMonth) + "-31"; break; } if (first) { dall = d1; } else { dall = d2; } } else { if (defaultMonth < 10) { dmonth = "0" + Integer.toString(defaultMonth); } else { dmonth = Integer.toString(defaultMonth); } if (defaultDay < 10) { dday = "0" + Integer.toString(defaultDay); } else { dday = Integer.toString(defaultDay); } dall = Integer.toString(mYear) + "-" + dmonth + "-" + dday; } return dall; } } ================================================ FILE: MoneyCharge/app/src/main/java/cwp/moneycharge/dao/ItypeDAO.java ================================================ package cwp.moneycharge.dao; import cwp.moneycharge.model.Datapicker; import cwp.moneycharge.model.Tb_itype; import cwp.moneycharge.dao.DBOpenHelper; import java.util.List; import java.util.ArrayList; import com.cwp.cmoneycharge.R; import android.database.sqlite.SQLiteDatabase; import android.content.Context; import android.database.Cursor; /** * @author cwpcc * */ public class ItypeDAO { //(_id INTEGER NOT NULL PRIMARY KEY,no not null int ,typename varchar(50) private DBOpenHelper helper;// 创建DBOpenHelper对象 private SQLiteDatabase db;// 创建SQLiteDatabase对象 int[] imageId = new int[] { R.drawable.icon_zysr_gzsr, R.drawable.icon_qtsr_zjsr, R.drawable.icon_zysr_tzsr, R.drawable.icon_qtsr, R.drawable.icon_qtzx, R.drawable.icon_jrbx_xfss, R.drawable.icon_zysr_lxsr, R.drawable.icon_zysr_jzsr, R.drawable.icon_zysr_jjsr, R.drawable.icon_lyyp_hwzb, R.drawable.icon_qtsr_jysd, R.drawable.icon_qtsr_jysd, R.drawable.icon_qtsr_jysd, R.drawable.icon_qtsr, R.drawable.icon_qtsr_ljsr, R.drawable.yysb }; public ItypeDAO(Context context) { // TODO Auto-generated constructor stub helper = new DBOpenHelper(context);// 初始化DBOpenHelper对象 } /** * 新增收入类型 * @param Tb_itype */ public void add(Tb_itype tb_itype){ db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 db.execSQL("insert into tb_itype (_id,no,typename) values (?,?,?)", new Object[] { tb_itype.get_id(),tb_itype.getNo(),tb_itype.getTypename()});// 执行添加收入类型操作 } /** * 修改收入类型 * @param Tb_itype */ public void modify(Tb_itype tb_itype){ db=helper.getWritableDatabase();// 初始化SQLiteDatabase对象 db.execSQL("update tb_itype set typename = ? where _id = ? and no=?", new Object[] { tb_itype.get_id(), tb_itype.getNo(),tb_itype.getTypename() });// 执行修改收入类型操作 } /** * 删除收入类型 * @param ids */ public void delete(Integer... ids){ if (ids.length > 0)// 判断是否存在要删除的id { StringBuffer sb = new StringBuffer();// 创建StringBuffer对象 for (int i = 0; i < ids.length-1; i++)// 遍历要删除的id集合 { sb.append('?').append(',');// 将删除条件添加到StringBuffer对象中 } sb.deleteCharAt(sb.length() - 1);// 去掉最后一个“,“字符 db = helper.getWritableDatabase();// 创建SQLiteDatabase对象 // 执行删除便签信息操作 db.execSQL("delete from tb_itype where _id in (?) and no in (" + sb + ")", (Object[]) ids); } } public void deleteByName(int id,String typename){ db = helper.getWritableDatabase();// 创建SQLiteDatabase对象 // 执行删除便签信息操作 db.execSQL("delete from tb_itype where _id =? and typename=?", new Object[] { id, typename}); } public void deleteById(int id){ db = helper.getWritableDatabase();// 创建SQLiteDatabase对象 // 执行删除便签信息操作 db.execSQL("delete from tb_itype where _id =? ", new Object[] { id}); } /** * 获取收入类型信息 * * @param start * 起始位置 * @param count * 每页显示数量 * @return */ public List getScrollData(int id,int start, int count) { List lisTb_itype = new ArrayList();// 创建集合对象 db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 // 获取所有便签信息 Cursor cursor = db.rawQuery("select * from tb_itype where _id=? order by no limit ?,?", new String[] { String.valueOf(id), String.valueOf(start), String.valueOf(count) }); while (cursor.moveToNext())// 遍历所有的便签信息 { // 将遍历到的便签信息添加到集合中 lisTb_itype.add(new Tb_itype( cursor.getInt(cursor.getColumnIndex("_id")), cursor.getInt(cursor.getColumnIndex("no")), cursor.getString(cursor.getColumnIndex("typename")))); } return lisTb_itype;// 返回集合 } /** * 获取总记录数 * * @return */ public long getCount() { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery("select count(no) from tb_itype", null);// 获取收入类型的记录数 if (cursor.moveToNext())// 判断Cursor中是否有数据 { return cursor.getLong(0);// 返回总记录数 } return 0;// 如果没有数据,则返回0 } public long getCount(int id) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db .rawQuery("select count(no) from tb_itype where _id=?", new String[]{String.valueOf(id)});// 获取收入信息的记录数 if (cursor.moveToNext())// 判断Cursor中是否有数据 { return cursor.getLong(0);// 返回总记录数 } return 0;// 如果没有数据,则返回0 } /** * 获取便签最大编号 * * @return */ public int getMaxId() { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery("select max(no) from tb_itype", null);// 获取收入类型表中的最大编号 while (cursor.moveToLast()) {// 访问Cursor中的最后一条数据 return cursor.getInt(0);// 获取访问到的数据,即最大编号 } return 0;// 如果没有数据,则返回0 } /** * 获取类型名数组 * param id * @return * */ public List getItypeName(int id){ List lisString = new ArrayList();// 创建集合对象 db = helper.getWritableDatabase(); Cursor cursor = db.rawQuery("select typename from tb_itype where _id=?",new String[]{String.valueOf(id) } ); while (cursor.moveToNext()) {// 访问Cursor中的最后一条数据 lisString.add(cursor.getString(cursor.getColumnIndex("typename"))); } return lisString; } public String getOneName(int id,int no){ db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery("select typename from tb_itype where _id=? and no=?",new String[]{String.valueOf(id),String.valueOf(no) } ); if (cursor.moveToNext()) { return cursor.getString(cursor.getColumnIndex("typename")); } return ""; } public int getOneImg(int id, int no) { if (imageId.length < no) { return imageId[14]; } return imageId[no - 1]; } //获取指定时间内数据库数据 public List getDataOnDay(int id,String date1,String date2){ db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 List datapicker = new ArrayList();// 创建集合对象 String sql= "'"+date1+"' and '"+date2+"'"; Cursor cursor = db.rawQuery("select no, time,sum(money) as tmoney from tb_pay where time between "+sql+" and _id =? group BY time order by time",new String[]{String.valueOf(id)} );// 获取支出信息表中的最大编号 while (cursor.moveToNext())// 遍历所有的支出信息 { // 将遍历到的支出信息添加到集合中 datapicker.add(new Datapicker( cursor.getInt(cursor.getColumnIndex("no")), cursor.getDouble(cursor.getColumnIndex("tmoney")), cursor.getString(cursor.getColumnIndex("time")))); } return datapicker;// 返回集合 // 将遍历到的支出信息添加到集合中 } // 返回集合 public void modifyByName(int id,String old,String now){ db = helper.getWritableDatabase(); db.execSQL("update tb_itype set typename = ? where _id = ? and typename=?", new Object[] { id, now,old});// 执行修改收入类型操作 } public void initData(int id) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 // 便签信息表 db.execSQL("delete from tb_itype where _id=?",new String[]{String.valueOf(id)}); // 确保无该id db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(id),"1","工资"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(id),"2","中奖"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(id),"3","股票"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(id),"4","还款"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(id),"5","基金"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(id),"6","分红"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(id),"7","利息"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(id),"8","兼职"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(id),"9","奖金"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(id),"10","租金"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(id),"11","销售款"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(id),"12","应收款"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(id),"13","报销款"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(id),"14","其他"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(id),"15","礼金"}); db.execSQL("insert into tb_itype(_id,no,typename) values(?,?,?)",new String[]{String.valueOf(id),"16","语音识别"}); } } ================================================ FILE: MoneyCharge/app/src/main/java/cwp/moneycharge/dao/NoteDAO.java ================================================ /** * */ package cwp.moneycharge.dao; /** * @author cwpcc * */ import java.util.ArrayList; import java.util.List; import cwp.moneycharge.dao.DBOpenHelper; import cwp.moneycharge.model.Tb_note; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; public class NoteDAO { //_id integer primary key,no integer autoincrement,note varchar(200)) /** * */ private DBOpenHelper helper;// 创建DBOpenHelper对象 private SQLiteDatabase db;// 创建SQLiteDatabase对象 public NoteDAO(Context context) { // TODO Auto-generated constructor stub helper = new DBOpenHelper(context);// 初始化DBOpenHelper对象 } /** * 添加便签信息 * * @param tb_note */ public void add(Tb_note tb_note) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 db.execSQL("insert into tb_note (_id,no,note) values (?,?,?)", new Object[] { tb_note.get_id(), tb_note.getNo(),tb_note.getNote() });// 执行添加便签信息操作 } /** * 更新便签信息 * * @param tb_note */ public void update(Tb_note tb_note) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 db.execSQL("update tb_note set note = ? where _id = ? and no=?", new Object[] { tb_note.getNote(), tb_note.get_id(),tb_note.getNo() });// 执行修改便签信息操作 } /** * 查找便签信息 * * @param id no * @return */ public Tb_note find(int id,int no) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery( "select _id,no,note from tb_note where _id = ? and no=?", new String[] { String.valueOf(id) ,String.valueOf(no)});// 根据编号查找便签信息,并存储到Cursor类中 if (cursor.moveToNext())// 遍历查找到的便签信息 { // 将遍历到的便签信息存储到Tb_flag类中 return new Tb_note(cursor.getInt(cursor.getColumnIndex("_id")), cursor.getInt(cursor.getColumnIndex("no")), cursor.getString(cursor.getColumnIndex("note"))); } return null;// 如果没有信息,则返回null } /** * 刪除便签信息 * * @param ids */ public void detele(Integer... ids) { if (ids.length > 0)// 判断是否存在要删除的id { StringBuffer sb = new StringBuffer();// 创建StringBuffer对象 for (int i = 0; i < ids.length-1; i++)// 遍历要删除的id集合 { sb.append('?').append(',');// 将删除条件添加到StringBuffer对象中 } sb.deleteCharAt(sb.length() - 1);// 去掉最后一个“,“字符 db = helper.getWritableDatabase();// 创建SQLiteDatabase对象 // 执行删除便签信息操作 db.execSQL("delete from tb_note where _id in (?) and no in (" + sb + ")", (Object[]) ids); } } /** * 获取便签信息 * * @param start * 起始位置 * @param count * 每页显示数量 * @return */ public List getScrollData(int id,int start, int count) { List lisTb_note = new ArrayList();// 创建集合对象 db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 // 获取所有便签信息 Cursor cursor = db.rawQuery("select _id,no,note from tb_note where _id=? order by no limit ?,?", new String[] { String.valueOf(id), String.valueOf(start), String.valueOf(count) }); while (cursor.moveToNext())// 遍历所有的便签信息 { // 将遍历到的便签信息添加到集合中 lisTb_note.add(new Tb_note( cursor.getInt(cursor.getColumnIndex("_id")), cursor.getInt(cursor.getColumnIndex("no")), cursor.getString(cursor.getColumnIndex("note")))); } return lisTb_note;// 返回集合 } /** * 获取总记录数 * * @return */ public long getCount(int id) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery("select count(no) from tb_note where _id=?",new String[]{String.valueOf(id)});// 获取便签信息的记录数 if (cursor.moveToNext())// 判断Cursor中是否有数据 { return cursor.getLong(0);// 返回总记录数 } return 0;// 如果没有数据,则返回0 } /** * 获取便签最大编号 * * @return */ public int getMaxNo(int id) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery("select max(no) from tb_note where _id=?",new String[]{String.valueOf(id)});// 获取便签信息表中的最大编号 while (cursor.moveToLast()) {// 访问Cursor中的最后一条数据 return cursor.getInt(0);// 获取访问到的数据,即最大编号 } return 0;// 如果没有数据,则返回0 } public void deleteUserData(int id){//清空用户数据 db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 db.execSQL("delete from tb_note where _id=?",new Object[]{id}); } } ================================================ FILE: MoneyCharge/app/src/main/java/cwp/moneycharge/dao/PayDAO.java ================================================ /** * */ package cwp.moneycharge.dao; /** * @author cwpcc * */ import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.List; import cwp.moneycharge.model.*; import android.annotation.SuppressLint; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.text.GetChars; import android.util.Log; public class PayDAO { private DBOpenHelper helper;// 创建DBOpenHelper对象 private SQLiteDatabase db;// 创建SQLiteDatabase对象 private int no = 1;// 编号 private int userid = 100000001; public PayDAO(Context context) { // TODO Auto-generated constructor stub helper = new DBOpenHelper(context);// 初始化DBOpenHelper对象 } /** * 添加支出信息 * * @param tb_pay */ public void add(Tb_pay tb_pay) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 // 执行添加支出信息操作 db.execSQL( "insert into tb_pay (_id,no,money,time,type,address,mark,photo,kind) values (?,?,?,?,?,?,?,?,?)", new Object[] { tb_pay.get_id(), tb_pay.getNo(), tb_pay.getMoney(), tb_pay.getTime(), tb_pay.getType(), tb_pay.getAddress(), tb_pay.getMark(), tb_pay.getPhoto(), "支出" }); } /** * 更新支出信息 * * @param tb_pay */ public void update(Tb_pay tb_pay) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 // 执行修改支出信息操作 db.execSQL( "update tb_pay set money = ?,time = ?,type = ?,address = ?,mark = ?,photo = ? where _id = ? and no=?", new Object[] { tb_pay.getMoney(), tb_pay.getTime(), tb_pay.getType(), tb_pay.getAddress(), tb_pay.getMark(), tb_pay.getPhoto(), tb_pay.get_id(), tb_pay.getNo() }); } /** * 查找支出信息 * * @param id * ,no * @return */ public Tb_pay find(int id, int no) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db .rawQuery( "select _id,no,money,time,type,address,mark,photo from tb_pay where _id = ? and no=?", new String[] { String.valueOf(id), String.valueOf(no) });// 根据编号查找支出信息,并存储到Cursor类中 if (cursor.moveToNext())// 遍历查找到的支出信息 { // 将遍历到的支出信息存储到Tb_outaccount类中 return new Tb_pay(cursor.getInt(cursor.getColumnIndex("_id")), cursor.getInt(cursor.getColumnIndex("no")), cursor.getDouble(cursor.getColumnIndex("money")), cursor.getString(cursor.getColumnIndex("time")), cursor.getInt(cursor.getColumnIndex("type")), cursor.getString(cursor.getColumnIndex("address")), cursor.getString(cursor.getColumnIndex("mark")), cursor.getString(cursor.getColumnIndex("photo"))); } return null;// 如果没有信息,则返回null } /** * 刪除支出信息 * * @param ids */ public void detele(Integer... ids) { if (ids.length > 0)// 判断是否存在要删除的id { StringBuffer sb = new StringBuffer();// 创建StringBuffer对象 for (int i = 0; i < ids.length - 1; i++)// 遍历要删除的id集合 { sb.append('?').append(',');// 将删除条件添加到StringBuffer对象中 } sb.deleteCharAt(sb.length() - 1);// 去掉最后一个“,“字符 db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 // 执行删除支出信息操作 db.execSQL("delete from tb_pay where _id in (?) and no in (" + sb + ")", (Object[]) ids); } } /** * 获取支出信息 * * @param start * 起始位置 * @param count * 每页显示数量 * @return */ public List getScrollData(int id, int start, int count) { List tb_pay = new ArrayList();// 创建集合对象 db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 // 获取所有支出信息 Cursor cursor = db .rawQuery( "select _id,no,money,time,type,address,mark,photo from tb_pay where _id=? order by no limit ?,?", new String[] { String.valueOf(id), String.valueOf(start), String.valueOf(count) }); while (cursor.moveToNext())// 遍历所有的支出信息 { // 将遍历到的支出信息添加到集合中 tb_pay.add(new Tb_pay(cursor.getInt(cursor.getColumnIndex("_id")), cursor.getInt(cursor.getColumnIndex("no")), cursor .getDouble(cursor.getColumnIndex("money")), cursor .getString(cursor.getColumnIndex("time")), cursor .getInt(cursor.getColumnIndex("type")), cursor .getString(cursor.getColumnIndex("address")), cursor.getString(cursor.getColumnIndex("mark")), cursor .getString(cursor.getColumnIndex("photo")))); } return tb_pay;// 返回集合 } /** * 获取总记录数 * * @return */ public long getCount() { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery("select count(no) from tb_pay", null);// 获取支出信息的记录数 if (cursor.moveToNext())// 判断Cursor中是否有数据 { return cursor.getLong(0);// 返回总记录数 } return 0;// 如果没有数据,则返回0 } public long getCount(int id) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery("select count(no) from tb_pay where _id=?", new String[] { String.valueOf(id) });// 获取收入信息的记录数 if (cursor.moveToNext())// 判断Cursor中是否有数据 { return cursor.getLong(0);// 返回总记录数 } return 0;// 如果没有数据,则返回0 } /** * 获取支出最大编号 * * @return */ public int getMaxNo(int id) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery("select max(no) from tb_pay where _id=?", new String[] { String.valueOf(id) });// 获取支出信息表中的最大编号 while (cursor.moveToLast()) {// 访问Cursor中的最后一条数据 return cursor.getInt(0);// 获取访问到的数据,即最大编号 } return 0;// 如果没有数据,则返回0 } @SuppressLint("SimpleDateFormat") public String addDays(String sdate, int days) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = new Date(); try { date = (Date) sdf.parse(sdate); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.add(Calendar.DATE, days); // minus number would decrement the days date = cal.getTime(); String result = sdf.format(date); return result; } public Double getamountData(int userid) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Double data = 0.0; Cursor cursor = db.rawQuery( "select sum(money) from tb_pay where _id=?", new String[] { String.valueOf(userid) }); // 获取支出信息表中的最大编号 while (cursor.moveToNext())// 遍历所有的支出信息 { // 将遍历到的支出信息添加到集合中 data = cursor.getDouble(0); } cursor.close(); return data; } public Datapicker getDataOnDay(String date1, String date2) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Double data = 0.0; Datapicker datapicker; Cursor cursor = db .rawQuery( "select total(money) as tmoney from tb_pay where time >= ? and time <= ? and _id =?", new String[] { date1, date2, String.valueOf(userid) });// 获取支出信息表中的最大编号 while (cursor.moveToNext())// 遍历所有的支出信息 { // 将遍历到的支出信息添加到集合中 data = cursor.getDouble(cursor.getColumnIndex("tmoney")); } cursor.close(); datapicker = new Datapicker(no, data, date1); no++; return datapicker; // 将遍历到的支出信息添加到集合中 } // 返回集合 public List getDataMonth(int id, int year, int month) { String d1, d2; d1 = String.valueOf(year) + "-"; d2 = String.valueOf(year) + "-"; userid = id; no = 1; switch (month) { case 1: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-31"; break; case 2: if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-29"; } else { d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-28"; } break; case 3: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-31"; break; case 4: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-30"; break; case 5: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-31"; break; case 6: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-30"; break; case 7: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-31"; break; case 8: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-31"; break; case 9: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-30"; break; case 10: d1 += String.valueOf(month) + "-01"; d2 += String.valueOf(month) + "-31"; break; case 11: d1 += String.valueOf(month) + "-01"; d2 += String.valueOf(month) + "-30"; break; case 12: d1 += String.valueOf(month) + "-01"; d2 += String.valueOf(month) + "-31"; break; } List datapickerlist = new ArrayList(); Datapicker datapicker; for (String temp = d1; temp.compareTo(d2) <= 0;) { // 创建集合对象 datapicker = getDataOnDay(temp, temp); datapickerlist.add(datapicker); temp = addDays(temp, 1); } return datapickerlist; } public List getDataAnytime(int id, String date1, String date2) { userid = id; no = 1; List datapickerlist = new ArrayList(); Datapicker datapicker; for (String temp = date1; temp.compareTo(date2) <= 0;) { // 创建集合对象 datapicker = getDataOnDay(temp, temp); datapickerlist.add(datapicker); temp = addDays(temp, 1); } return datapickerlist; } public void deleteUserData(int id) {// 清空用户数据 db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 db.execSQL("delete from tb_pay where _id=?", new Object[] { id }); } public List getScrollData(int id, int start, int count, String date1, String date2) { List tb_pay = new ArrayList();// 创建集合对象 db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 // 获取所有支出信息 Cursor cursor = db .rawQuery( "select _id,no,money,time,type,address,mark,photo from tb_pay where _id=? and time >= ? and time <= ? order by time DESC", new String[] { String.valueOf(id), date1, date2 }); while (cursor.moveToNext())// 遍历所有的支出信息 { // 将遍历到的支出信息添加到集合中 tb_pay.add(new Tb_pay(cursor.getInt(cursor.getColumnIndex("_id")), cursor.getInt(cursor.getColumnIndex("no")), cursor .getDouble(cursor.getColumnIndex("money")), cursor .getString(cursor.getColumnIndex("time")), cursor .getInt(cursor.getColumnIndex("type")), cursor .getString(cursor.getColumnIndex("address")), cursor.getString(cursor.getColumnIndex("mark")), cursor .getString(cursor.getColumnIndex("photo")))); } return tb_pay;// 返回集合 } public List getKDataOnDay(int id, String date1, String date2) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 List kinddatalist = new ArrayList(); Cursor cursor = db .rawQuery( "select type, total(money) as tmoney from tb_pay where time >= ? and time <= ? and _id =? group by type", new String[] { date1, date2, String.valueOf(id) });// 获取支出信息表中的最大编号 while (cursor.moveToNext())// 遍历所有的支出信息 { // 将遍历到的支出信息添加到集合中 kinddatalist.add(new KindData(cursor.getInt(cursor .getColumnIndex("type")), cursor.getDouble(cursor .getColumnIndex("tmoney")))); } cursor.close(); return kinddatalist;// 返回集合 // 将遍历到的支出信息添加到集合中 } // 返回集合 public List getKDataOnMonth(int id, int year, int month) { String d1, d2; d1 = String.valueOf(year) + "-"; d2 = String.valueOf(year) + "-"; switch (month) { case 1: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-31"; break; case 2: if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-29"; } else { d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-28"; } break; case 3: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-31"; break; case 4: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-30"; break; case 5: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-31"; break; case 6: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-30"; break; case 7: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-31"; break; case 8: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-31"; break; case 9: d1 += "0" + String.valueOf(month) + "-01"; d2 += "0" + String.valueOf(month) + "-30"; break; case 10: d1 += String.valueOf(month) + "-01"; d2 += String.valueOf(month) + "-31"; break; case 11: d1 += String.valueOf(month) + "-01"; d2 += String.valueOf(month) + "-30"; break; case 12: d1 += String.valueOf(month) + "-01"; d2 += String.valueOf(month) + "-31"; break; } return getKDataOnDay(id, d1, d2); } } ================================================ FILE: MoneyCharge/app/src/main/java/cwp/moneycharge/dao/PtypeDAO.java ================================================ package cwp.moneycharge.dao; import cwp.moneycharge.model.Tb_ptype; import cwp.moneycharge.dao.DBOpenHelper; import java.util.List; import java.util.ArrayList; import com.cwp.cmoneycharge.R; import android.database.sqlite.SQLiteDatabase; import android.content.Context; import android.database.Cursor; public class PtypeDAO { // (_id INTEGER NOT NULL PRIMARY KEY,no not null integer ,typename // varchar(50) private DBOpenHelper helper;// 创建DBOpenHelper对象 private SQLiteDatabase db;// 创建SQLiteDatabase对象 int[] imageId = new int[] { R.drawable.icon_spjs_zwwc, R.drawable.icon_spjs_zwwc, R.drawable.icon_spjs_zwwc, R.drawable.icon_spjs_zwwc, R.drawable.icon_jjwy_rcyp, R.drawable.icon_xxyl_wg, R.drawable.icon_yfsp, R.drawable.icon_rqwl_slqk, R.drawable.icon_jltx_sjf, R.drawable.icon_spjs, R.drawable.icon_jrbx_ajhk, R.drawable.icon_jrbx, R.drawable.icon_xcjt_dczc, R.drawable.icon_qtzx, R.drawable.icon_jrbx_lxzc, R.drawable.yysb }; public PtypeDAO(Context context) { // TODO Auto-generated constructor stub helper = new DBOpenHelper(context);// 初始化DBOpenHelper对象 } /** * 新增收入类型 * * @param tb_ptype */ public void add(Tb_ptype tb_ptype) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 db.execSQL( "insert into tb_ptype (_id,no,typename) values (?,?,?)", new Object[] { tb_ptype.get_id(), tb_ptype.getNo(), tb_ptype.getTypename() });// 执行添加支出类型操作 } /** * 修改收入类型 * * @param tb_ptype */ public void modify(Tb_ptype tb_ptype) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 db.execSQL( "update Tb_ptype set typename = ? where _id = ? and no=?", new Object[] { tb_ptype.get_id(), tb_ptype.getNo(), tb_ptype.getTypename() });// 执行修改支出类型操作 } public void modifyByName(int id, String old, String now) { db = helper.getWritableDatabase(); db.execSQL( "update Tb_ptype set typename = ? where _id = ? and typename=?", new Object[] { id, now, old });// 执行修改收入类型操作 } /** * 删除收入类型 * * @param ids */ public void delete(Integer... ids) { if (ids.length > 0)// 判断是否存在要删除的id { StringBuffer sb = new StringBuffer();// 创建StringBuffer对象 for (int i = 0; i < ids.length - 1; i++)// 遍历要删除的id集合 { sb.append('?').append(',');// 将删除条件添加到StringBuffer对象中 } sb.deleteCharAt(sb.length() - 1);// 去掉最后一个“,“字符 db = helper.getWritableDatabase();// 创建SQLiteDatabase对象 // 执行删除便签信息操作 db.execSQL("delete from tb_ptype where _id in (?) and no in (" + sb + ")", (Object[]) ids); } } public void deleteByName(int id, String typename) { db = helper.getWritableDatabase();// 创建SQLiteDatabase对象 // 执行删除便签信息操作 db.execSQL("delete from tb_ptype where _id =? and typename=?", new Object[] { id, typename }); } public void deleteById(int id) { db = helper.getWritableDatabase();// 创建SQLiteDatabase对象 // 执行删除便签信息操作 db.execSQL("delete from tb_ptype where _id =? ", new Object[] { id }); } /** * 获取收入类型信息 * * @param start * 起始位置 * @param count * 每页显示数量 * @return */ public List getScrollData(int id, int start, int count) { List lisTb_ptype = new ArrayList();// 创建集合对象 db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 // 获取所有便签信息 Cursor cursor = db.rawQuery( "select * from tb_ptype where _id=? order by no limit ?,?", new String[] { String.valueOf(id), String.valueOf(start), String.valueOf(count) }); while (cursor.moveToNext())// 遍历所有的便签信息 { // 将遍历到的便签信息添加到集合中 lisTb_ptype.add(new Tb_ptype(cursor.getInt(cursor .getColumnIndex("_id")), cursor.getInt(cursor .getColumnIndex("no")), cursor.getString(cursor .getColumnIndex("typename")))); } return lisTb_ptype;// 返回集合 } /** * 获取总记录数 * * @return */ public long getCount() { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery("select count(no) from tb_ptype", null);// 获取支出类型的记录数 if (cursor.moveToNext())// 判断Cursor中是否有数据 { return cursor.getLong(0);// 返回总记录数 } return 0;// 如果没有数据,则返回0 } public long getCount(int id) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery( "select count(no) from tb_ptype where _id=?", new String[] { String.valueOf(id) });// 获取收入信息的记录数 if (cursor.moveToNext())// 判断Cursor中是否有数据 { return cursor.getLong(0);// 返回总记录数 } return 0;// 如果没有数据,则返回0 } /** * 获取便签最大编号 * * @return */ public int getMaxId() { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery("select max(no) from tb_ptype", null);// 获取收入类型表中的最大编号 while (cursor.moveToLast()) {// 访问Cursor中的最后一条数据 return cursor.getInt(0);// 获取访问到的数据,即最大编号 } return 0;// 如果没有数据,则返回0 } /** * 获取类型名数组 param id * * @return * */ public List getPtypeName(int id) { List lisCharSequence = new ArrayList();// 创建集合对象 db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery( "select typename from tb_ptype where _id=?", new String[] { String.valueOf(id) });// 获取收入类型表中的最大编号 while (cursor.moveToNext()) {// 访问Cursor中的最后一条数据 lisCharSequence.add(cursor.getString(cursor .getColumnIndex("typename"))); } return lisCharSequence;// 如果没有数据,则返回0 } public String getOneName(int id, int no) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 Cursor cursor = db.rawQuery( "select typename from tb_ptype where _id=? and no=?", new String[] { String.valueOf(id), String.valueOf(no) }); if (cursor.moveToNext()) { return cursor.getString(cursor.getColumnIndex("typename")); } return ""; } public int getOneImg(int id, int no) { if (imageId.length < no) { return imageId[14]; } return imageId[no - 1]; } public void initData(int id) { db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象 db.execSQL("delete from tb_ptype where _id=?", new String[] { String.valueOf(id) }); // 确保无该id db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "1", "早餐" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "2", "午餐" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "3", "晚餐" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "4", "夜宵" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "5", "生活用品" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "6", "工作用品" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "7", "衣服" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "8", "应酬" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "9", "电子产品" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "10", "食品" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "11", "租金" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "12", "股票" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "13", "打的" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "14", "基金" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "15", "其他" }); db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)", new String[] { String.valueOf(id), "16", "语音识别" }); } } ================================================ FILE: MoneyCharge/app/src/main/java/cwp/moneycharge/model/ActivityManager.java ================================================ package cwp.moneycharge.model; import java.util.LinkedList; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.app.Application; import android.content.DialogInterface; import android.content.Intent; public class ActivityManager { private List mList = new LinkedList(); private static ActivityManager instance; public ActivityManager() { // TODO Auto-generated constructor stub } public synchronized static ActivityManager getInstance() { if (null == instance) { instance = new ActivityManager(); } return instance; } // add Activity public void addActivity(Activity activity) { mList.add(activity); } public void exit() { try { for (Activity activity : mList) { if (activity != null) activity.finish(); } } catch (Exception e) { e.printStackTrace(); } finally { System.exit(0); } } } ================================================ FILE: MoneyCharge/app/src/main/java/cwp/moneycharge/model/CustomDialog.java ================================================ package cwp.moneycharge.model; import com.cwp.cmoneycharge.R; import com.cwp.cmoneycharge.R.id; import com.cwp.cmoneycharge.R.layout; import com.cwp.cmoneycharge.R.style; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; /** * * Create custom Dialog windows for your application * Custom dialogs rely on custom layouts wich allow you to * create and use your own look & feel. * * Under GPL v3 : http://www.gnu.org/licenses/gpl-3.0.html * * @author antoine vianey * */ public class CustomDialog extends Dialog { public CustomDialog(Context context, int theme) { super(context, theme); } public CustomDialog(Context context) { super(context); } /** * Helper class for creating a custom dialog */ public static class Builder { private Context context; private String title; private String message; private String positiveButtonText; private String negativeButtonText; private View contentView; private DialogInterface.OnClickListener positiveButtonClickListener, negativeButtonClickListener; public Builder(Context context) { this.context = context; } /** * Set the Dialog message from String * @param title * @return */ public Builder setMessage(String message) { this.message = message; return this; } /** * Set the Dialog message from resource * @param title * @return */ public Builder setMessage(int message) { this.message = (String) context.getText(message); return this; } /** * Set the Dialog title from resource * @param title * @return */ public Builder setTitle(int title) { this.title = (String) context.getText(title); return this; } /** * Set the Dialog title from String * @param title * @return */ public Builder setTitle(String title) { this.title = title; return this; } /** * Set a custom content view for the Dialog. * If a message is set, the contentView is not * added to the Dialog... * @param v * @return */ public Builder setContentView(View v) { this.contentView = v; return this; } /** * Set the positive button resource and it's listener * @param positiveButtonText * @param listener * @return */ public Builder setPositiveButton(int positiveButtonText, DialogInterface.OnClickListener listener) { this.positiveButtonText = (String) context .getText(positiveButtonText); this.positiveButtonClickListener = listener; return this; } /** * Set the positive button text and it's listener * @param positiveButtonText * @param listener * @return */ public Builder setPositiveButton(String positiveButtonText, DialogInterface.OnClickListener listener) { this.positiveButtonText = positiveButtonText; this.positiveButtonClickListener = listener; return this; } /** * Set the negative button resource and it's listener * @param negativeButtonText * @param listener * @return */ public Builder setNegativeButton(int negativeButtonText, DialogInterface.OnClickListener listener) { this.negativeButtonText = (String) context .getText(negativeButtonText); this.negativeButtonClickListener = listener; return this; } /** * Set the negative button text and it's listener * @param negativeButtonText * @param listener * @return */ public Builder setNegativeButton(String negativeButtonText, DialogInterface.OnClickListener listener) { this.negativeButtonText = negativeButtonText; this.negativeButtonClickListener = listener; return this; } /** * Create the custom dialog */ public CustomDialog create() { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); // instantiate the dialog with the custom Theme final CustomDialog dialog = new CustomDialog(context, R.style.Dialog); View layout = inflater.inflate(R.layout.dialog, null); dialog.addContentView(layout, new LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); // set the dialog title ((TextView) layout.findViewById(R.id.title)).setText(title); // set the confirm button if (positiveButtonText != null) { ((Button) layout.findViewById(R.id.positiveButton)) .setText(positiveButtonText); if (positiveButtonClickListener != null) { ((Button) layout.findViewById(R.id.positiveButton)) .setOnClickListener(new View.OnClickListener() { public void onClick(View v) { positiveButtonClickListener.onClick( dialog, DialogInterface.BUTTON_POSITIVE); } }); } } else { // if no confirm button just set the visibility to GONE layout.findViewById(R.id.positiveButton).setVisibility( View.GONE); } // set the cancel button if (negativeButtonText != null) { ((Button) layout.findViewById(R.id.negativeButton)) .setText(negativeButtonText); if (negativeButtonClickListener != null) { ((Button) layout.findViewById(R.id.negativeButton)) .setOnClickListener(new View.OnClickListener() { public void onClick(View v) { negativeButtonClickListener.onClick( dialog, DialogInterface.BUTTON_NEGATIVE); } }); } } else { // if no confirm button just set the visibility to GONE layout.findViewById(R.id.negativeButton).setVisibility( View.GONE); } // set the content message if (message != null) { ((TextView) layout.findViewById( R.id.message)).setText(message); } else if (contentView != null) { // if no message set // add the contentView to the dialog body ((LinearLayout) layout.findViewById(R.id.content)) .removeAllViews(); ((LinearLayout) layout.findViewById(R.id.content)) .addView(contentView, new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); } dialog.setContentView(layout); return dialog; } } } ================================================ FILE: MoneyCharge/app/src/main/java/cwp/moneycharge/model/Datapicker.java ================================================ package cwp.moneycharge.model; public class Datapicker { private int no; private String time; private Double money; public Datapicker(int no,Double money,String time) { // TODO Auto-generated constructor stub this.no=no; this.time=time; this.money=money; } public int getNo() { return no; } public void setNo(int no) { this.no = no; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public Double getMoney() { return money; } public void setMoney(Double money) { this.money = money; } } ================================================ FILE: MoneyCharge/app/src/main/java/cwp/moneycharge/model/KindData.java ================================================ package cwp.moneycharge.model; public class KindData { private int kindname; private double amount; public KindData(int kindname,double amount) { // TODO Auto-generated constructor stub this.kindname=kindname; this.amount=amount; } public int getKindname() { return kindname; } public void setKindname(int kindname) { this.kindname = kindname; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } } ================================================ FILE: MoneyCharge/app/src/main/java/cwp/moneycharge/model/Tb_account.java ================================================ package cwp.moneycharge.model; public class Tb_account { //_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT ,username varchar(20),pwd varchar(50) private int _id ; private String username; private String pwd ; public Tb_account( int id ,String username, String pwd ) { // TODO Auto-generated constructor stub super(); this._id=id; this.pwd=pwd; this.username=username; } public Tb_account(){ super(); } public int get_id() { return _id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } } ================================================ FILE: MoneyCharge/app/src/main/java/cwp/moneycharge/model/Tb_income.java ================================================ /** * */ package cwp.moneycharge.model; import java.math.BigDecimal; import java.text.DecimalFormat; /** * @author cwpcc * */ public class Tb_income { // _id INTEGER NOT NULL PRIMARY KEY,no not null integer ,money decimal,time // varchar(10), // type integer ,handler varchar(100),mark varchar(200)) private int _id;// 存储用户id private int no;// 存储收入编号 private double money;// 存储收入金额 private String time;// 存储收入时间 private int type;// 存储收入类别id private String handler;// 存储收入地址 private String mark;// 存储收入备注 private String kind;// 存储收入收支类别 private String photo;// 存储支出备注 public Tb_income(int id, int no, double d, String time, int type, String handler, String mark, String photo, String kind) { super(); this._id = id;// 为用户id this.no = no;// 为收入编号赋值 this.money = d;// 为收入金额赋值 this.time = time;// 为收入时间赋值 this.type = type;// 为收入类别赋值 this.handler = handler;// 为收入付款方赋值 this.mark = mark;// 为收入备注赋值 this.kind = kind;// 为收入备注赋值 this.photo = photo;// 为支出备注赋值 } public String getPhoto() { return photo; } public void setPhoto(String photo) { this.photo = photo; } public Tb_income() { super(); } public int get_id() { return _id; } public void set_id(int _id) { this._id = _id; } public int getNo() { return no; } public void setNo(int no) { this.no = no; } public double getMoney() { return money; } public String getMoney2() { double a = money; DecimalFormat df = new DecimalFormat("#.00"); return df.format(a); } public void setMoney(double money) { this.money = money; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getHandler() { return handler; } public void setHandler(String handler) { this.handler = handler; } public String getMark() { return mark; } public void setMark(String mark) { this.mark = mark; } public String getKind() { return kind; } public void setKind(String kind) { this.kind = kind; } } ================================================ FILE: MoneyCharge/app/src/main/java/cwp/moneycharge/model/Tb_itype.java ================================================ package cwp.moneycharge.model; public class Tb_itype { //_id INTEGER NOT NULL PRIMARY KEY,no not null integer AUTOINCREMENT ,typename varchar(50) private int _id;//用户id private int no;//收入类型id private String typename;//收入类型名称 public Tb_itype() { // TODO Auto-generated constructor stub super(); } public Tb_itype(int id,int no,String typename) { // TODO Auto-generated constructor stub super(); this._id=id; this.no=no; this.typename=typename; } public int get_id() { return _id; } public void set_id(int _id) { this._id = _id; } public int getNo() { return no; } public void set_No(int no) { this.no = no; } public String getTypename() { return typename; } public void setTypename(String typename) { this.typename = typename; } } ================================================ FILE: MoneyCharge/app/src/main/java/cwp/moneycharge/model/Tb_note.java ================================================ package cwp.moneycharge.model; public class Tb_note { //_id integer primary key,no integer autoincrement,flag varchar(200)) private int _id; private int no; private String note; public Tb_note() { // TODO Auto-generated constructor stub super(); } public Tb_note(int id,int no,String note) { super(); this._id=id; this.no=no; this.note=note; } public int get_id() { return _id; } public void set_id(int _id) { this._id = _id; } public int getNo() { return no; } public void setNo(int no) { this.no = no; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } } ================================================ FILE: MoneyCharge/app/src/main/java/cwp/moneycharge/model/Tb_pay.java ================================================ package cwp.moneycharge.model; import java.math.BigDecimal; import java.text.DecimalFormat; public class Tb_pay { // _id INTEGER NOT NULL PRIMARY KEY,no not null integer AUTOINCREMENT ,money // decimal,time varchar(10)," // + "type integer ,address varchar(100),mark varchar(200)) private int _id; private int no;// 存储支出编号 private double money;// 存储支出金额 private String time;// 存储支出时间 private int type;// 存储支出类别 private String address;// 存储支出地点 private String mark;// 存储支出备注 private String photo;// 存储支出备注 public Tb_pay() { // TODO Auto-generated constructor stub super(); } public Tb_pay(int id, int no, double d, String time, int type, String address, String mark, String photo) { super(); this._id = id; this.no = no;// 为支出编号赋值 this.money = d;// 为支出金额赋值 this.time = time;// 为支出时间赋值 this.type = type;// 为支出类别赋值 this.address = address;// 为支出地点赋值 this.mark = mark;// 为支出备注赋值 this.photo = photo;// 为支出备注赋值 } public int get_id() { return _id; } public void set_id(int _id) { this._id = _id; } public void setNo(int no) { this.no = no; } public int getNo() { return no; } public double getMoney() { return money; } public void setMoney(double money) { this.money = money; } public String getMoney2() { double a = money; DecimalFormat df = new DecimalFormat("#.00"); return df.format(a); } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getMark() { return mark; } public void setMark(String mark) { this.mark = mark; } public String getPhoto() { return photo; } public void setPhoto(String photo) { this.photo = photo; } } ================================================ FILE: MoneyCharge/app/src/main/java/cwp/moneycharge/model/Tb_ptype.java ================================================ package cwp.moneycharge.model; public class Tb_ptype { //_id INTEGER NOT NULL PRIMARY KEY,no not null integer AUTOINCREMENT ,typename varchar(50) private int _id;//用户id private int no;//支出类型id private String typename;//支出类型名称 public Tb_ptype() { // TODO Auto-generated constructor stub super(); } public Tb_ptype(int id,int no,String typename) { // TODO Auto-generated constructor stub super(); this._id=id; this.no=no; this.typename=typename; } public int get_id() { return _id; } public void set_id(int _id) { this._id = _id; } public void set_No(int no) { this.no = no; } public int getNo() { return no; } public String getTypename() { return typename; } public void setTypename(String typename) { this.typename = typename; } } ================================================ FILE: MoneyCharge/app/src/main/res/anim/animation_1.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/anim/animation_2.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/anim/fade_ins.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/anim/hold.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/anim/in_from_right.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/anim/interpolator_cycle.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/anim/out_to_left.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/anim/push_bottom_in.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/anim/push_bottom_in_2.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/anim/push_up_in.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/anim/push_up_out.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/anim/shake.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/anim/shake_x.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/anim/shake_y.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/color/cost_text.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/color/tab_friendfeed_text.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/color/tab_home_text.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/color/tab_more_text.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/color/tab_myfeed_text.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/addphoto_btn.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/bg_border.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/bgd_relatly_line.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/bt_add_pic.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/bt_nobgd.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/bt_queding.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/bt_quxiao.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/bt_shanchu.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/btn_cancel_selector.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/btn_login_selector.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/btn_press.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/btn_selector.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/btn_unpress.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/chart_left_btn.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/chart_right_btn.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/chart_silding_btn.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/checkbox.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/common_btn_green.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/common_btn_red.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/corner_bdbdbd.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/corner_e0e0e0.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/corner_f2f2f2.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/dialog_bg.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/dialog_bottom_bg.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/fb_send_btn_bg.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/keyboard_key.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/locate_btn.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/search_button_type.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/selector.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/shadow.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/skin_color_button.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/tab_friendfeed_btn.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/tab_home_btn.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/tab_more_btn.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/tab_myfeed_btn.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/text_while.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable/welcome_bg.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable-hdpi/common_lv_item_for_metadata_bg.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable-hdpi/common_lv_item_higher_bg.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable-hdpi/common_toolbar_btn.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable-hdpi/common_toolbar_btn_small.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable-hdpi/form_row_input_middle.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable-hdpi/form_row_input_middle_short_left.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable-hdpi/form_row_input_middle_short_right.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable-hdpi/form_row_input_top.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable-hdpi/income_tab_btn_radio.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable-hdpi/main_add_expense_quickly.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable-hdpi/main_row_stat.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/drawable-hdpi/payout_tab_btn_radio.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/layout/about.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/layout/account.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/layout/incomedata.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/layout/notification_item.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/layout/pay.xml ================================================ ================================================ FILE: MoneyCharge/app/src/main/res/layout/paychart.xml ================================================