Example #1
0
  private void setOnClickListener(final MessageItem msgItem) {
    switch (msgItem.mAttachmentType) {
      case WorkingMessage.IMAGE:
      case WorkingMessage.VIDEO:
        mImageView.setOnClickListener(
            new OnClickListener() {
              @Override
              public void onClick(View v) {
                sendMessage(msgItem, MSG_LIST_PLAY);
              }
            });
        mImageView.setOnLongClickListener(
            new OnLongClickListener() {
              @Override
              public boolean onLongClick(View v) {
                return v.showContextMenu();
              }
            });
        break;

      default:
        mImageView.setOnClickListener(null);
        break;
    }
  }
  @Override
  public View onCreateView(
      LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_personal_info, container, false);
    mHeaderView = rootView.findViewById(R.id.header);
    mTopImageView = (ImageView) rootView.findViewById(R.id.theme_top_image);
    mTopImageView.setOnLongClickListener(this);
    displayThemeImages();
    mAvatarImage = (ImageView) rootView.findViewById(R.id.avatar_image);
    MiscUtils.showAvatarThumb(
        mAvatarManager,
        mSettingHelper.getAccountAvatarThumb(),
        mAvatarImage,
        R.drawable.contact_single);
    mAvatarImage.setOnClickListener(this);
    mListView = (ListView) rootView.findViewById(R.id.list);
    View listHeader = inflater.inflate(R.layout.personal_info_list_header, mListView, false);
    mListHeaderView = listHeader;
    mListView.addHeaderView(listHeader);
    mListView.setAdapter(mInfoAdapter);
    mListView.setOnItemClickListener(mInfoAdapter);
    mListView.setOnScrollListener(
        new AbsListView.OnScrollListener() {
          @Override
          public void onScrollStateChanged(AbsListView view, int scrollState) {}

          @Override
          public void onScroll(
              AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            ViewHelper.setTranslationY(
                mHeaderView, Math.max(-getScrollY(), -mHeaderView.getMeasuredHeight()));
          }
        });
    return rootView;
  }
 @Override
 public void setOnLongClickListener(OnLongClickListener l) {
   mSignButton.setOnLongClickListener(l);
   if (mImageView != null) {
     mImageView.setOnLongClickListener(l);
   }
 }
 public MyViewHolder(View itemView) {
   super(itemView);
   itemTV = (TextView) itemView.findViewById(R.id.itemRecyclerText);
   imageV = (ImageView) itemView.findViewById(R.id.listIcon);
   locationTV = (TextView) itemView.findViewById(R.id.itemLocationRecyclerText);
   imageV.setOnLongClickListener(this);
   quantityTV = (TextView) itemView.findViewById(R.id.itemQuantTextView);
 }
 @Override
 public void setOnLongClickListener(OnLongClickListener l) {
   mCaptureButton.setOnLongClickListener(l);
   mChooseButton.setOnLongClickListener(l);
   if (mImageView != null) {
     mImageView.setOnLongClickListener(l);
   }
 }
Example #6
0
  /**
   * 牙牙表情等gif类型的消息: 1. 设定内容Emoparser 2. 点击事件 单击跳转、 双击方法、长按pop menu 点击头像的事件 跳转
   *
   * @param position
   * @param convertView
   * @param viewGroup
   * @param isMine
   * @return
   */
  private View gifMsgRender(
      final int position, View convertView, final ViewGroup viewGroup, final boolean isMine) {
    EmojiRenderView gifRenderView;
    final TextMessage textMessage = (TextMessage) msgObjectList.get(position);
    UserEntity userEntity = imService.getContactManager().findContact(textMessage.getFromId());
    if (null == convertView) {
      gifRenderView =
          EmojiRenderView.inflater(
              ctx, viewGroup, isMine); // new TextRenderView(ctx,viewGroup,isMine);
    } else {
      gifRenderView = (EmojiRenderView) convertView;
    }

    final ImageView imageView = gifRenderView.getMessageContent();
    // 失败事件添加
    gifRenderView
        .getMessageFailed()
        .setOnClickListener(
            new View.OnClickListener() {
              @Override
              public void onClick(View arg0) {
                MessageOperatePopup popup =
                    getPopMenu(viewGroup, new OperateItemClickListener(textMessage, position));
                popup.show(imageView, DBConstant.SHOW_GIF_TYPE, true, isMine);
              }
            });

    imageView.setOnLongClickListener(
        new View.OnLongClickListener() {
          @Override
          public boolean onLongClick(View v) {
            MessageOperatePopup popup =
                getPopMenu(viewGroup, new OperateItemClickListener(textMessage, position));
            boolean bResend = textMessage.getStatus() == MessageConstant.MSG_FAILURE;
            popup.show(imageView, DBConstant.SHOW_GIF_TYPE, bResend, isMine);

            return true;
          }
        });

    imageView.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View arg0) {
            final String content = textMessage.getContent();
            Intent intent = new Intent(ctx, PreviewGifActivity.class);
            intent.putExtra(IntentConstant.PREVIEW_TEXT_CONTENT, content);
            ctx.startActivity(intent);
            ((Activity) ctx).overridePendingTransition(R.anim.tt_image_enter, R.anim.tt_stay);
          }
        });

    gifRenderView.render(textMessage, userEntity, ctx);
    return gifRenderView;
  }
Example #7
0
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
          ImageVO vo = imageList.get(position);
          View view = getLayoutInflater().inflate(R.layout.layout_image, null);
          final ImageView ivImage = (ImageView) view.findViewById(R.id.iv_image);
          ivImage.setTag(position);
          ivImage.setOnLongClickListener(
              new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {

                  return false;
                }
              });
          final ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
          Utils.displayImage(
              vo.getUrl(),
              ivImage,
              options,
              new ImageLoadingListener() {
                @Override
                public void onLoadingStarted(String imageUri, View view) {
                  progressBar.setVisibility(View.VISIBLE);
                }

                @Override
                public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                  progressBar.setVisibility(View.GONE);
                  ivImage.setVisibility(View.VISIBLE);
                }

                @Override
                public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                  progressBar.setVisibility(View.GONE);
                  // 重新计算图片宽和高  screenWidth    imageWidth
                  //                   xxxx           imageHeight
                  int screenWidth = Utils.getScreenWidth(ImageActivity.this);
                  int ivHeight = screenWidth * loadedImage.getHeight() / loadedImage.getWidth();
                  RelativeLayout.LayoutParams params =
                      new RelativeLayout.LayoutParams(
                          RelativeLayout.LayoutParams.MATCH_PARENT, ivHeight);
                  params.addRule(RelativeLayout.CENTER_IN_PARENT);
                  ivImage.setLayoutParams(params);
                  ivImage.setVisibility(View.VISIBLE);
                }

                @Override
                public void onLoadingCancelled(String imageUri, View view) {
                  progressBar.setVisibility(View.GONE);
                }
              });
          container.addView(view, 0);
          return view;
        }
Example #8
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    user = ParseUser.getCurrentUser();
    status = (String) user.get(getString(R.string.status));

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("");
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);

    mDrawerList = (ListView) findViewById(R.id.navList);
    mCardview = (CardView) findViewById(R.id.nav_card_view);
    addDrawerItems();
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mActivityTitle = getTitle().toString();
    mDrawerList.setOnItemClickListener(
        new AdapterView.OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (position == 0 || position == 1) displyDialog(position);
          }
        });
    setupDrawer();
    mTextview = (TextView) findViewById(R.id.nav_text_view);
    mTextview.setText(user.get("fullName").toString() + "\n" + user.getUsername());

    mImageView = (ImageView) findViewById(R.id.nav_pic);
    mImageView.setImageResource(R.drawable.person_default_image);

    mImageView.setOnLongClickListener(
        new View.OnLongClickListener() {
          @Override
          public boolean onLongClick(View v) {

            Intent i =
                new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            startActivityForResult(i, RESULT_LOAD_IMAGE);
            return false;
          }
        });
  }
Example #9
0
 @Override
 public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   super.requestWindowFeature(Window.FEATURE_NO_TITLE);
   super.getWindow()
       .setFlags(
           WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
   super.setContentView(R.layout.sys_chgbg);
   chgbg_bg = (TextView) super.findViewById(R.id.chgbg_bg);
   chgbg_img = (ImageView) super.findViewById(R.id.chgbg_img);
   chgbg_img.setOnLongClickListener(this);
   Toast.makeText(this, "全屏设置", Toast.LENGTH_SHORT).show();
 }
Example #10
0
 @Override
 public void setOnLongClickListener(OnLongClickListener l) {
     mQuestionText.setOnLongClickListener(l);
     if (mMissingImage != null) {
         mMissingImage.setOnLongClickListener(l);
     }
     if (mImageView != null) {
         mImageView.setOnLongClickListener(l);
     }
     if (label != null) {
         label.setOnLongClickListener(l);
     }
 }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mToast = Toast.makeText(this, "", Toast.LENGTH_LONG);
    mToast.setView(makeView());

    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);

    mContent = new ImageView(this);
    mContent.setImageResource(R.drawable.palogo);
    mContent.setScaleType(ImageView.ScaleType.CENTER_INSIDE);

    final int p = (int) (32 * metrics.density);
    mContent.setPadding(p, p, p, p);

    mContent.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            mToast.show();
          }
        });

    mContent.setOnLongClickListener(
        new View.OnLongClickListener() {
          @Override
          public boolean onLongClick(View v) {
            try {
              startActivity(
                  new Intent(Intent.ACTION_MAIN)
                      .setFlags(
                          Intent.FLAG_ACTIVITY_NEW_TASK
                              | Intent.FLAG_ACTIVITY_CLEAR_TASK
                              | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
                      .setClassName(
                          "com.android.settings", "com.android.settings.paranoid.PACircus"));
            } catch (ActivityNotFoundException ex) {
              android.util.Log.e("PALogoActivity", "Couldn't find a circus of PA's.");
            }
            finish();
            return true;
          }
        });

    setContentView(mContent);
  }
