com.socks.library.KLog Java Examples

The following examples show how to use com.socks.library.KLog. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DBManager.java    From ZZShow with Apache License 2.0 6 votes vote down vote up
/**
 * 根据条件查询记录条数
 *
 * @param selection    条件
 * @param selectionArgs  值
 * @return
 */
public long getCountByWhere(String selection,String[] selectionArgs){
    db.beginTransaction();
    long count = 0;
    Cursor cursor = null;
    try {
        cursor = db.rawQuery("select count(news_channel_id) from " + DBHelper.TABLE_NEWS_CHANNEL + " where " + selection,selectionArgs);
        cursor.moveToFirst();
        count = cursor.getLong(0);
        db.setTransactionSuccessful();
    }catch (Exception e){
        KLog.e(e.getMessage());
    }finally {
        if(cursor != null) cursor.close();
        db.endTransaction();
    }
    return count;
}
 
Example #2
Source File: CircleBaseViewHolder.java    From star-zone-android with Apache License 2.0 6 votes vote down vote up
@Override
public void onBindData(MomentInfo data, int position) {
    if (data == null) {
        KLog.e("数据是空的!!!!");
        findView(userText, R.id.item_text_field);
        userText.setText("这个动态的数据是空的。。。。OMG");
        return;
    }
    this.momentInfo = data;
    this.itemPosition = position;
    //通用数据绑定
    onBindMutualDataToViews(data);
    //点击事件
    menuButton.setOnClickListener(onMenuButtonClickListener);
    menuButton.setTag(R.id.momentinfo_data_tag_id, data);
    deleteMoments.setOnClickListener(onDeleteMomentClickListener);
    //传递到子类
    onBindDataToView(data, position, getViewType());
}
 
Example #3
Source File: DefaultGlideModule.java    From star-zone-android with Apache License 2.0 6 votes vote down vote up
@Override
public void applyOptions(Context context, GlideBuilder builder) {
    //磁盘缓存
    builder.setDiskCache(new DiskLruCacheFactory(context.getCacheDir().getAbsolutePath(), 50 * 1024 * 1024));
    KLog.d("Glide", "glide cache file path  >>>  " + context.getCacheDir().getAbsolutePath());
    //内存缓存
    MemorySizeCalculator calculator = new MemorySizeCalculator.Builder(context).build();
    int defaultMemoryCacheSize = calculator.getMemoryCacheSize();
    int defaultBitmapPoolSize = calculator.getBitmapPoolSize();
    //设置比默认大小大1.5倍的缓存和图片池大小
    int customMemoryCacheSize = (int) (1.5 * defaultMemoryCacheSize);
    int customBitmapPoolSize = defaultBitmapPoolSize;

    builder.setMemoryCache(new LruResourceCache(customMemoryCacheSize));
    builder.setBitmapPool(new LruBitmapPool(customBitmapPoolSize));


    KLog.d("Glide", "bitmapPoolSize >>>>>   " +
            formatFileSize(context, customBitmapPoolSize) +
            " / memorySize>>>>>>>>   " +
            formatFileSize(context, customMemoryCacheSize));

    builder.setLogLevel(Log.ERROR);
}
 
Example #4
Source File: FileUtil.java    From star-zone-android with Apache License 2.0 6 votes vote down vote up
/**
 * 调用系统打开文件
 */
public static boolean openFile(File file, Context context) {
    Intent intent = new Intent();
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    // 设置intent的Action属性
    intent.setAction(Intent.ACTION_VIEW);
    // 获取文件file的MIME类型
    String type = getMIMEType(file);
    // 设置intent的data和Type属性。
    intent.setDataAndType(Uri.fromFile(file), type);
    // 跳转
    try {
        ((Activity) context).startActivity(intent);
    } catch (ActivityNotFoundException e) {
        KLog.e(e);
        return false;
    }
    return true;
}
 