Example #12
0
 public ImageView createImageView(int i, String url) {
   LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
   lp.weight = 1;
   ImageView image = new ImageView(getContext());
   image.setLayoutParams(lp);
   image.setScaleType(ScaleType.CENTER_CROP);
   image.setId(i);
   image.setTag(i);
   image.setOnClickListener(imgClick);
   image.setOnLongClickListener(longClick);
   if (imgList.size() < 3 || (imgList.size() < 4 && i == 0)) {
     ImageLoader.getInstance().displayImage(url + StaticFactory._600x600, image, options_defalut);
   } else {
     ImageLoader.getInstance().displayImage(url + StaticFactory._320x320, image, options_defalut);
   }
   return image;
 }
  private void addThumbnail(
      LinearLayout container,
      Bitmap bm,
      final ActivityManager.RecentTaskInfo task,
      final ActivityManager.TaskThumbnail thumbs) {
    ImageView iv = new ImageView(this);
    if (bm != null) {
      iv.setImageBitmap(bm);
    }
    iv.setBackgroundResource(android.R.drawable.gallery_thumb);
    int w = getResources().getDimensionPixelSize(android.R.dimen.thumbnail_width);
    int h = getResources().getDimensionPixelSize(android.R.dimen.thumbnail_height);
    container.addView(iv, new LinearLayout.LayoutParams(w, h));

    iv.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            if (task.id >= 0 && thumbs != null) {
              mAm.moveTaskToFront(task.id, ActivityManager.MOVE_TASK_WITH_HOME);
            } else {
              try {
                startActivity(task.baseIntent);
              } catch (ActivityNotFoundException e) {
                Log.w("foo", "Unable to start task: " + e);
              }
            }
            buildUi();
          }
        });
    iv.setOnLongClickListener(
        new View.OnLongClickListener() {
          @Override
          public boolean onLongClick(View v) {
            if (task.id >= 0 && thumbs != null) {
              mAm.removeTask(task.id);
              buildUi();
              return true;
            }
            return false;
          }
        });
  }
  private RelativeLayout createImage(String path, int id, final String bigPath) {
    RelativeLayout relativeLayout = new RelativeLayout(context);
    LayoutParams layoutParams =
        new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    layoutParams.gravity = Gravity.CENTER;
    layoutParams.leftMargin = width / 55;
    layoutParams.weight = 1;
    relativeLayout.setLayoutParams(layoutParams);
    ImageView imageView = new ImageView(context);
    imageView.setId(id);
    imageView.setOnLongClickListener(this);
    imageView.setOnClickListener(
        new OnClickListener() {

          @Override
          public void onClick(View v) {
            // 展示大图片
            BigImageActivity.setViewData(bigPath);
            startActivity(new Intent(CaseTestActivity.this, BigImageActivity.class));
          }
        });
    LayoutParams imageViewParams = new LayoutParams(width / 15 * 4, width / 15 * 4);
    imageView.setLayoutParams(imageViewParams);
    imageView.setScaleType(ScaleType.CENTER_CROP);
    if (!"null".equals(path) && !"".equals(path)) {
      if (path.startsWith("http:")) {
        imageView.setTag(path);
        imageView.setImageResource(R.anim.loading_anim_test);
        ImageListener listener =
            ImageLoader.getImageListener(imageView, 0, android.R.drawable.ic_menu_delete);
        mImageLoader.get(path, listener, 200, 200);
      } else {
        Bitmap bitmap = CommonUtil.readBitMap(200, path);
        imageView.setImageBitmap(bitmap);
      }
    }
    relativeLayout.addView(imageView);
    return relativeLayout;
  }
  /**
   * Method that create a new frame to be drawn in the specified location
   *
   * @param r The location relative to the parent layout
   * @return v The new view
   */
  private View createFrame(Rect r, boolean animate) {
    int padding = (int) getResources().getDimension(R.dimen.disposition_frame_padding);
    final ImageView v = new ImageView(getContext());
    v.setImageResource(R.drawable.ic_camera);
    v.setScaleType(ScaleType.CENTER);

    // Is locked? Then change the background color
    v.setBackgroundColor(
        getResources()
            .getColor(
                mResizeFrame == null
                    ? R.color.disposition_locked_frame_bg_color
                    : R.color.disposition_frame_bg_color));

    RelativeLayout.LayoutParams params =
        new RelativeLayout.LayoutParams(r.width() - padding, r.height() - padding);
    v.setX(r.left + padding);
    v.setY(r.top + padding);
    v.setOnLongClickListener(this);
    addView(v, params);

    // Animate the view
    if (animate) {
      List<Animator> animators = new ArrayList<Animator>();
      animators.add(ObjectAnimator.ofFloat(v, "scaleX", 0.0f, 1.0f));
      animators.add(ObjectAnimator.ofFloat(v, "scaleY", 0.0f, 1.0f));
      animators.add(ObjectAnimator.ofFloat(v, "alpha", 0.0f, 1.0f));
      animators.add(ObjectAnimator.ofFloat(v, "alpha", 0.0f, 1.0f));

      AnimatorSet animSet = new AnimatorSet();
      animSet.playTogether(animators);
      animSet.setDuration(getResources().getInteger(R.integer.disposition_show_anim));
      animSet.setInterpolator(new BounceInterpolator());
      animSet.setTarget(v);
      animSet.start();
    }

    return v;
  }
Example #16
0
  @SuppressLint("InflateParams")
  private MyQRCodeDialog(Context context, int defStyle) {
    super(context, defStyle);
    View contentView = getLayoutInflater().inflate(R.layout.dialog_my_qr_code, null);
    mIvCode = (ImageView) contentView.findViewById(R.id.iv_qr_code);
    try {
      bitmap =
          QrCodeUtil.Create2DCode(
              String.format("http://me.yuedong.com/u/%s", AppContext.getContext().getLoginUid()));
      mIvCode.setImageBitmap(bitmap);
    } catch (WriterException e) {
      e.printStackTrace();
    }
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    mIvCode.setOnLongClickListener(
        new OnLongClickListener() {
          @Override
          public boolean onLongClick(View v) {
            dismiss();
            if (FileUtils.bitmapToFile(
                bitmap, FileUtils.getSavePath("Yuedong") + "/my_qr_code.png")) {
              ToastUtil.toast("二维码已保存到 Yuedong 文件夹下");
            } else {
              ToastUtil.toast("SD卡写入错误,二维码保存失败");
            }
            return false;
          }
        });

    contentView.setOnTouchListener(
        new View.OnTouchListener() {
          @Override
          public boolean onTouch(View v, MotionEvent event) {
            MyQRCodeDialog.this.dismiss();
            return false;
          }
        });
    super.setContentView(contentView);
  }
Example #17
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setTheme();
    setContentView(R.layout.waypoint);
    setTitle(R.string.waypoint_title);

    // get parameters
    Bundle extras = getIntent().getExtras();

    // try to get data from extras
    if (extras != null) {
      id = extras.getInt("waypoint");
    }

    if (id <= 0) {
      showToast(res.getString(R.string.err_waypoint_unknown));
      finish();
      return;
    }

    waitDialog = ProgressDialog.show(this, null, res.getString(R.string.waypoint_loading), true);
    waitDialog.setCancelable(true);

    (new loadWaypoint()).start();

    ImageView defaultNavigationImageView = (ImageView) findViewById(R.id.defaultNavigation);
    defaultNavigationImageView.setOnLongClickListener(
        new OnLongClickListener() {
          @Override
          public boolean onLongClick(View v) {
            startDefaultNavigation2();
            return true;
          }
        });
  }
Example #18
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.draganddropmain);

    imageView = (ImageView) findViewById(R.id.imageView);
    mIconBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
    imageView.setImageBitmap(mIconBitmap);
    imageView.setTag(IMAGEVIEW_TAG);
    imageView.setOnLongClickListener(
        new View.OnLongClickListener() {
          public boolean onLongClick(View v) {
            Toast.makeText(DragAndDropActivity.this, "ImageView is LongClicked", Toast.LENGTH_SHORT)
                .show();
            ClipData.Item item = new ClipData.Item((CharSequence) v.getTag());
            String[] mimeTypes = {ClipDescription.MIMETYPE_TEXT_PLAIN};
            ClipData dragData = new ClipData((CharSequence) v.getTag(), mimeTypes, item);
            DragShadowBuilder myShadow = new MyDragShadowBuilder(imageView);
            return v.startDrag(dragData, myShadow, null, 0);
          }
        });
    ImageView dropView = (ImageView) findViewById(R.id.dropView);
    dropView.setOnDragListener(mDragListen);
  }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_room_detail);

    app = (App) getApplicationContext();

    Intent intent = getIntent();
    room = new Room(intent.getStringExtra(ROOM_NUMBER), intent.getStringExtra(ROOM_TYPE));
    ToggleButton toggle_recommendation = (ToggleButton) findViewById(R.id.toggle_recommendation);
    toggle_recommendation.setChecked(true);

    if (room.getRoomType().equals(Room.STANDARD_ROOM)) {
      resource = R.drawable.hotel1;
    } else {
      resource = R.drawable.hotel2;
    }

    ImageView img_header = (ImageView) findViewById(R.id.img_header);
    img_header.setImageResource(resource);
    img_header.setOnLongClickListener(
        new View.OnLongClickListener() {

          @Override
          public boolean onLongClick(View v) {
            ConfirmStorePhotoDialogFragment frag = new ConfirmStorePhotoDialogFragment();
            frag.show(getSupportFragmentManager(), CONFIRMATION_DIALOG_TAG);
            return false;
          }
        });

    setTitle(room.getRoomNumber());

    SharedPreferences settings = getSharedPreferences(room.getRoomNumber(), 0);
    favorite = settings.getBoolean("favorite", false);
  }
Example #20
0
 private void initImageCell(ImageView imageCell) {
   imageCell.setOnClickListener(this);
   imageCell.setOnLongClickListener(this);
 }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // Lookup R.layout.main
    LinearLayout layout = (LinearLayout) findViewById(R.id.admoblayout);

    // Create the adView
    // Please replace MY_BANNER_UNIT_ID with your AdMob Publisher ID
    AdView adView = new AdView(this, AdSize.BANNER, "a14e9304811c39d");

    // Add the adView to it
    layout.addView(adView);

    // Initiate a generic request to load it with an ad
    AdRequest request = new AdRequest();
    request.setTesting(true);

    adView.loadAd(request);
    position = 0;
    imgView = (ImageView) findViewById(R.id.ImageView01);
    imgView.setImageResource(Imgid[0]);

    gallery = (Gallery) findViewById(R.id.liquidgallery);
    gallery.setAdapter(new AddImgAdp(this));

    gallery.setOnItemClickListener(
        new OnItemClickListener() {
          @Override
          public void onItemClick(
              @SuppressWarnings("rawtypes") AdapterView parent, View v, int position, long id) {
            imgView.setImageResource(Imgid[position]);
            LiquidBackgroundsFreeActivity.this.position = position;
          }
        });

    imgView.setOnLongClickListener(
        new View.OnLongClickListener() {
          @Override
          public boolean onLongClick(View v) {

            AlertDialog alertDialog =
                new AlertDialog.Builder(LiquidBackgroundsFreeActivity.this).create();
            alertDialog.setTitle(Messages.getString("DIA_NUM.0")); // $NON-NLS-1$
            alertDialog.setMessage(Messages.getString("DIA_NUM.1")); // $NON-NLS-1$
            alertDialog.setButton(
                Messages.getString("DIA_NUM.2"), // $NON-NLS-1$
                new DialogInterface.OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int which) {

                    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), Imgid[position]);
                    try {
                      LiquidBackgroundsFreeActivity.this.setWallpaper(bitmap);
                    } catch (IOException e) {
                      // TODO Auto-generated catch block
                      e.printStackTrace();
                    }
                    Log.d(
                        Messages.getString("DIA_NUM.3"),
                        Messages.getString("DIA_NUM.4")); // $NON-NLS-1$ //$NON-NLS-2$
                  }
                });

            alertDialog.show();
            return true;
          }
        });
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.editor_settingview);

    mContext = this;

    // ------------------------------------
    // UI Setting
    // ------------------------------------
    mPenBtn = (ImageView) findViewById(R.id.penBtn);
    mPenBtn.setOnClickListener(mBtnClickListener);
    mPenBtn.setOnLongClickListener(mBtnLongClickListener);
    mEraserBtn = (ImageView) findViewById(R.id.eraseBtn);
    mEraserBtn.setOnClickListener(mBtnClickListener);
    mEraserBtn.setOnLongClickListener(mBtnLongClickListener);
    mTextBtn = (ImageView) findViewById(R.id.textBtn);
    mTextBtn.setOnClickListener(mBtnClickListener);
    mTextBtn.setOnLongClickListener(mBtnLongClickListener);
    mFillingBtn = (ImageView) findViewById(R.id.fillingBtn);
    mFillingBtn.setOnClickListener(mBtnClickListener);
    mFillingBtn.setOnLongClickListener(mBtnLongClickListener);
    mColorPickerBtn = (ImageView) findViewById(R.id.colorPickerBtn);
    mColorPickerBtn.setOnClickListener(mColorPickerListener);

    mUndoBtn = (ImageView) findViewById(R.id.undoBtn);
    mUndoBtn.setOnClickListener(undoNredoBtnClickListener);
    mRedoBtn = (ImageView) findViewById(R.id.redoBtn);
    mRedoBtn.setOnClickListener(undoNredoBtnClickListener);

    mSettingInfo = (TextView) findViewById(R.id.settingInfo);
    mColorSettingInfo = (ImageView) findViewById(R.id.colorsettingInfo);

    // ------------------------------------
    // Create SCanvasView
    // ------------------------------------
    mLayoutContainer = (FrameLayout) findViewById(R.id.layout_container);
    mCanvasContainer = (RelativeLayout) findViewById(R.id.canvas_container);

    mSCanvas = new SCanvasView(mContext);
    mCanvasContainer.addView(mSCanvas);

    // ------------------------------------
    // SettingView Setting
    // ------------------------------------
    // Resource Map for Layout & Locale
    HashMap<String, Integer> settingResourceMapInt =
        SPenSDKUtils.getSettingLayoutLocaleResourceMap(true, true, true, true);
    // Resource Map for Custom font path
    HashMap<String, String> settingResourceMapString =
        SPenSDKUtils.getSettingLayoutStringResourceMap(true, true, true, true);
    // Create Setting View
    mSCanvas.createSettingView(mLayoutContainer, settingResourceMapInt, settingResourceMapString);

    // ====================================================================================
    //
    // Set Callback Listener(Interface)
    //
    // ====================================================================================
    // ------------------------------------------------
    // SCanvas Listener
    // ------------------------------------------------
    mSCanvas.setSCanvasInitializeListener(
        new SCanvasInitializeListener() {
          @Override
          public void onInitialized() {
            // --------------------------------------------
            // Start SCanvasView/CanvasView Task Here
            // --------------------------------------------
            // Application Identifier Setting
            if (!mSCanvas.setAppID(
                APPLICATION_ID_NAME,
                APPLICATION_ID_VERSION_MAJOR,
                APPLICATION_ID_VERSION_MINOR,
                APPLICATION_ID_VERSION_PATCHNAME))
              Toast.makeText(mContext, "Fail to set App ID.", Toast.LENGTH_LONG).show();

            // Set Title
            if (!mSCanvas.setTitle("SPen-SDK Test"))
              Toast.makeText(mContext, "Fail to set Title.", Toast.LENGTH_LONG).show();

            // Update button state
            mSCanvas.setCanvasMode(SCanvasConstants.SCANVAS_MODE_INPUT_PEN);
            mSCanvas.setSettingViewSizeOption(
                SCanvasConstants.SCANVAS_SETTINGVIEW_PEN,
                SCanvasConstants.SCANVAS_SETTINGVIEW_SIZE_EXT);
            mSCanvas.showSettingView(SCanvasConstants.SCANVAS_SETTINGVIEW_PEN, true);
            updateModeState();
          }
        });

    // ------------------------------------------------
    // History Change Listener
    // ------------------------------------------------
    mSCanvas.setHistoryUpdateListener(
        new HistoryUpdateListener() {
          @Override
          public void onHistoryChanged(boolean undoable, boolean redoable) {
            mUndoBtn.setEnabled(undoable);
            mRedoBtn.setEnabled(redoable);
          }
        });

    // ------------------------------------------------
    // SCanvas Mode Changed Listener
    // ------------------------------------------------
    mSCanvas.setSCanvasModeChangedListener(
        new SCanvasModeChangedListener() {

          @Override
          public void onModeChanged(int mode) {
            updateModeState();
          }
        });

    // ------------------------------------------------
    // Color Picker Listener
    // ------------------------------------------------
    mSCanvas.setColorPickerColorChangeListener(
        new ColorPickerColorChangeListener() {
          @Override
          public void onColorPickerColorChanged(int nColor) {

            int nCurMode = mSCanvas.getCanvasMode();
            if (nCurMode == SCanvasConstants.SCANVAS_MODE_INPUT_PEN) {
              SettingStrokeInfo strokeInfo = mSCanvas.getSettingViewStrokeInfo();
              if (strokeInfo != null) {
                strokeInfo.setStrokeColor(nColor);
                mSCanvas.setSettingViewStrokeInfo(strokeInfo);
              }
            } else if (nCurMode == SCanvasConstants.SCANVAS_MODE_INPUT_ERASER) {
              // do nothing
            } else if (nCurMode == SCanvasConstants.SCANVAS_MODE_INPUT_TEXT) {
              SettingTextInfo textInfo = mSCanvas.getSettingViewTextInfo();
              if (textInfo != null) {
                textInfo.setTextColor(nColor);
                mSCanvas.setSettingViewTextInfo(textInfo);
              }
            } else if (nCurMode == SCanvasConstants.SCANVAS_MODE_INPUT_FILLING) {
              SettingFillingInfo fillingInfo = mSCanvas.getSettingViewFillingInfo();
              if (fillingInfo != null) {
                fillingInfo.setFillingColor(nColor);
                mSCanvas.setSettingViewFillingInfo(fillingInfo);
              }
            }
          }
        });

    // ------------------------------------------------
    // SettingView Show Listener : Optional
    // ------------------------------------------------
    mSCanvas.setSettingViewShowListener(
        new SettingViewShowListener() {
          @Override
          public void onEraserSettingViewShow(boolean bVisible) {
            if (SHOW_LOG) {
              if (bVisible) Log.i(TAG, "Eraser setting view is shown");
              else Log.i(TAG, "Eraser setting view is closed");
            }
          }

          @Override
          public void onPenSettingViewShow(boolean bVisible) {
            if (SHOW_LOG) {
              if (bVisible) Log.i(TAG, "Pen setting view is shown");
              else Log.i(TAG, "Pen setting view is closed");
            }

            if (bVisible) {
              SettingStrokeInfo strokeInfo = mSCanvas.getSettingViewStrokeInfo();
              if (strokeInfo != null) {
                updateColor(strokeInfo.getStrokeColor());
              }
            }
          }

          @Override
          public void onTextSettingViewShow(boolean bVisible) {
            if (SHOW_LOG) {
              if (bVisible) Log.i(TAG, "Text setting view is shown");
              else Log.i(TAG, "Text setting view is closed");
            }

            if (bVisible) {
              SettingTextInfo textInfo = mSCanvas.getSettingViewTextInfo();
              if (textInfo != null) {
                updateColor(textInfo.getTextColor());
              }
            }
          }

          @Override
          public void onFillingSettingViewShow(boolean bVisible) {
            if (SHOW_LOG) {
              if (bVisible) Log.i(TAG, "Text setting view is shown");
              else Log.i(TAG, "Text setting view is closed");
            }

            if (bVisible) {
              SettingFillingInfo fillingInfo = mSCanvas.getSettingViewFillingInfo();
              if (fillingInfo != null) {
                updateColor(fillingInfo.getFillingColor());
              }
            }
          }
        });

    // ------------------------------------------------
    // SettingStrokeChangeListener Listener
    // ------------------------------------------------
    mSCanvas.setSettingStrokeChangeListener(
        new SettingStrokeChangeListener() {

          @Override
          public void onClearAll(boolean bClearAllCompleted) {
            if (bClearAllCompleted) updateSetting("Clear All is completed");
          }

          @Override
          public void onEraserWidthChanged(int eraserWidth) {
            updateSetting("Eraser width is changed : " + eraserWidth);
          }

          @Override
          public void onStrokeColorChanged(int strokeColor) {
            updateColor(strokeColor);
          }

          @Override
          public void onStrokeStyleChanged(int strokeStyle) {
            if (strokeStyle == SObjectStroke.SAMM_STROKE_STYLE_PENCIL)
              updateSetting("Stroke Style = Pen");
            else if (strokeStyle == SObjectStroke.SAMM_STROKE_STYLE_BRUSH)
              updateSetting("Stroke Style = Brush");
            else if (strokeStyle == SObjectStroke.SAMM_STROKE_STYLE_CHINESE_BRUSH)
              updateSetting("Stroke Style = Chinese Brush");
            else if (strokeStyle == SObjectStroke.SAMM_STROKE_STYLE_CRAYON)
              updateSetting("Stroke Style = Pencil Crayon");
            else if (strokeStyle == SObjectStroke.SAMM_STROKE_STYLE_MARKER)
              updateSetting("Stroke Style = Marker");
            else if (strokeStyle == SObjectStroke.SAMM_STROKE_STYLE_ERASER)
              updateSetting("Stroke Style = Eraser");
          }

          @Override
          public void onStrokeWidthChanged(int strokeWidth) {
            updateSetting("Stroke width is changed : " + strokeWidth);
          }

          @Override
          public void onStrokeAlphaChanged(int strokeAlpha) {
            updateSetting("Alpha is changed : " + strokeAlpha);
          }
        });

    // ------------------------------------------------
    // OnSettingTextChangeListener Listener
    // ------------------------------------------------
    mSCanvas.setSettingTextChangeListener(
        new SettingTextChangeListener() {

          @Override
          public void onTextColorChanged(int textColor) {
            updateColor(textColor);
          }

          @Override
          public void onTextFontChanged(String fontName) {
            updateSetting("Font is changed : " + fontName);
          }

          @Override
          public void onTextSizeChanged(int textSize) {
            updateSetting("Text size is changed : " + textSize);
          }

          @Override
          public void onTextStyleChanged(int textStyle) {
            StringBuilder textStyleString = new StringBuilder();
            boolean bDefault = (textStyle == SObjectText.SAMM_TEXT_STYLE_NONE);
            if (bDefault) textStyleString.append("Default ");
            boolean bBold = ((textStyle & SObjectText.SAMM_TEXT_STYLE_BOLD) != 0);
            if (bBold) textStyleString.append("Bold ");
            boolean bItalic = ((textStyle & SObjectText.SAMM_TEXT_STYLE_ITALIC) != 0);
            if (bItalic) textStyleString.append("Italic ");
            boolean bUnderline = ((textStyle & SObjectText.SAMM_TEXT_STYLE_UNDERLINE) != 0);
            if (bUnderline) textStyleString.append("Underline ");
            updateSetting("Text style is changed : " + textStyleString);
          }

          @Override
          public void onTextAlignmentChanged(int textHorizAlignment) {
            switch (textHorizAlignment) {
              case SAMMLibConstants.SAMM_ALIGN_NORMAL:
                updateSetting("Text alignment is changed as Left alignment");
                break;
              case SAMMLibConstants.SAMM_ALIGN_CENTER:
                updateSetting("Text alignment is changed as Center alignment");
                break;
              case SAMMLibConstants.SAMM_ALIGN_OPPOSITE:
                updateSetting("Text alignment is changed as Right alignment");
                break;
            }
          }
        });

    // ------------------------------------------------
    // SettingFillingChangeListener Listener
    // ------------------------------------------------
    mSCanvas.setSettingFillingChangeListener(
        new SettingFillingChangeListener() {
          @Override
          public void onFillingColorChanged(int fillingColor) {
            updateColor(fillingColor);
          }
        });

    mUndoBtn.setEnabled(false);
    mRedoBtn.setEnabled(false);
    mPenBtn.setSelected(true);

    // Caution:
    // Do NOT load file or start animation here because we don't know canvas size here.
    // Start such SCanvasView Task at onInitialized() of SCanvasInitializeListener
  }
Example #23
0
  private void Init_View() {
    dir = new File(PATH);
    if (!dir.exists()) {
      dir.mkdirs();
      Log.e(PATH, dir.mkdirs() + "");
    }

    final ImageView fabIconNew = new ImageView(this);
    fabIconNew.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_new_light));
    rightLowerButton = new FloatingActionButton.Builder(this).setContentView(fabIconNew).build();
    rLSubBuilder = new SubActionButton.Builder(this);
    ImageView rlIcon1 = new ImageView(this);
    ImageView rlIcon2 = new ImageView(this);
    ImageView rlIcon3 = new ImageView(this);
    ImageView rlIcon4 = new ImageView(this);
    ImageView rlIcon5 = new ImageView(this);
    ImageView rlIcon6 = new ImageView(this);

    rlIcon1.setImageDrawable(getResources().getDrawable(R.drawable.iconfont_color));
    rlIcon2.setImageDrawable(getResources().getDrawable(R.drawable.iconfont_bi));
    rlIcon3.setImageDrawable(getResources().getDrawable(R.drawable.iconfont_daoru));
    rlIcon4.setImageDrawable(getResources().getDrawable(R.drawable.iconfont_xpc));
    rlIcon5.setImageDrawable(getResources().getDrawable(R.drawable.iconfont_clear));
    rlIcon6.setImageDrawable(getResources().getDrawable(R.drawable.icon_chonghui));

    rightLowerMenu =
        new FloatingActionMenu.Builder(this)
            .addSubActionView(rLSubBuilder.setContentView(rlIcon6).build())
            .addSubActionView(rLSubBuilder.setContentView(rlIcon1).build())
            .addSubActionView(rLSubBuilder.setContentView(rlIcon2).build())
            .addSubActionView(rLSubBuilder.setContentView(rlIcon3).build())
            .addSubActionView(rLSubBuilder.setContentView(rlIcon4).build())
            .addSubActionView(rLSubBuilder.setContentView(rlIcon5).build())
            .attachTo(rightLowerButton)
            .build();

    rightLowerMenu.setStateChangeListener(
        new FloatingActionMenu.MenuStateChangeListener() {
          @Override
          public void onMenuOpened(FloatingActionMenu menu) {
            // Rotate the icon of rightLowerButton 45 degrees clockwise
            fabIconNew.setRotation(0);
            OPEN = true;
            PropertyValuesHolder pvhR = PropertyValuesHolder.ofFloat(View.ROTATION, 45);
            ObjectAnimator animation = ObjectAnimator.ofPropertyValuesHolder(fabIconNew, pvhR);
            animation.start();
          }

          @Override
          public void onMenuClosed(FloatingActionMenu menu) {
            // Rotate the icon of rightLowerButton 45 degrees counter-clockwise
            fabIconNew.setRotation(45);
            OPEN = false;
            PropertyValuesHolder pvhR = PropertyValuesHolder.ofFloat(View.ROTATION, 0);
            ObjectAnimator animation = ObjectAnimator.ofPropertyValuesHolder(fabIconNew, pvhR);
            animation.start();
          }
        });
    rlIcon3.setOnLongClickListener(
        new View.OnLongClickListener() {
          @Override
          public boolean onLongClick(View view) {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("file/*");
            startActivityForResult(intent, SELECT_FILE);
            return true;
          }
        });

    rlIcon6.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View view) {
            if (!paintView.isShowing()) {
              paintView.preview(pathNode.getPathList());
            }
          }
        });

    rlIcon6.setOnLongClickListener(
        new View.OnLongClickListener() {
          @Override
          public boolean onLongClick(View view) {
            paintView.PathNodeToJson(pathNode, dir);
            return false;
          }
        });
    rlIcon5.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            if (!paintView.isShowing()) {
              paintView.clean();
              pathNode.ClearList();
              paintView.clearReUnList();
            }
          }
        });
    rlIcon4.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View view) {
            paintView.Eraser();
          }
        });
    rlIcon2.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View view) {
            paintView.Paint();
          }
        });
    Init_Eraser_View();
    rlIcon2.setOnLongClickListener(
        new View.OnLongClickListener() {
          @Override
          public boolean onLongClick(View view) {
            Init_First_Dialog();
            mMaterialDialog.show();
            return true;
          }
        });
    rlIcon1.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View view) {
            ColorPickerDialogFragment f =
                ColorPickerDialogFragment.newInstance(DIALOG_ID, null, null, Color.BLACK, true);
            f.setStyle(DialogFragment.STYLE_NORMAL, R.style.LightPickerDialogTheme);
            f.show(getFragmentManager(), "d");
          }
        });
    rlIcon4.setOnLongClickListener(
        new View.OnLongClickListener() {
          @Override
          public boolean onLongClick(View view) {
            Init_Eraser_View();
            mMaterialDialog.show();
            return true;
          }
        });
    rlIcon3.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View view) {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");
            startActivityForResult(Intent.createChooser(intent, "选择图片"), SELECT_PICTURE);
          }
        });
    rightLowerButton.setOnLongClickListener(
        new View.OnLongClickListener() {
          @Override
          public boolean onLongClick(View view) {
            Log.e("", Environment.getExternalStorageDirectory().getPath() + "/DrawAPicture");
            paintView.BitmapToPicture(dir);
            return true;
          }
        });
  }