Example #5
Source File: SplashActivity.java    From ZZShow with Apache License 2.0 6 votes vote down vote up
private void startLogoOuterAndAppName() {
    final ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, 1);
    valueAnimator.setDuration(1000);
    valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            float fraction = animation.getAnimatedFraction();
            KLog.d("fraction: " + fraction);
            if (fraction >= 0.8 && !isShowingRubberEffect) {
                isShowingRubberEffect = true;
                startLogoOuter();
                startShowAppName();
                finishActivity();
            } else if (fraction >= 0.95) {
                valueAnimator.cancel();
                startLogoInner2();
            }

        }
    });
    valueAnimator.start();
}
 
Example #6
Source File: NewsFragment.java    From ZZShow with Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }
    mSubscription = RxBus.getInstance().toObservable(ChannelChangeEvent.class)
            .subscribe(new Action1<ChannelChangeEvent>() {
                @Override
                public void call(ChannelChangeEvent channelChangeEvent) {
                    KLog.d("NewsChannelPresenterImpl","GET ---------------");
                    if(channelChangeEvent.isChannelChanged()) {
                        mPresenter.loadNewsChannels();
                        if(channelChangeEvent.getChannelName() != null) {
                            mCurrentViewPagerName = channelChangeEvent.getChannelName();
                        }
                    }else{
                        if(channelChangeEvent.getChannelName() != null) {
                            mCurrentViewPagerName = channelChangeEvent.getChannelName();
                            mViewPager.setCurrentItem(getCurrentViewPagerPosition());
                        }
                    }
                }
            });
}
 
Example #7
Source File: DBManager.java    From ZZShow with Apache License 2.0 6 votes vote down vote up
/**
 * 修改
 * @param channelTable 对象
 */
public int update (NewsChannelTable channelTable){
    db.beginTransaction();
    int index = -1;
    try {
        ContentValues values = new ContentValues();
        values.put("news_channel_name", channelTable.getNewsChannelName());
        values.put("news_channel_id", channelTable.getNewsChannelId());
        values.put("news_channel_type", channelTable.getNewsChannelType());
        values.put("news_channel_select", channelTable.isNewsChannelSelect() ? 1:0);
        values.put("news_channel_index", channelTable.getNewsChannelIndex());
        values.put("news_channel_fixed", channelTable.isNewsChannelFixed()? 1:0);
        index = db.update(DBHelper.TABLE_NEWS_CHANNEL,values,"news_channel_id = ?",new String[]{channelTable.getNewsChannelId()});
        db.setTransactionSuccessful();
    }catch (Exception e){
        KLog.e(e.getMessage());
    }finally {
        db.endTransaction();
    }
    return index;
}
 
Example #8
Source File: CartFragment.java    From BitkyShop with MIT License 6 votes vote down vote up
/**
 * 更新全选复选框的状态
 */
private void updateCheckedAll() {
  Boolean isCheckedAll = true;
  if (commodityLocals == null || commodityLocals.size() == 0) {
    isCheckedAll = false;
  } else {
    for (CommodityLocal commodityLocal : commodityLocals) {
      if (!commodityLocal.getCartIsChecked()) {
        isCheckedAll = false;
        break;
      }
    }
  }
  KLog.d("isCheckedAll+" + isCheckedAll);
  checkBoxAll.setChecked(isCheckedAll);
}
 
Example #9
Source File: FileUtil.java    From star-zone-android with Apache License 2.0 6 votes vote down vote up
/**
 * 写入文件
 *
 * @param strFileName 文件名
 * @param ins         流
 */
public static void writeToFile(String strFileName, InputStream ins) {
    try {
        File file = new File(strFileName);

        FileOutputStream fouts = new FileOutputStream(file);
        int len;
        int maxSize = 1024 * 1024;
        byte buf[] = new byte[maxSize];
        while ((len = ins.read(buf, 0, maxSize)) != -1) {
            fouts.write(buf, 0, len);
            fouts.flush();
        }

        fouts.close();
    } catch (IOException e) {
        KLog.e(e);
    }
}
 
Example #10
Source File: FileUtil.java    From star-zone-android with Apache License 2.0 6 votes vote down vote up
/**
 * 复制单个文件
 *
 * @param oldPath String 原文件路径
 * @param newPath String 复制后路径
 * @return boolean
 */