Example #24
0
  private void initLayout(Context context) {
    LayoutInflater factory = LayoutInflater.from(context);
    factory.inflate(R.layout.bottom_bar, this);
    mBottomBar = (LinearLayout) findViewById(R.id.bottombar);
    mBottomBarBack = (ImageView) findViewById(R.id.back);
    mBottomBarForward = (ImageView) findViewById(R.id.forward);
    mBottomBarTabs = (ImageView) findViewById(R.id.tabs);
    mBottomBarBookmarks = (ImageView) findViewById(R.id.bookmarks);
    mBottomBarTabCount = (TextView) findViewById(R.id.tabcount);

    mBottomBarBack.setOnClickListener(
        new OnClickListener() {
          public void onClick(View arg0) {
            ((Controller) mUiController).onBackKey();
          }
        });
    mBottomBarBack.setOnLongClickListener(
        new OnLongClickListener() {
          @Override
          public boolean onLongClick(View arg0) {
            Toast.makeText(
                    mUiController.getActivity(),
                    mUiController.getActivity().getResources().getString(R.string.back),
                    0)
                .show();
            return false;
          }
        });
    mBottomBarForward.setOnClickListener(
        new OnClickListener() {
          public void onClick(View arg0) {
            if (mUiController != null && mUiController.getCurrentTab() != null) {
              mUiController.getCurrentTab().goForward();
            }
          }
        });
    mBottomBarForward.setOnLongClickListener(
        new OnLongClickListener() {
          @Override
          public boolean onLongClick(View arg0) {
            Toast.makeText(
                    mUiController.getActivity(),
                    mUiController.getActivity().getResources().getString(R.string.forward),
                    0)
                .show();
            return false;
          }
        });
    mBottomBarTabs.setOnClickListener(
        new OnClickListener() {
          public void onClick(View arg0) {
            ((PhoneUi) mBaseUi).toggleNavScreen();
          }
        });
    mBottomBarTabs.setOnLongClickListener(
        new OnLongClickListener() {
          @Override
          public boolean onLongClick(View arg0) {
            Toast.makeText(
                    mUiController.getActivity(),
                    mUiController.getActivity().getResources().getString(R.string.tabs),
                    0)
                .show();
            return false;
          }
        });
    mBottomBarBookmarks.setOnClickListener(
        new OnClickListener() {
          public void onClick(View arg0) {
            mUiController.bookmarksOrHistoryPicker(ComboViews.Bookmarks);
          }
        });
    mBottomBarBookmarks.setOnLongClickListener(
        new OnLongClickListener() {
          @Override
          public boolean onLongClick(View arg0) {
            Toast.makeText(
                    mUiController.getActivity(),
                    mUiController.getActivity().getResources().getString(R.string.bookmarks),
                    0)
                .show();
            return false;
          }
        });
    mBottomBarTabCount.setText(Integer.toString(mUiController.getTabControl().getTabCount()));
    mTabControl.setOnTabCountChangedListener(
        new TabControl.OnTabCountChangedListener() {
          public void onTabCountChanged() {
            mBottomBarTabCount.setText(Integer.toString(mTabControl.getTabCount()));
          }
        });
  }
Example #25
0
  private void initLayout() {
    ActionBar actionBar = getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setTitle(R.string.write_weibo);

    View title = getLayoutInflater().inflate(R.layout.statusnewactivity_title_layout, null);
    TextView contentNumber = (TextView) title.findViewById(R.id.content_number);
    contentNumber.setVisibility(View.GONE);
    haveGPS = (ImageView) title.findViewById(R.id.have_gps);
    haveGPS.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {

            String geoUriString =
                "geo:" + geoBean.getLat() + "," + geoBean.getLon() + "?q=" + location;
            Uri geoUri = Uri.parse(geoUriString);
            Intent mapCall = new Intent(Intent.ACTION_VIEW, geoUri);
            PackageManager packageManager = getPackageManager();
            List<ResolveInfo> activities = packageManager.queryIntentActivities(mapCall, 0);
            boolean isIntentSafe = activities.size() > 0;
            if (isIntentSafe) {
              startActivity(mapCall);
            }
          }
        });
    haveGPS.setOnLongClickListener(
        new View.OnLongClickListener() {
          @Override
          public boolean onLongClick(View v) {
            haveGPS.setVisibility(View.GONE);
            geoBean = null;
            return true;
          }
        });
    havePic = (ImageView) title.findViewById(R.id.have_pic);

    havePic.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(new File(picPath)), "image/png");
            PackageManager packageManager = getPackageManager();
            List<ResolveInfo> activities = packageManager.queryIntentActivities(intent, 0);
            boolean isIntentSafe = activities.size() > 0;
            if (isIntentSafe) {
              startActivity(intent);
            }
          }
        });

    havePic.setOnLongClickListener(
        new View.OnLongClickListener() {
          @Override
          public boolean onLongClick(View v) {
            havePic.setVisibility(View.GONE);
            picPath = "";
            return true;
          }
        });
    actionBar.setCustomView(title, new ActionBar.LayoutParams(Gravity.RIGHT));
    actionBar.setDisplayShowCustomEnabled(true);
    content = ((EditText) findViewById(R.id.status_new_content));
    content.addTextChangedListener(
        new TextNumLimitWatcher((TextView) findViewById(R.id.menu_send), content, this));

    View.OnClickListener onClickListener = new BottomButtonClickListener();
    findViewById(R.id.menu_add_gps).setOnClickListener(onClickListener);
    findViewById(R.id.menu_add_pic).setOnClickListener(onClickListener);
    findViewById(R.id.menu_send).setOnClickListener(onClickListener);

    View.OnLongClickListener onLongClickListener = new BottomButtonLongClickListener();
    findViewById(R.id.menu_add_gps).setOnLongClickListener(onLongClickListener);
    findViewById(R.id.menu_add_pic).setOnLongClickListener(onLongClickListener);
    findViewById(R.id.menu_send).setOnLongClickListener(onLongClickListener);
  }