public static boolean copyFile(String oldPath, String newPath) {
    try {
        int byteread = 0;
        File oldfile = new File(oldPath);
        if (oldfile.exists()) { // 文件存在时
            InputStream inStream = new FileInputStream(oldPath); // 读入原文件
            FileOutputStream fs = new FileOutputStream(newPath);
            byte[] buffer = new byte[IO_BUFFER_SIZE];

            while ((byteread = inStream.read(buffer)) != -1) {
                fs.write(buffer, 0, byteread);
            }
            inStream.close();
            fs.close();
        }
    } catch (Exception e) {
        KLog.e(e);
        return false;
    }
    return true;
}
 
Example #11
Source File: XmlLog.java    From KLog with Apache License 2.0 6 votes vote down vote up
public static void printXml(String tag, String xml, String headString) {

        if (xml != null) {
            xml = XmlLog.formatXML(xml);
            xml = headString + "\n" + xml;
        } else {
            xml = headString + KLog.NULL_TIPS;
        }

        KLogUtil.printLine(tag, true);
        String[] lines = xml.split(KLog.LINE_SEPARATOR);
        for (String line : lines) {
            if (!KLogUtil.isEmpty(line)) {
                Log.d(tag, "║ " + line);
            }
        }
        KLogUtil.printLine(tag, false);
    }
 
Example #12
Source File: PhotoBrowseActivity.java    From star-zone-android with Apache License 2.0 6 votes vote down vote up
@Override
public void finish() {
    final GalleryPhotoView currentPhotoView = viewBuckets.get(photoViewpager.getCurrentItem());
    if (currentPhotoView == null) {
        KLog.e(TAG, "childView is null");
        super.finish();
        return;
    }
    final Rect endRect = photoBrowseInfo.getViewLocalRects().get(photoViewpager.getCurrentItem());
    currentPhotoView.playExitAnima(endRect, blackBackground, new GalleryPhotoView.OnExitAnimaEndListener() {
        @Override
        public void onExitAnimaEnd() {
            PhotoBrowseActivity.super.finish();
            overridePendingTransition(0, 0);
        }
    });
}
 
Example #13
Source File: HeaderViewWrapperAdapter.java    From star-zone-android with Apache License 2.0 6 votes vote down vote up
public HeaderViewWrapperAdapter(RecyclerView recyclerView,
                                @NonNull RecyclerView.Adapter mWrappedAdapter,
                                ArrayList<FixedViewInfo> mHeaderViewInfos,
                                ArrayList<FixedViewInfo> mFooterViewInfos) {
    this.recyclerView = recyclerView;
    this.mWrappedAdapter = mWrappedAdapter;
    try {
        mWrappedAdapter.registerAdapterDataObserver(mDataObserver);
    }catch (IllegalStateException e){
        //maybe observer is added
        KLog.w(e);
    }
    if (mHeaderViewInfos == null) {
        this.mHeaderViewInfos = EMPTY_INFO_LIST;
    } else {
        this.mHeaderViewInfos = mHeaderViewInfos;
    }
    if (mFooterViewInfos == null) {
        this.mFooterViewInfos = EMPTY_INFO_LIST;
    } else {
        this.mFooterViewInfos = mFooterViewInfos;
    }
}
 
Example #14
Source File: MainActivity.java    From OkHttpPlus with Apache License 2.0 6 votes vote down vote up
public void downloadFile(View view) {

        String desFileDir = Environment.getExternalStorageDirectory().getAbsolutePath();
        OkHttpProxy.download(URL_DOWMLOAD, new DownloadListener(desFileDir, "json.jar") {

            @Override
            public void onUIProgress(Progress progress) {
                //当下载资源长度不可知时,progress.getTotalBytes()为-1,此时不能显示下载进度
                int pro = (int) (progress.getCurrentBytes() / progress.getTotalBytes() * 100);
                if (pro > 0) {
                    pb.setProgress(pro);
                }
                KLog.d("pro = " + pro + " getCurrentBytes = " + progress.getCurrentBytes() + " getTotalBytes = " + progress.getTotalBytes());
            }

            @Override
            public void onSuccess(File file) {
                tv_response.setText(file.getAbsolutePath());
            }

            @Override
            public void onFailure(Exception e) {
                tv_response.setText(e.getMessage());
            }
        });
    }
 
Example #15
Source File: SearchActivity.java    From BitkyShop with MIT License 6 votes vote down vote up
private void searchCommodity() {
  ((InputMethodManager) context.getSystemService(
      Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(searchEdittext.getWindowToken(),
      InputMethodManager.HIDE_NOT_ALWAYS);
  String msg = searchEdittext.getText().toString().trim();
  if (msg.equals("")) {
    toastUtil.show("请输入要搜索的商品");
    return;
  }
  BmobQuery<Commodity> bmobQuery = new BmobQuery<>();
  bmobQuery.addWhereEqualTo("categorySub", msg);
  KLog.d(msg);
  bmobQuery.findObjects(new FindListener<Commodity>() {
    @Override public void done(List<Commodity> list, BmobException e) {
      if (e != null) {
        KLog.d(e.getMessage());
      }
      if (list != null) {
        KLog.d(list.size());
      }
    }
  });
}
 
Example #16
Source File: JsonLog.java    From KLog with Apache License 2.0 6 votes vote down vote up
public static void printJson(String tag, String msg, String headString) {

        String message;

        try {
            if (msg.startsWith("{")) {
                JSONObject jsonObject = new JSONObject(msg);
                message = jsonObject.toString(KLog.JSON_INDENT);
            } else if (msg.startsWith("[")) {
                JSONArray jsonArray = new JSONArray(msg);
                message = jsonArray.toString(KLog.JSON_INDENT);
            } else {
                message = msg;
            }
        } catch (JSONException e) {
            message = msg;
        }

        KLogUtil.printLine(tag, true);
        message = headString + KLog.LINE_SEPARATOR + message;
        String[] lines = message.split(KLog.LINE_SEPARATOR);
        for (String line : lines) {
            Log.d(tag, "║ " + line);
        }
        KLogUtil.printLine(tag, false);
    }
 
Example #17
Source File: OrderActivity.java    From BitkyShop with MIT License 5 votes vote down vote up
private void initRecyclerOrderData(List<CommodityOrder> commodityOrders) {
  //用于从服务器请求得到的商品信息
  commodities = new ArrayList<>();
  //用于提交到服务器中的订单中的商品信息
  commodityOrderSubmitList = new ArrayList<>();

  for (final CommodityOrder commodityOrder : commodityOrders) {
    BmobQuery<Commodity> bmobQuery = new BmobQuery<>();
    bmobQuery.getObject(commodityOrder.getObjectId(), new QueryListener<Commodity>() {
      @Override public void done(Commodity commodity, BmobException e) {
        if (e != null) {
          KLog.d("有异常:" + e.getMessage());
          return;
        }
        if (commodity.getCount() <= 0 && currentStatus == KySet.CART_REQUEST_SUBMIT_ORDER) {
          return;
        }
        KLog.d("读取成功,objectId:" + commodity.getObjectId() + "," + commodity.getName());
        commodity.setCount(commodityOrder.getCount());
        commodities.add(commodity);
        commodityOrderSubmitList.add(commodityOrder);
        recyclerAdapter.reloadData(commodities);
        countTotalPrices();
      }
    });
  }
}
 
Example #18
Source File: AddressOptionActivity.java    From BitkyShop with MIT License 5 votes vote down vote up
/**
 * 从云端读入的数据
 *
 * @param receiveList 完全正确的数据
 */
public void initReceiveAddress(List<ReceiveAddress> receiveList) {
  if (receiveList != null && receiveList.size() > 0) {
    KLog.d("reloadData");
    recyclerAdapter.reloadData(receiveList);
  }
}
 
Example #19
Source File: PhotoTextView.java    From ZZShow with Apache License 2.0 5 votes vote down vote up
/**
 *  解绑ImageGetterSubscription
 */
public void cancelImageGetterSubscription(){
    if(imgGetter != null){
        try {
            imgGetter.unSubscribe();
        }catch (Exception e){
            KLog.e("解绑 UrlImageGetter Subscription 异常");
        }
    }
}
 
Example #20
Source File: MainActivity.java    From KLog with Apache License 2.0 5 votes vote down vote up
public void logWithTag(View view) {
    KLog.v(TAG, LOG_MSG);
    KLog.d(TAG, LOG_MSG);
    KLog.i(TAG, LOG_MSG);
    KLog.w(TAG, LOG_MSG);
    KLog.e(TAG, LOG_MSG);
    KLog.a(TAG, LOG_MSG);
}
 
Example #21
Source File: HomeFragment.java    From BitkyShop with MIT License 5 votes vote down vote up
@Override
public void initRecyclerViewData(List<Commodity> list) {
    recyclerAdapter =
        new KyBaseRecyclerAdapter<Commodity>(list, R.layout.recycler_homefragment_show) {

            @Override
            public void setDataToViewHolder(final Commodity dataItem, KyBaseViewHolder holder) {
                holder.getSimpleDraweeView(R.id.recycler_homeshow_draweeview)
                    .setImageURI(Uri.parse(dataItem.getCoverPhotoUrl()));
                holder.getTextView(R.id.recycler_homeshow_text_title).setText(dataItem.getName());
                holder.getTextView(R.id.recycler_homeshow_text_price)
                    .setText(dataItem.getPrice().toString() + " 元");
                holder.getButton(R.id.recycler_homeshow_btn_addCart)
                    .setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            GreenDaoKyHelper.insertOrIncrease(dataItem);
                            toastUtil.show("已添加到购物车");
                            KLog.json(new Gson().toJson(GreenDaoKyHelper.queryAll()));
                        }
                    });
            }
        };
    recyclerAdapter.setOnClickListener(
        new KyBaseRecyclerAdapter.KyRecyclerViewItemOnClickListener<Commodity>() {
            @Override
            public void Onclick(View v, int adapterPosition, Commodity data) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("commodity", data);
                Intent intent = new Intent(mContext, CommodityDetailActivity.class);
                intent.putExtra("bundle", bundle);
                startActivity(intent);
            }
        });
}
 