Example #26
0
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_dash_board);
    final getBoatDetails boat = new getBoatDetails();
    String s = null;

    boatDetailsType = (TextView) findViewById(R.id.boatText);
    listView = (ListView) findViewById(R.id.listView);
    boatDetailsType.setText("All Boats");
    try {

      s = boat.execute("http://192.248.22.121/GPS_mobile/Nishan/getAllBoats.php").get();
      JSONArray jArray = new JSONArray(s);
      System.out.println(s);
      int count = jArray.length();
      String[] mobileArray = new String[count];
      for (int i = 0; i < count; i++) {
        JSONObject json = jArray.getJSONObject(i);
        // System.out.println(json.getString("local_reg_no"));
        mobileArray[i] = (json.getString("local_reg_no") + " - " + json.getString("name"));
      }
      ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.boats, mobileArray);

      listView.setAdapter(adapter);

      // System.out.print(s);
    } catch (InterruptedException e) {
      e.printStackTrace();
    } catch (ExecutionException e) {
      e.printStackTrace();
    } catch (JSONException e) {
      e.printStackTrace();
    }

    ImageView departureImage = (ImageView) findViewById(R.id.btnDeparture);
    ImageView arrivalImage = (ImageView) findViewById(R.id.btnArrival);
    ImageView livemap = (ImageView) findViewById(R.id.btnMap);

    final ImageView Leaving = (ImageView) findViewById(R.id.btnLeving);
    final ImageView allBoats = (ImageView) findViewById(R.id.btnAllBoats);
    final ImageView arriving = (ImageView) findViewById(R.id.btnArriving);
    final ImageView arrivedBoat = (ImageView) findViewById(R.id.btnArrived);
    final ImageView QCApprovedBoat = (ImageView) findViewById(R.id.btnQCApproved);
    final ImageView FIApproved = (ImageView) findViewById(R.id.btnFIapproaval);

    listView.setOnItemLongClickListener(
        new AdapterView.OnItemLongClickListener() {
          @Override
          public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            if (isConnectingToInternet()) {
              Object o = listView.getItemAtPosition(position);
              // As you are using Default String Adapter

              String IMULA = o.toString().split("-")[0];
              boatDetails bt = new boatDetails();
              try {
                String boat =
                    bt.execute(
                            "http://192.248.22.121/GPS_mobile/Nishan/getBoat.php?IMULA="
                                + URLEncoder.encode(IMULA, "UTF-8"))
                        .get();
                Intent popup = new Intent(DashBoard.this, PopUpWindow.class);
                // Toast.makeText(getBaseContext(),boat,Toast.LENGTH_SHORT).show();
                popup.putExtra("boatlist", boat);
                startActivity(popup);
              } catch (InterruptedException e) {
                e.printStackTrace();
              } catch (ExecutionException e) {
                e.printStackTrace();
              } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
              }

              return false;
            } else {
              AlertDialog.Builder builder = new AlertDialog.Builder(DashBoard.this);
              builder
                  .setMessage("You are not connected to the internet!\nඔබ අන්තර්ජාලයට සම්බන්ද නැත!")
                  .setCancelable(false)
                  .setPositiveButton(
                      "OK",
                      new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {}
                      });
              AlertDialog alert = builder.create();
              alert.show();
              return false;
            }
          }
        });

    departureImage.setOnLongClickListener(
        new View.OnLongClickListener() {

          @Override
          public boolean onLongClick(View v) {

            if (isConnectingToInternet()) {
              Intent intent;
              intent = new Intent(v.getContext(), Departure.class);
              startActivity(intent);
              return false;
            } else {
              AlertDialog.Builder builder = new AlertDialog.Builder(DashBoard.this);
              builder
                  .setMessage("You are not connected to the internet!\nඔබ අන්තර්ජාලයට සම්බන්ද නැත!")
                  .setCancelable(false)
                  .setPositiveButton(
                      "OK",
                      new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {}
                      });
              AlertDialog alert = builder.create();
              alert.show();
              return false;
            }
          }
        });

    arrivalImage.setOnLongClickListener(
        new View.OnLongClickListener() {
          @Override
          public boolean onLongClick(View v) {
            if (isConnectingToInternet()) {
              Intent intent;
              intent = new Intent(v.getContext(), Arrival.class);
              startActivity(intent);
              return false;
            } else {
              AlertDialog.Builder builder = new AlertDialog.Builder(DashBoard.this);
              builder
                  .setMessage("You are not connected to the internet!\nඔබ අන්තර්ජාලයට සම්බන්ද නැත!")
                  .setCancelable(false)
                  .setPositiveButton(
                      "OK",
                      new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {}
                      });
              AlertDialog alert = builder.create();
              alert.show();
              return false;
            }
          }
        });

    livemap.setOnLongClickListener(
        new View.OnLongClickListener() {
          @Override
          public boolean onLongClick(View v) {
            if (isConnectingToInternet()) {
              Intent intent;
              intent = getPackageManager().getLaunchIntentForPackage("com.example.dula.test1");
              startActivity(intent);
              return false;
            } else {
              AlertDialog.Builder builder = new AlertDialog.Builder(DashBoard.this);
              builder
                  .setMessage("You are not connected to the internet!\nඔබ අන්තර්ජාලයට සම්බන්ද නැත!")
                  .setCancelable(false)
                  .setPositiveButton(
                      "OK",
                      new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {}
                      });
              AlertDialog alert = builder.create();
              alert.show();
              return false;
            }
          }
        });

    Leaving.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {

            if (isConnectingToInternet()) {
              String s = null;
              getBoats deportBoats = new getBoats();
              if (clickedButton == 0) allBoats.setImageResource(R.drawable.allboats);
              else if (clickedButton == 2) arriving.setImageResource(R.drawable.arrivingboats);
              else if (clickedButton == 3) arrivedBoat.setImageResource(R.drawable.arrivedboats);
              else if (clickedButton == 4) FIApproved.setImageResource(R.drawable.fiapprovedboats);
              else if (clickedButton == 5)
                QCApprovedBoat.setImageResource(R.drawable.qcapprovedboats);
              clickedButton = 1;
              Leaving.setImageResource(R.drawable.leavingoatsp);
              try {

                s =
                    deportBoats
                        .execute("http://192.248.22.121/GPS_mobile/Nishan/getToBeDeportedBoats.php")
                        .get();
                JSONArray jArray = new JSONArray(s);
                int count = jArray.length();
                String[] mobileArray = new String[count];
                for (int i = 0; i < count; i++) {
                  JSONObject json = jArray.getJSONObject(i);
                  mobileArray[i] =
                      (json.getString("local_reg_no") + " - " + json.getString("name"));
                }

                ArrayAdapter adapter =
                    new ArrayAdapter<String>(DashBoard.this, R.layout.boats, mobileArray);
                boatDetailsType.setText("Leaving Boats");
                ListView listView = (ListView) findViewById(R.id.listView);
                listView.setAdapter(adapter);
                // System.out.print(s);
              } catch (InterruptedException e) {
                e.printStackTrace();
              } catch (ExecutionException e) {
                e.printStackTrace();
              } catch (JSONException e) {
                e.printStackTrace();
              }
            } else {
              AlertDialog.Builder builder = new AlertDialog.Builder(DashBoard.this);
              builder
                  .setMessage("You are not connected to the internet!\nඔබ අන්තර්ජාලයට සම්බන්ද නැත!")
                  .setCancelable(false)
                  .setPositiveButton(
                      "OK",
                      new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {}
                      });
              AlertDialog alert = builder.create();
              alert.show();
            }
          }
        });

    allBoats.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            if (isConnectingToInternet()) {
              String s = null;
              getBoats deportBoats = new getBoats();
              allBoats.setImageResource(R.drawable.allboatsp);
              if (clickedButton == 1) Leaving.setImageResource(R.drawable.leavingboats);
              else if (clickedButton == 2) arriving.setImageResource(R.drawable.arrivingboats);
              else if (clickedButton == 3) arrivedBoat.setImageResource(R.drawable.arrivedboats);
              else if (clickedButton == 4) FIApproved.setImageResource(R.drawable.fiapprovedboats);
              else if (clickedButton == 5)
                QCApprovedBoat.setImageResource(R.drawable.qcapprovedboats);
              clickedButton = 0;
              try {

                s =
                    deportBoats
                        .execute("http://192.248.22.121/GPS_mobile/Nishan/getAllBoats.php")
                        .get();
                JSONArray jArray = new JSONArray(s);
                int count = jArray.length();
                String[] mobileArray = new String[count];
                for (int i = 0; i < count; i++) {
                  JSONObject json = jArray.getJSONObject(i);
                  mobileArray[i] =
                      (json.getString("local_reg_no") + " - " + json.getString("name"));
                }

                ArrayAdapter adapter =
                    new ArrayAdapter<String>(DashBoard.this, R.layout.boats, mobileArray);
                boatDetailsType.setText("All Boats");
                ListView listView = (ListView) findViewById(R.id.listView);
                listView.setAdapter(adapter);
                // System.out.print(s);
              } catch (InterruptedException e) {
                e.printStackTrace();
              } catch (ExecutionException e) {
                e.printStackTrace();
              } catch (JSONException e) {
                e.printStackTrace();
              }
            } else {
              AlertDialog.Builder builder = new AlertDialog.Builder(DashBoard.this);
              builder
                  .setMessage("You are not connected to the internet!\nඔබ අන්තර්ජාලයට සම්බන්ද නැත!")
                  .setCancelable(false)
                  .setPositiveButton(
                      "OK",
                      new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {}
                      });
              AlertDialog alert = builder.create();
              alert.show();
            }
          }
        });

    arriving.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            if (isConnectingToInternet()) {
              String s = null;
              getBoats deportBoats = new getBoats();
              if (clickedButton == 0) allBoats.setImageResource(R.drawable.allboats);
              else if (clickedButton == 1) Leaving.setImageResource(R.drawable.leavingboats);
              else if (clickedButton == 3) arrivedBoat.setImageResource(R.drawable.arrivedboats);
              else if (clickedButton == 4) FIApproved.setImageResource(R.drawable.fiapprovedboats);
              else if (clickedButton == 5)
                QCApprovedBoat.setImageResource(R.drawable.qcapprovedboats);
              arriving.setImageResource(R.drawable.arrivingboatsp);
              clickedButton = 2;
              try {

                s =
                    deportBoats
                        .execute(
                            "http://192.248.22.121/GPS_mobile/Nishan/getReportingRangeBoats.php")
                        .get();
                JSONArray jArray = new JSONArray(s);
                int count = jArray.length();
                String[] mobileArray = new String[count];
                for (int i = 0; i < count; i++) {
                  JSONObject json = jArray.getJSONObject(i);
                  mobileArray[i] =
                      (json.getString("local_reg_no") + " - " + json.getString("name"));
                }

                ArrayAdapter adapter =
                    new ArrayAdapter<String>(DashBoard.this, R.layout.boats, mobileArray);
                boatDetailsType.setText("Arriving Boats");
                ListView listView = (ListView) findViewById(R.id.listView);
                listView.setAdapter(adapter);
                // System.out.print(s);
              } catch (InterruptedException e) {
                e.printStackTrace();
              } catch (ExecutionException e) {
                e.printStackTrace();
              } catch (JSONException e) {
                e.printStackTrace();
              }
            } else {
              AlertDialog.Builder builder = new AlertDialog.Builder(DashBoard.this);
              builder
                  .setMessage("You are not connected to the internet!\nඔබ අන්තර්ජාලයට සම්බන්ද නැත!")
                  .setCancelable(false)
                  .setPositiveButton(
                      "OK",
                      new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {}
                      });
              AlertDialog alert = builder.create();
              alert.show();
            }
          }
        });

    arrivedBoat.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            if (isConnectingToInternet()) {
              String s = null;
              getBoats deportBoats = new getBoats();
              if (clickedButton == 0) allBoats.setImageResource(R.drawable.allboats);
              else if (clickedButton == 1) Leaving.setImageResource(R.drawable.leavingboats);
              else if (clickedButton == 2) arriving.setImageResource(R.drawable.arrivingboats);
              else if (clickedButton == 4) FIApproved.setImageResource(R.drawable.fiapprovedboats);
              else if (clickedButton == 5)
                QCApprovedBoat.setImageResource(R.drawable.qcapprovedboats);
              arrivedBoat.setImageResource(R.drawable.arrivedboatsp);
              clickedButton = 3;
              try {

                s =
                    deportBoats
                        .execute("http://192.248.22.121/GPS_mobile/Nishan/getArrivedBoats.php")
                        .get();
                JSONArray jArray = new JSONArray(s);
                int count = jArray.length();
                String[] mobileArray = new String[count];
                for (int i = 0; i < count; i++) {
                  JSONObject json = jArray.getJSONObject(i);
                  mobileArray[i] =
                      (json.getString("local_reg_no") + " - " + json.getString("name"));
                }

                ArrayAdapter adapter =
                    new ArrayAdapter<String>(DashBoard.this, R.layout.boats, mobileArray);
                boatDetailsType.setText("Arrived Boats");
                ListView listView = (ListView) findViewById(R.id.listView);
                listView.setAdapter(adapter);
                // System.out.print(s);
              } catch (InterruptedException e) {
                e.printStackTrace();
              } catch (ExecutionException e) {
                e.printStackTrace();
              } catch (JSONException e) {
                e.printStackTrace();
              }
            } else {
              AlertDialog.Builder builder = new AlertDialog.Builder(DashBoard.this);
              builder
                  .setMessage("You are not connected to the internet!\nඔබ අන්තර්ජාලයට සම්බන්ද නැත!")
                  .setCancelable(false)
                  .setPositiveButton(
                      "OK",
                      new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {}
                      });
              AlertDialog alert = builder.create();
              alert.show();
            }
          }
        });

    QCApprovedBoat.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            if (isConnectingToInternet()) {
              String s = null;
              getBoats deportBoats = new getBoats();
              if (clickedButton == 0) allBoats.setImageResource(R.drawable.allboats);
              else if (clickedButton == 1) Leaving.setImageResource(R.drawable.leavingboats);
              else if (clickedButton == 3) arrivedBoat.setImageResource(R.drawable.arrivedboats);
              else if (clickedButton == 4) FIApproved.setImageResource(R.drawable.fiapprovedboats);
              else if (clickedButton == 2) arriving.setImageResource(R.drawable.arrivingboats);
              QCApprovedBoat.setImageResource(R.drawable.qcapprovedboatsp);
              clickedButton = 5;
              try {

                s =
                    deportBoats
                        .execute("http://192.248.22.121/GPS_mobile/Nishan/getQCApprovedBoats.php")
                        .get();
                JSONArray jArray = new JSONArray(s);
                int count = jArray.length();
                String[] mobileArray = new String[count];
                for (int i = 0; i < count; i++) {
                  JSONObject json = jArray.getJSONObject(i);
                  mobileArray[i] =
                      (json.getString("local_reg_no") + " - " + json.getString("name"));
                }

                ArrayAdapter adapter =
                    new ArrayAdapter<String>(DashBoard.this, R.layout.boats, mobileArray);
                boatDetailsType.setText("QC Approved Boats -  Arrival");
                ListView listView = (ListView) findViewById(R.id.listView);
                listView.setAdapter(adapter);
                // System.out.print(s);
              } catch (InterruptedException e) {
                e.printStackTrace();
              } catch (ExecutionException e) {
                e.printStackTrace();
              } catch (JSONException e) {
                e.printStackTrace();
              }
            } else {
              AlertDialog.Builder builder = new AlertDialog.Builder(DashBoard.this);
              builder
                  .setMessage("You are not connected to the internet!\nඔබ අන්තර්ජාලයට සම්බන්ද නැත!")
                  .setCancelable(false)
                  .setPositiveButton(
                      "OK",
                      new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {}
                      });
              AlertDialog alert = builder.create();
              alert.show();
            }
          }
        });

    FIApproved.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            if (isConnectingToInternet()) {
              String s = null;
              getBoats deportBoats = new getBoats();
              if (clickedButton == 0) allBoats.setImageResource(R.drawable.allboats);
              else if (clickedButton == 1) Leaving.setImageResource(R.drawable.leavingboats);
              else if (clickedButton == 3) arrivedBoat.setImageResource(R.drawable.arrivedboats);
              else if (clickedButton == 2) arriving.setImageResource(R.drawable.arrivingboats);
              else if (clickedButton == 5)
                QCApprovedBoat.setImageResource(R.drawable.qcapprovedboats);
              FIApproved.setImageResource(R.drawable.fiapprovedboatsp);
              clickedButton = 4;
              try {

                s =
                    deportBoats
                        .execute("http://192.248.22.121/GPS_mobile/Nishan/getFIApprovedBoats.php")
                        .get();
                JSONArray jArray = new JSONArray(s);
                int count = jArray.length();
                String[] mobileArray = new String[count];
                for (int i = 0; i < count; i++) {
                  JSONObject json = jArray.getJSONObject(i);
                  mobileArray[i] =
                      (json.getString("local_reg_no") + " - " + json.getString("name"));
                }

                ArrayAdapter adapter =
                    new ArrayAdapter<String>(DashBoard.this, R.layout.boats, mobileArray);
                boatDetailsType.setText("FI Approved Boats -  Arrival");
                ListView listView = (ListView) findViewById(R.id.listView);
                listView.setAdapter(adapter);
                // System.out.print(s);
              } catch (InterruptedException e) {
                e.printStackTrace();
              } catch (ExecutionException e) {
                e.printStackTrace();
              } catch (JSONException e) {
                e.printStackTrace();
              }
            } else {
              AlertDialog.Builder builder = new AlertDialog.Builder(DashBoard.this);
              builder
                  .setMessage("You are not connected to the internet!\nඔබ අන්තර්ජාලයට සම්බන්ද නැත!")
                  .setCancelable(false)
                  .setPositiveButton(
                      "OK",
                      new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {}
                      });
              AlertDialog alert = builder.create();
              alert.show();
            }
          }
        });
  }
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // Look up the AdView as a resource and load a request.
    AdView adView = (AdView) this.findViewById(R.id.adView);
    adView.loadAd(new AdRequest());

    // delete button listener
    OnClickListener DeleteButtonListner =
        new OnClickListener() {
          public void onClick(View v) {
            yesnoDeleteHandler("Are you sure?", "Are you sure you want to delete?");
          }
        };
    Button deleteButton = (Button) findViewById(R.id.delete);
    deleteButton.setOnClickListener(DeleteButtonListner);

    // save button listener
    OnClickListener SaveButtonListner =
        new OnClickListener() {
          public void onClick(View v) {
            saveCurrentPyramid(v.getContext());
          }
        };
    Button saveButton = (Button) findViewById(R.id.save);
    saveButton.setOnClickListener(SaveButtonListner);

    // new button listener
    OnClickListener newButtonListner =
        new OnClickListener() {
          public void onClick(View v) {
            newPyramid();
          }
        };
    Button newPButton = (Button) findViewById(R.id.newrow);
    newPButton.setOnClickListener(newButtonListner);

    // dots button listener
    OnClickListener topDotsListner =
        new OnClickListener() {
          public void onClick(View v) {
            TextView topCheckBox = (TextView) findViewById(R.id.TopItemCheckBox);
            String blockname = topCheckBox.getText().toString();
            switchToTextView(v.getContext(), blockname);
          }
        };
    OnClickListener dotsOneListner =
        new OnClickListener() {
          public void onClick(View v) {
            CheckBox cb = (CheckBox) findViewById(R.id.itemOneCheckBox);
            String blockname = cb.getText().toString();
            switchToTextView(v.getContext(), blockname);
          }
        };
    OnClickListener dotsTwoListner =
        new OnClickListener() {
          public void onClick(View v) {
            CheckBox cb = (CheckBox) findViewById(R.id.itemTwoCheckBox);
            String blockname = cb.getText().toString();
            switchToTextView(v.getContext(), blockname);
          }
        };
    OnClickListener dotsThreeListner =
        new OnClickListener() {
          public void onClick(View v) {
            CheckBox cb = (CheckBox) findViewById(R.id.itemThreeCheckBox);
            String blockname = cb.getText().toString();
            switchToTextView(v.getContext(), blockname);
          }
        };
    OnClickListener dotsFourListner =
        new OnClickListener() {
          public void onClick(View v) {
            CheckBox cb = (CheckBox) findViewById(R.id.itemFourCheckBox);
            String blockname = cb.getText().toString();
            switchToTextView(v.getContext(), blockname);
          }
        };
    OnClickListener dotsFiveListner =
        new OnClickListener() {
          public void onClick(View v) {
            CheckBox cb = (CheckBox) findViewById(R.id.itemFiveCheckBox);
            String blockname = cb.getText().toString();
            switchToTextView(v.getContext(), blockname);
          }
        };
    OnClickListener dotsSixListner =
        new OnClickListener() {
          public void onClick(View v) {
            CheckBox cb = (CheckBox) findViewById(R.id.itemSixCheckBox);
            String blockname = cb.getText().toString();
            switchToTextView(v.getContext(), blockname);
          }
        };

    Button topDotsButton = (Button) findViewById(R.id.topdots);
    Button DotsOneButton = (Button) findViewById(R.id.dotsOne);
    Button DotsTwoButton = (Button) findViewById(R.id.dotsTwo);
    Button DotsThreeButton = (Button) findViewById(R.id.dotsThree);
    Button DotsFourButton = (Button) findViewById(R.id.dotsFour);
    Button DotsFiveButton = (Button) findViewById(R.id.dotsFive);
    Button DotsSixButton = (Button) findViewById(R.id.dotsSix);

    topDotsButton.setOnClickListener(topDotsListner);
    DotsOneButton.setOnClickListener(dotsOneListner);
    DotsTwoButton.setOnClickListener(dotsTwoListner);
    DotsThreeButton.setOnClickListener(dotsThreeListner);
    DotsFourButton.setOnClickListener(dotsFourListner);
    DotsFiveButton.setOnClickListener(dotsFiveListner);
    DotsSixButton.setOnClickListener(dotsSixListner);

    // image listeners
    // photo on click listener
    ImageView imageOne = (ImageView) findViewById(R.id.ImageViewOne);
    ImageView imageTwo = (ImageView) findViewById(R.id.ImageViewTwo);
    ImageView imageThree = (ImageView) findViewById(R.id.ImageViewThree);
    ImageView imageFour = (ImageView) findViewById(R.id.ImageViewFour);
    ImageView imageFive = (ImageView) findViewById(R.id.ImageViewFive);
    ImageView imageSix = (ImageView) findViewById(R.id.ImageViewSix);
    ImageView imageTop = (ImageView) findViewById(R.id.TopBlockImage);

    // Create an anonymous implementation of OnClickListener
    OnLongClickListener TopNameListner =
        new OnLongClickListener() {
          public boolean onLongClick(View v) {
            // do something when the button is clicked

            // in onCreate or any event where your want the user to

            AlertDialog.Builder alert = new AlertDialog.Builder(v.getContext());

            alert.setTitle("Block Name?");
            alert.setMessage("Please Enter A Name For The Block");

            // Set an EditText view to get user input
            final EditText input = new EditText(v.getContext());
            alert.setView(input);

            alert.setPositiveButton(
                "Ok",
                new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int whichButton) {
                    tempName = input.getText().toString();

                    Cursor tempCursor = getPyramidCursorByName(tempName);
                    if (tempCursor.getCount() > 0) {
                      Toast.makeText(
                              getBaseContext(), "That Name is Already In Use!", Toast.LENGTH_LONG)
                          .show();
                    } else {
                      // Do something with value!
                      if (tempName.length() > 1) {
                        // select a file
                        TextView topCheckBox = (TextView) findViewById(R.id.TopItemCheckBox);
                        topCheckBox.setText(tempName);
                      } else {
                        Toast.makeText(getBaseContext(), "Invalid Name!", Toast.LENGTH_LONG).show();
                      }
                    }
                  }
                });

            alert.setNegativeButton(
                "Cancel",
                new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int whichButton) {
                    // Canceled.
                  }
                });

            alert.show();
            return true;
          }
        };
    TextView topCheckBox = (TextView) findViewById(R.id.TopItemCheckBox);
    topCheckBox.setOnLongClickListener(TopNameListner);

    // checkbox listeners
    // Create an anonymous implementation of OnClickListener
    OnLongClickListener otherNameListener =
        new OnLongClickListener() {
          public boolean onLongClick(final View v) {
            // do something when the button is clicked

            // in onCreate or any event where your want the user to

            AlertDialog.Builder alert = new AlertDialog.Builder(v.getContext());

            alert.setTitle("Block Name?");
            alert.setMessage("Please Enter A Name For The Block");

            // Set an EditText view to get user input
            final EditText input = new EditText(v.getContext());
            alert.setView(input);

            alert.setPositiveButton(
                "Ok",
                new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int whichButton) {
                    tempName = input.getText().toString();

                    // Do something with value!
                    if (tempName.length() > 1) {
                      // select a file
                    } else {
                      tempName = "Unnamed";
                    }

                    // set the correct view name
                    final CheckBox checkBoxOne = (CheckBox) findViewById(R.id.itemOneCheckBox);
                    final CheckBox checkBoxTwo = (CheckBox) findViewById(R.id.itemTwoCheckBox);
                    final CheckBox checkBoxThree = (CheckBox) findViewById(R.id.itemThreeCheckBox);
                    final CheckBox checkBoxFour = (CheckBox) findViewById(R.id.itemFourCheckBox);
                    final CheckBox checkBoxFive = (CheckBox) findViewById(R.id.itemFiveCheckBox);
                    final CheckBox checkBoxSix = (CheckBox) findViewById(R.id.itemSixCheckBox);

                    if (tempName != null) {
                      if (v.equals(checkBoxOne)) {
                        checkBoxOne.setText(tempName);
                      } else if (v.equals(checkBoxTwo)) {
                        checkBoxTwo.setText(tempName);
                      } else if (v.equals(checkBoxThree)) {
                        checkBoxThree.setText(tempName);
                      } else if (v.equals(checkBoxFour)) {
                        checkBoxFour.setText(tempName);
                      } else if (v.equals(checkBoxFive)) {
                        checkBoxFive.setText(tempName);
                      } else if (v.equals(checkBoxSix)) {
                        checkBoxSix.setText(tempName);
                      }
                    }
                  }
                });

            alert.setNegativeButton(
                "Cancel",
                new DialogInterface.OnClickListener() {
                  public void onClick(DialogInterface dialog, int whichButton) {
                    // Canceled.
                    tempName = null;
                  }
                });

            alert.show();

            return true;
          }
        };

    CheckBox checkBoxOne = (CheckBox) findViewById(R.id.itemOneCheckBox);
    checkBoxOne.setOnLongClickListener(otherNameListener);
    CheckBox checkBoxTwo = (CheckBox) findViewById(R.id.itemTwoCheckBox);
    checkBoxTwo.setOnLongClickListener(otherNameListener);
    CheckBox checkBoxThree = (CheckBox) findViewById(R.id.itemThreeCheckBox);
    checkBoxThree.setOnLongClickListener(otherNameListener);
    CheckBox checkBoxFour = (CheckBox) findViewById(R.id.itemFourCheckBox);
    checkBoxFour.setOnLongClickListener(otherNameListener);
    CheckBox checkBoxFive = (CheckBox) findViewById(R.id.itemFiveCheckBox);
    checkBoxFive.setOnLongClickListener(otherNameListener);
    CheckBox checkBoxSix = (CheckBox) findViewById(R.id.itemSixCheckBox);
    checkBoxSix.setOnLongClickListener(otherNameListener);

    checkBoxOne.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            CheckBox checkBoxOne = (CheckBox) findViewById(R.id.itemOneCheckBox);
            if (checkBoxOne.isChecked()) {
              checkBoxOne.setPaintFlags(checkBoxOne.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            } else {
              checkBoxOne.setPaintFlags(checkBoxOne.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
            }
          }
        });

    checkBoxTwo.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            CheckBox checkBoxTwo = (CheckBox) findViewById(R.id.itemTwoCheckBox);
            if (checkBoxTwo.isChecked()) {
              checkBoxTwo.setPaintFlags(checkBoxTwo.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            } else {
              checkBoxTwo.setPaintFlags(checkBoxTwo.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
            }
          }
        });

    checkBoxThree.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            CheckBox checkBoxThree = (CheckBox) findViewById(R.id.itemThreeCheckBox);
            if (checkBoxThree.isChecked()) {
              checkBoxThree.setPaintFlags(
                  checkBoxThree.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            } else {
              checkBoxThree.setPaintFlags(
                  checkBoxThree.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
            }
          }
        });

    checkBoxFour.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            CheckBox checkBoxFour = (CheckBox) findViewById(R.id.itemFourCheckBox);
            if (checkBoxFour.isChecked()) {
              checkBoxFour.setPaintFlags(
                  checkBoxFour.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            } else {
              checkBoxFour.setPaintFlags(
                  checkBoxFour.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
            }
          }
        });

    checkBoxFive.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            CheckBox checkBoxFive = (CheckBox) findViewById(R.id.itemFiveCheckBox);
            if (checkBoxFive.isChecked()) {
              checkBoxFive.setPaintFlags(
                  checkBoxFive.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            } else {
              checkBoxFive.setPaintFlags(
                  checkBoxFive.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
            }
          }
        });

    checkBoxSix.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            CheckBox checkBoxSix = (CheckBox) findViewById(R.id.itemSixCheckBox);
            if (checkBoxSix.isChecked()) {
              checkBoxSix.setPaintFlags(checkBoxSix.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
            } else {
              checkBoxSix.setPaintFlags(checkBoxSix.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG);
            }
          }
        });

    // image onlongclick listeners
    imageOne.setOnLongClickListener(
        new OnLongClickListener() {
          public boolean onLongClick(View v) {
            ImageView imageOne = (ImageView) findViewById(R.id.ImageViewOne);
            colorPicker(imageOne, v.getContext());
            return true;
          }
        });

    imageTwo.setOnLongClickListener(
        new OnLongClickListener() {
          public boolean onLongClick(View v) {
            ImageView imageOne = (ImageView) findViewById(R.id.ImageViewTwo);
            colorPicker(imageOne, v.getContext());
            return true;
          }
        });

    imageThree.setOnLongClickListener(
        new OnLongClickListener() {
          public boolean onLongClick(View v) {
            ImageView imageOne = (ImageView) findViewById(R.id.ImageViewThree);
            colorPicker(imageOne, v.getContext());
            return true;
          }
        });

    imageFour.setOnLongClickListener(
        new OnLongClickListener() {
          public boolean onLongClick(View v) {
            ImageView imageOne = (ImageView) findViewById(R.id.ImageViewFour);
            colorPicker(imageOne, v.getContext());
            return true;
          }
        });

    imageFive.setOnLongClickListener(
        new OnLongClickListener() {
          public boolean onLongClick(View v) {
            ImageView imageOne = (ImageView) findViewById(R.id.ImageViewFive);
            colorPicker(imageOne, v.getContext());
            return true;
          }
        });

    imageSix.setOnLongClickListener(
        new OnLongClickListener() {
          public boolean onLongClick(View v) {
            ImageView imageOne = (ImageView) findViewById(R.id.ImageViewSix);
            colorPicker(imageOne, v.getContext());
            return true;
          }
        });

    imageTop.setOnLongClickListener(
        new OnLongClickListener() {
          public boolean onLongClick(View v) {
            ImageView imageOne = (ImageView) findViewById(R.id.TopBlockImage);
            colorPicker(imageOne, v.getContext());
            return true;
          }
        });

    // set regular click listeners for the bottom 6 items
    imageOne.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            CheckBox checkBoxOne = (CheckBox) findViewById(R.id.itemOneCheckBox);
            saveAndCreateNewFromName(v.getContext(), checkBoxOne.getText().toString());
          }
        });

    // set regular click listeners for the bottom 6 items
    imageTwo.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            CheckBox checkBoxOne = (CheckBox) findViewById(R.id.itemTwoCheckBox);
            saveAndCreateNewFromName(v.getContext(), checkBoxOne.getText().toString());
          }
        });

    // set regular click listeners for the bottom 6 items
    imageThree.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            CheckBox checkBoxOne = (CheckBox) findViewById(R.id.itemThreeCheckBox);
            saveAndCreateNewFromName(v.getContext(), checkBoxOne.getText().toString());
          }
        });

    // set regular click listeners for the bottom 6 items
    imageFour.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            CheckBox checkBoxOne = (CheckBox) findViewById(R.id.itemFourCheckBox);
            saveAndCreateNewFromName(v.getContext(), checkBoxOne.getText().toString());
          }
        });

    // set regular click listeners for the bottom 6 items
    imageFive.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            CheckBox checkBoxOne = (CheckBox) findViewById(R.id.itemFiveCheckBox);
            saveAndCreateNewFromName(v.getContext(), checkBoxOne.getText().toString());
          }
        });

    // set regular click listeners for the bottom 6 items
    imageSix.setOnClickListener(
        new OnClickListener() {
          public void onClick(View v) {
            CheckBox checkBoxOne = (CheckBox) findViewById(R.id.itemSixCheckBox);
            saveAndCreateNewFromName(v.getContext(), checkBoxOne.getText().toString());
          }
        });

    fillImagesRandomly();

    // set an adapter for our spinner
    m_adapterForSpinner =
        new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_item);
    m_adapterForSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    Spinner spinner = (Spinner) findViewById(R.id.oldpyramids);
    spinner.setAdapter(m_adapterForSpinner);
    m_adapterForSpinner.add("*New Pyramid");

    spinner.setOnItemSelectedListener(new MyUnitsOnItemSelectedListener());

    // fill up our spinner item
    Cursor cursor = getPyramidssCursor();
    if (cursor.getCount() > 0) {
      deleteButton.setEnabled(true);
      while (cursor.moveToNext()) {
        String singlecardName = cursor.getString(1);
        m_adapterForSpinner.add(singlecardName);
      }
    } else {
      spinner.setEnabled(false);
    }
  }
Example #28
0
  private void init() {
    if (initialized) {
      return;
    }

    initialized = true;

    Settings.setLanguage(Settings.isUseEnglish());

    findOnMap.setClickable(true);
    findOnMap.setOnClickListener(
        new OnClickListener() {
          @Override
          public void onClick(final View v) {
            cgeoFindOnMap(v);
          }
        });

    findByOffline.setClickable(true);
    findByOffline.setOnClickListener(
        new OnClickListener() {
          @Override
          public void onClick(final View v) {
            cgeoFindByOffline(v);
          }
        });
    findByOffline.setOnLongClickListener(
        new View.OnLongClickListener() {

          @Override
          public boolean onLongClick(final View v) {
            new StoredList.UserInterface(MainActivity.this)
                .promptForListSelection(
                    R.string.list_title,
                    new Action1<Integer>() {

                      @Override
                      public void call(final Integer selectedListId) {
                        Settings.saveLastList(selectedListId);
                        CacheListActivity.startActivityOffline(MainActivity.this);
                      }
                    },
                    false,
                    PseudoList.HISTORY_LIST.id);
            return true;
          }
        });
    findByOffline.setLongClickable(true);

    advanced.setClickable(true);
    advanced.setOnClickListener(
        new OnClickListener() {
          @Override
          public void onClick(final View v) {
            cgeoSearch(v);
          }
        });

    any.setClickable(true);
    any.setOnClickListener(
        new OnClickListener() {
          @Override
          public void onClick(final View v) {
            cgeoPoint(v);
          }
        });

    filter.setClickable(true);
    filter.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(final View v) {
            selectGlobalTypeFilter();
          }
        });
    filter.setOnLongClickListener(
        new View.OnLongClickListener() {

          @Override
          public boolean onLongClick(final View v) {
            Settings.setCacheType(CacheType.ALL);
            setFilterTitle();
            return true;
          }
        });

    updateCacheCounter();

    setFilterTitle();
    checkRestore();
    (new CleanDatabaseThread()).start();
  }