Example #22
Source File: BaseActivity.java    From star-zone-android with Apache License 2.0 5 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    KLog.i("当前打开 :  " + this.getClass().getSimpleName());
    if (mPermissionHelper == null) {
        mPermissionHelper = new PermissionHelper(this);
    }
    ARouter.getInstance().inject(this);
    onHandleIntent(getIntent());
}
 
Example #23
Source File: HomeActivity.java    From ZZShow with Apache License 2.0 5 votes vote down vote up
@Override
public void initVariables() {
    KLog.d("NightMode"," - initVariables - ");
    mNewsFragment = new NewsFragment();
    mVideoFragment = new VideoFragment();
    mPhotoFragment = new PhotoFragment();
}
 
Example #24
Source File: NewsListFragment.java    From ZZShow with Apache License 2.0 5 votes vote down vote up
@Override
public void OnItemClickListener(View view, int position) {
    List<NewsSummary> mNewsSummaryList = mAdapter.getList();
    NewsSummary newsSummary = mNewsSummaryList.get(position);
    if(NewsListAdapter.TYPE_PHOTO_SET == mAdapter.getItemViewType(position)){
        NewsPhotoDetail mNewsPhotoDetail = setNewsPhotoDetail(newsSummary);
        startActivity(NewsPhotoDetailActivity.getNewsDetailIntent(getActivity(),mNewsPhotoDetail));
        KLog.d(TAG,"postId = " + newsSummary.getPostid() +"--- postSetId= "+ newsSummary.getPhotosetID());
    }else{
        Intent intent = NewsDetailActivity.getNewsDetailIntent(getActivity(),newsSummary.getPostid(),newsSummary.getImgsrc());
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ImageView animationIv = (ImageView) view.findViewById(R.id.news_picture_iv);
            ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(
                    getActivity(),
                    animationIv,
                    Constants.TRANSITION_ANIMATION_NEWS_PHOTOS);
            startActivity(intent,options.toBundle());
        }else{
            ActivityOptionsCompat optionsCompat = ActivityOptionsCompat.makeScaleUpAnimation(
                    view,
                    view.getWidth() / 2,
                    view.getHeight() / 2,
                    0,
                    0);
            ActivityCompat.startActivity(getActivity(),intent,optionsCompat.toBundle());
        }
    }
}
 
Example #25
Source File: NewsListFragment.java    From ZZShow with Apache License 2.0 5 votes vote down vote up
@Override
protected void initData() {
    mPresenter.setNewsTypeAndId(mNewsChannelType, mNewsChannelId);
    KLog.d(TAG,"initPresenter - mNewsChannelIndex = "+ mNewsChannelIndex);
    if(getUserVisibleHint()){
        KLog.d(TAG,"initPresenter - mNewsChannelIndex = "+ mNewsChannelIndex + " -- onCreate");
        mPresenter.onCreate();
    }
}
 
Example #26
Source File: DateUtil.java    From ZZShow with Apache License 2.0 5 votes vote down vote up
/**
 * from yyyy-MM-dd HH:mm:ss to MM-dd HH:mm
 * @param before 时间戳
 * @return  日期
 */
public static String formatDate(String before){
    String after;
    try {
        Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).parse(before);
        after = new SimpleDateFormat("MM-dd HH:mm",Locale.getDefault()).format(date);
    } catch (ParseException e) {
        KLog.e("转换新闻日期格式异常:" + e.toString());
        return before;
    }
    return after;
}
 
Example #27
Source File: OkHttpUtil.java    From ZZShow with Apache License 2.0 5 votes vote down vote up
@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    long t1 = System.nanoTime();
    KLog.i(String.format("Sending request %s on %s%n%s",request.url(),chain.connection(),request.headers()));
    Response response = chain.proceed(request);
    long t2 = System.nanoTime();
    KLog.i(String.format(Locale.getDefault(),"Received response for %s in %.1fms%n%s",
            response.request().url(),(t2 - t1)/1e6d,response.headers()));
    return response;
}
 
Example #28
Source File: PhotoSelectActivity.java    From star-zone-android with Apache License 2.0 5 votes vote down vote up
private void initFrag() {
    if (gridFragement == null) {
        KLog.i(TAG, "maxCount = " + maxCount);
        gridFragement = PhotoGridFragement.newInstance(maxCount);
    }
    if (albumFragement == null) {
        albumFragement = new PhotoAlbumFragement();
    }
    changeFragment(currentFragment, gridFragement, false);
}
 
Example #29
Source File: PhotoGridFragement.java    From star-zone-android with Apache License 2.0 5 votes vote down vote up
private void scanImgSyncWithProgress() {
    AppSetting.saveBooleanPreferenceByKey(AppSetting.APP_HAS_SCAN_IMG, true);
    final PopupProgress popupProgress = new PopupProgress(getActivity());
    popupProgress.setProgressTips("正在扫描系统相册...");
    LocalPhotoManager.INSTANCE.scanImg(new LocalPhotoManager.OnScanProgresslistener() {

        @Override
        public void onStart() {
            popupProgress.showPopupWindow();
            popupProgress.setProgress(0);
            KLog.i(TAG, "onStart");
        }

        @Override
        public void onProgress(int progress) {
            popupProgress.setProgress(progress);
        }

        @Override
        public void onFinish() {
            KLog.i(TAG, "onFinish");
            AppSetting.saveBooleanPreferenceByKey(AppSetting.APP_HAS_SCAN_IMG, true);
            popupProgress.dismiss();
            initView();
        }

        @Override
        public void onError(LPException e) {
            KLog.e(TAG, e);
            UIHelper.ToastMessage(e.getMessage());
            popupProgress.dismiss();
        }
    });
}
 
Example #30
Source File: CheckImageView.java    From star-zone-android with Apache License 2.0 5 votes vote down vote up
private void init(Context context) {
    checkDrawable = new CheckDrawable(context);
    checkDrawable.setCallback(this);

    setOnTouchListener(new OnTouchListener() {
        int x = 0;
        int y = 0;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    x = (int) event.getX();
                    y = (int) event.getY();
                    return touchRectDelegate.contains(x, y);
                case MotionEvent.ACTION_UP:
                    if (touchRectDelegate.contains(x, y) && canSelect) {
                        isSelected = checkDrawable.toggleSelected();
                        if (onSelectedChangeListener != null) {
                            KLog.i(TAG, "on touch up");
                            onSelectedChangeListener.onSelectChange(isSelected);
                        }
                        invalidate();
                        return true;
                    }
                    break;
            }
            return false;
        }
    });
}