Example #29
0
  /**
   * 1.头像事件 mine:事件 other事件 图片的状态 消息收到,没收到,图片展示成功,没有成功 触发图片的事件 【长按】
   *
   * <p>图片消息类型的render
   *
   * @param position
   * @param convertView
   * @param parent
   * @param isMine
   * @return
   */
  private View imageMsgRender(
      final int position, View convertView, final ViewGroup parent, final boolean isMine) {
    ImageRenderView imageRenderView;
    final ImageMessage imageMessage = (ImageMessage) msgObjectList.get(position);
    UserEntity userEntity = imService.getContactManager().findContact(imageMessage.getFromId());

    /** 保存在本地的path */
    final String imagePath = imageMessage.getPath();
    /** 消息中的image路径 */
    final String imageUrl = imageMessage.getUrl();

    if (null == convertView) {
      imageRenderView = ImageRenderView.inflater(ctx, parent, isMine);
    } else {
      imageRenderView = (ImageRenderView) convertView;
    }

    final ImageView messageImage = imageRenderView.getMessageImage();
    final int msgId = imageMessage.getMsgId();
    imageRenderView.setBtnImageListener(
        new ImageRenderView.BtnImageListener() {
          @Override
          public void onMsgFailure() {
            /**
             * 多端同步也不会拉到本地失败的数据 只有isMine才有的状态,消息发送失败 1. 图片上传失败。点击图片重新上传??[也是重新发送] 2. 图片上传成功,但是发送失败。
             * 点击重新发送??
             */
            if (FileUtil.isSdCardAvailuable()) {
              //
              // imageMessage.setLoadStatus(MessageStatus.IMAGE_UNLOAD);//如果是图片已经上传成功呢?
              imageMessage.setStatus(MessageConstant.MSG_SENDING);
              if (imService != null) {
                imService.getMessageManager().resendMessage(imageMessage);
              }
              updateItemState(msgId, imageMessage);
            } else {
              Toast.makeText(ctx, ctx.getString(R.string.sdcard_unavaluable), Toast.LENGTH_LONG)
                  .show();
            }
          }

          // DetailPortraitActivity 以前用的是DisplayImageActivity 这个类
          @Override
          public void onMsgSuccess() {
            Intent i = new Intent(ctx, PreviewMessageImagesActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(IntentConstant.CUR_MESSAGE, imageMessage);
            i.putExtras(bundle);
            ctx.startActivity(i);
            ((Activity) ctx).overridePendingTransition(R.anim.tt_image_enter, R.anim.tt_stay);
          }
        });

    // 设定触发loadImage的事件
    imageRenderView.setImageLoadListener(
        new ImageRenderView.ImageLoadListener() {

          @Override
          public void onLoadComplete(String loaclPath) {
            logger.d("chat#pic#save image ok");
            logger.d("pic#setsavepath:%s", loaclPath);
            //                imageMessage.setPath(loaclPath);//下载的本地路径不再存储
            imageMessage.setLoadStatus(MessageConstant.IMAGE_LOADED_SUCCESS);
            updateItemState(imageMessage);
          }

          @Override
          public void onLoadFailed() {
            logger.d("chat#pic#onBitmapFailed");
            imageMessage.setLoadStatus(MessageConstant.IMAGE_LOADED_FAILURE);
            updateItemState(imageMessage);
            logger.d("download failed");
          }
        });

    final View messageLayout = imageRenderView.getMessageLayout();
    messageImage.setOnLongClickListener(
        new View.OnLongClickListener() {
          @Override
          public boolean onLongClick(View v) {
            // 创建一个pop对象,然后 分支判断状态,然后显示需要的内容
            MessageOperatePopup popup =
                getPopMenu(parent, new OperateItemClickListener(imageMessage, position));
            boolean bResend =
                (imageMessage.getStatus() == MessageConstant.MSG_FAILURE)
                    || (imageMessage.getLoadStatus() == MessageConstant.IMAGE_UNLOAD);
            popup.show(messageLayout, DBConstant.SHOW_IMAGE_TYPE, bResend, isMine);
            return true;
          }
        });

    /** 父类控件中的发送失败view */
    imageRenderView
        .getMessageFailed()
        .setOnClickListener(
            new View.OnClickListener() {
              @Override
              public void onClick(View arg0) {
                // 重发或者重新加载
                MessageOperatePopup popup =
                    getPopMenu(parent, new OperateItemClickListener(imageMessage, position));
                popup.show(messageLayout, DBConstant.SHOW_IMAGE_TYPE, true, isMine);
              }
            });
    imageRenderView.render(imageMessage, userEntity, ctx);

    return imageRenderView;
  }
  @Override
  public View bindView(final int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    final ChatMsg item = list.get(position);
    if (convertView == null) {
      convertView = createViewByType(item, position);
    }
    // 文本类型
    RoundImageView iv_avatar = ViewHolder.get(convertView, R.id.iv_avatar); // 圆形头像
    final ImageView iv_fail_resend = ViewHolder.get(convertView, R.id.iv_fail_resend); // 失败重发
    final TextView tv_send_status = ViewHolder.get(convertView, R.id.tv_send_status); // 发送状态
    TextView tv_time = ViewHolder.get(convertView, R.id.tv_time); // 发送时间
    TextView tv_message = ViewHolder.get(convertView, R.id.tv_message); // 文本内容
    // 图片
    ImageView iv_picture = ViewHolder.get(convertView, R.id.iv_picture);
    final ProgressBar progress_load = ViewHolder.get(convertView, R.id.progress_load); // 进度条
    // 语音
    final ImageView iv_voice = ViewHolder.get(convertView, R.id.iv_voice);
    final TextView tv_voice_length = ViewHolder.get(convertView, R.id.tv_voice_length); // 语音长度

    final ImageView iv_voice_tips = ViewHolder.get(convertView, R.id.iv_voice_tips);

    final boolean isTeamExist =
        DBUtil.isTeamExitByUuid(
            item.getBelongId().replace("@team", ""),
            UserManager.getInstance(mContext).getCurrentUser().getPlayer().getUuid());
    String avatar = item.getBelongAvatar();
    if (avatar != null && !avatar.equals("")) { // 加载头像-为了不每次都加载头像
      if (item.getBelongId().equals("System")) { // 云球团队
        ImageLoader.getInstance()
            .displayImage(
                avatar.trim(),
                iv_avatar,
                new DisplayImageOptions.Builder()
                    .showImageOnLoading(R.drawable.ic_launcher)
                    .showImageForEmptyUri(R.drawable.ic_launcher)
                    .showImageOnFail(R.drawable.ic_launcher)
                    .cacheInMemory(true)
                    .cacheOnDisk(true)
                    .build(),
                animateFirstListener);
      } else if (isTeamExist) {
        ImageLoader.getInstance()
            .displayImage(
                avatar.trim(),
                iv_avatar,
                new DisplayImageOptions.Builder()
                    .showImageOnLoading(R.drawable.team_bage_default)
                    .showImageForEmptyUri(R.drawable.team_bage_default)
                    .showImageOnFail(R.drawable.team_bage_default)
                    .cacheInMemory(true)
                    .cacheOnDisk(true)
                    .build(),
                animateFirstListener);
      } else {
        ImageLoader.getInstance()
            .displayImage(
                avatar.trim(),
                iv_avatar,
                new DisplayImageOptions.Builder()
                    .showImageOnLoading(R.drawable.icon_default_head)
                    .showImageForEmptyUri(R.drawable.icon_default_head)
                    .showImageOnFail(R.drawable.icon_default_head)
                    .cacheInMemory(true)
                    .cacheOnDisk(true)
                    .build(),
                animateFirstListener);
      }
    } else {
      iv_avatar.setImageResource(R.drawable.head);
    }

    // 点击头像进入个人资料("球员信息")
    iv_avatar.setOnClickListener(
        new OnClickListener() {
          @Override
          public void onClick(View arg0) {
            Intent intent = new Intent();
            if (getItemViewType(position) == TYPE_RECEIVER_TXT
                || getItemViewType(position) == TYPE_RECEIVER_IMAGE
                || getItemViewType(position) == TYPE_RECEIVER_VOICE) {
              if (item.getBelongId().equals("System")) { // 云球团队
                // 不处理
              } else if (isTeamExist) { // 球队,不能用tag=group判断,因为球员的普通群聊消息的tag也是group
                intent.setClass(mContext, TeamInfoActivity.class);
                QueryBuilder<Team> teamQB =
                    CustomApplcation.getDaoSession(mContext).getTeamDao().queryBuilder();
                teamQB.where(TeamDao.Properties.Uuid.eq(item.getBelongId().replace("@team", "")));
                Team team = teamQB.unique();
                if (team == null || TextUtils.isEmpty(team.getUuid())) {
                  return;
                }
                intent.putExtra(TeamInfoActivity.INTENT_TEAM_INFO_BEAN, team);
                mContext.startActivity(intent);
              } else { // 球员
                String accountName = item.getConversationId().split("&")[0];
                // 先根据accountName获取得到用户的UUID
                getPlayerUidByAccountName(accountName);
              }
            } else {
              intent.setClass(mContext, SetMyInfoActivity.class);
              mContext.startActivity(intent);
            }
          }
        });

    // 以时间差显示
    if (position > 0) { // 从第二条消息开始显示时间差
      long preMsgTime = Long.parseLong(list.get(position - 1).getMsgTime()); // 前一条消息时间
      long currentMsgTime = Long.parseLong(list.get(position).getMsgTime()); // 当前消息时间
      if ((currentMsgTime - preMsgTime) / 1000 < 120) { // 计算两条消息时间间隔,小于两分钟则不显示时间
        tv_time.setVisibility(View.GONE);
      } else {
        tv_time.setVisibility(View.VISIBLE);
        tv_time.setText(TimeUtil.getChatTime(currentMsgTime));
      }
    } else { // 第一条消息直接显示时间
      tv_time.setText(TimeUtil.getChatTime(Long.parseLong(item.getMsgTime())));
    }

    int itemViewType = getItemViewType(position);
    if (itemViewType == TYPE_SEND_TXT
        // ||getItemViewType(position)==TYPE_SEND_IMAGE//图片单独处理
        || getItemViewType(position) == TYPE_SEND_VOICE) { // 只有自己发送的消息才有重发机制
      // 状态描述
      if (item.getStatus() == ChatConstants.STATUS_SEND_SUCCESS) { // 发送成功
        progress_load.setVisibility(View.INVISIBLE);
        iv_fail_resend.setVisibility(View.INVISIBLE);
        if (item.getMsgType().equals(ChatConstants.MSG_TYPE_AUDIO)) { // 如果是语音消息的话,显示语音长度
          tv_send_status.setVisibility(View.GONE);
          tv_voice_length.setVisibility(View.VISIBLE);
        } else { // 如果是文字消息的话则显示发送状态
          tv_send_status.setVisibility(View.VISIBLE);
          tv_send_status.setText("已发送");
        }
      } else if (item.getStatus()
          == ChatConstants.STATUS_SEND_FAIL) { // 服务器无响应或者查询失败等原因造成的发送失败,均需要重发
        progress_load.setVisibility(View.INVISIBLE);
        iv_fail_resend.setVisibility(View.VISIBLE); // 显示重发按钮
        iv_fail_resend.setOnClickListener(new OnResendClickListener(item, position));
        tv_send_status.setVisibility(View.INVISIBLE);
        if (item.getMsgType().equals(ChatConstants.MSG_TYPE_AUDIO)) {
          tv_voice_length.setVisibility(View.GONE);
        }
      } else if (item.getStatus() == ChatConstants.STATUS_SEND_START) { // 开始上传
        progress_load.setVisibility(View.VISIBLE); // 显示发送进度
        iv_fail_resend.setVisibility(View.INVISIBLE);
        tv_send_status.setVisibility(View.INVISIBLE);
        if (item.getMsgType().equals(ChatConstants.MSG_TYPE_AUDIO)) {
          tv_voice_length.setVisibility(View.GONE);
        }
      }
    }

    // 根据类型显示内容
    final String text = item.getContent();

    int msgTypeInt = getMsgTypeIntValue(item.getMsgType());

    switch (msgTypeInt) {
      case ChatConstants.TYPE_TEXT:
        try {
          SpannableString spannableString =
              FaceTextUtils.toSpannableString(mContext, text); // 转为可显示表情的字符串
          tv_message.setText(spannableString);
          tv_message.setOnClickListener(
              new OnClickListener() {

                @Override
                public void onClick(View v) {
                  // TODO 自动生成的方法存根
                  Intent intent = new Intent(mContext, BiggerTextSizeActivity.class);
                  intent.putExtra(ChatConstants.INTENT_TEXT_MESSAGE, text);
                  mContext.startActivity(intent);
                }
              });
          tv_message.setOnLongClickListener(new OnChatItemLongClickListener(item, position));
        } catch (Exception e) {
        }
        break;

      case ChatConstants.TYPE_IMAGE: // 图片类
        try {
          if (text != null && !text.equals("")) { // 发送成功之后存储的图片类型的content和接收到的是不一样的
            dealWithImage(
                position, progress_load, iv_fail_resend, tv_send_status, iv_picture, item);
          }
          iv_picture.setOnClickListener(
              new OnClickListener() { // 浏览大图

                @Override
                public void onClick(View arg0) {
                  Intent intent = new Intent(mContext, ImageBrowserActivity.class);
                  ArrayList<String> list = new ArrayList<String>();
                  for (int i = 0; i < ChatActivity.picUrls.size(); i++) {
                    list.add(ChatActivity.picUrls.valueAt(i));
                  }
                  intent.putStringArrayListExtra("photos", list);
                  intent.putExtra("position", ChatActivity.picUrls.indexOfValue(item.getContent()));
                  mContext.startActivity(intent);
                }
              });
          iv_picture.setOnLongClickListener(new OnChatItemLongClickListener(item, position));

        } catch (Exception e) {
        }
        break;

      case ChatConstants.TYPE_VOICE: // 语音消息
        try {
          if (text != null && !text.equals("")) {
            tv_voice_length.setVisibility(View.VISIBLE);
            final String localFilePath = Config.VOICE_DIR + MD5Util.getMD5(text.trim()) + ".amr";
            if (item.getBelongId().equals(currentUserAccountName)) { // 发送的消息
              if (item.getStatus() == ChatConstants.STATUS_SEND_RECEIVERED
                  || item.getStatus()
                      == ChatConstants.STATUS_SEND_SUCCESS) { // 当发送成功或者发送已阅读的时候,则显示语音长度
                tv_voice_length.setVisibility(View.VISIBLE);
                long duration = VoiceRecorder.getAmrDuration(new File(localFilePath));
                tv_voice_length.setText(duration + "\''");

              } else {
                tv_voice_length.setVisibility(View.INVISIBLE);
              }

            } else { // 收到的消息,则先下载下来
              iv_voice_tips.setVisibility(View.GONE); // 有出现一个Bug,就是有未读消息时,上下滑动消息记录,上方已读的语音消息又会出现红点
              if (!(new File(localFilePath).exists())) {
                final String netUrl = text.trim();
                DownloadManager downloadTask =
                    new DownloadManager(
                        new DownloadListener() {

                          @Override
                          public void onStart() {
                            // TODO Auto-generated method stub
                            progress_load.setVisibility(View.VISIBLE);
                            tv_voice_length.setVisibility(View.GONE);
                            iv_voice.setVisibility(View.INVISIBLE); // 只有下载完成才显示播放的按钮
                          }

                          @Override
                          public void onSuccess() {
                            // TODO Auto-generated method stub
                            try {
                              long duration = 0;
                              while (true) { // 取到真正语音长度为止,不能为0
                                duration = VoiceRecorder.getAmrDuration(new File(localFilePath));
                                if (duration != 0) break;
                              }
                              progress_load.setVisibility(View.GONE);
                              tv_voice_length.setVisibility(View.VISIBLE);
                              tv_voice_length.setText(duration + "\''");
                              iv_voice.setVisibility(View.VISIBLE);
                              iv_voice_tips.setVisibility(View.VISIBLE);
                            } catch (IOException e) {
                              // TODO 自动生成的 catch 块
                              e.printStackTrace();
                            }
                          }

                          @Override
                          public void onError(String error) {
                            // TODO Auto-generated method stub
                            progress_load.setVisibility(View.GONE);
                            tv_voice_length.setVisibility(View.GONE);
                            iv_voice.setVisibility(View.INVISIBLE);
                          }
                        });
                downloadTask.execute(netUrl, localFilePath);
              } else {
                long duration = VoiceRecorder.getAmrDuration(new File(localFilePath));
                tv_voice_length.setText(duration + "\''");
                if (item.getStatus() == ChatConstants.STATUS_UNPLAY) {
                  iv_voice_tips.setVisibility(View.VISIBLE);
                }
              }
            }
          }
          // 播放语音文件
          convertView.setOnClickListener(
              new NewRecordPlayClickListener(
                  mContext,
                  item,
                  iv_voice,
                  iv_voice_tips,
                  new OnPlayChangeListener() {

                    @Override
                    public void onPlayStop() {
                      // TODO 自动生成的方法存根
                      Intent intent = new Intent();
                      intent.setAction("chat.msg.playrecord");
                      mContext.sendBroadcast(intent);
                    }

                    @Override
                    public void onPlayStart() {
                      // TODO 自动生成的方法存根

                    }
                  }));
          convertView.setOnLongClickListener(new OnChatItemLongClickListener(item, position));
        } catch (Exception e) {

        }
        break;
      default:
        break;
    }
    return convertView;
  }