private static String buildHeader(ThreadRowInfo row, String fgColorStr) {
   if (row == null || (StringUtil.isEmpty(row.getSubject()) && !row.getISANONYMOUS())) return "";
   StringBuilder sb = new StringBuilder();
   sb.append("<h4 style='color:").append(fgColorStr).append("' >");
   if (!StringUtil.isEmpty(row.getSubject())) sb.append(row.getSubject());
   if (row.getISANONYMOUS())
     sb.append("<font style='color:#D00;font-weight: bold;'>").append("[匿名]").append("</font>");
   sb.append("</h4>");
   return sb.toString();
 }
  private void handleJsonList(ViewHolder holder, int position) {
    ThreadPageInfo entry = getEntry(position);
    // this.topicListInfo.getArticleEntryList().get(position);

    if (entry == null) {
      return;
    }
    Resources res = inflater.getContext().getResources();
    ThemeManager theme = ThemeManager.getInstance();
    boolean night = false;
    int nightLinkColor = res.getColor(R.color.night_link_color);
    if (theme.getMode() == ThemeManager.MODE_NIGHT) night = true;
    holder.author.setText(entry.getAuthor());
    if (night) holder.author.setTextColor(nightLinkColor);

    String lastPoster = entry.getLastposter_org();
    if (StringUtil.isEmpty(lastPoster)) lastPoster = entry.getLastposter();
    holder.lastReply.setText(lastPoster);
    holder.num.setText("" + entry.getReplies());
    if (night) {
      holder.lastReply.setTextColor(nightLinkColor);
      holder.num.setTextColor(nightLinkColor);
    }

    holder.title.setTextColor(res.getColor(theme.getForegroundColor()));
    float size = PhoneConfiguration.getInstance().getTextSize();

    String titile = entry.getContent();
    if (StringUtil.isEmpty(titile)) {
      titile = entry.getSubject();
      holder.title.setText(StringUtil.unEscapeHtml(titile));

    } else {
      holder.title.setText(StringUtil.removeBrTag(StringUtil.unEscapeHtml(titile)));
    }

    holder.title.setTextSize(size);
    final TextPaint tp = holder.title.getPaint();
    tp.setFakeBoldText(false);

    if (!StringUtil.isEmpty(entry.getTitlefont())) {
      final String font = entry.getTitlefont();
      if (font.equals("~1~~") || font.equals("~~~1")) {
        tp.setFakeBoldText(true);
      } else if (font.startsWith("green")) {
        holder.title.setTextColor(res.getColor(R.color.title_green));
      } else if (font.startsWith("blue")) {
        holder.title.setTextColor(res.getColor(R.color.title_blue));
      } else if (font.startsWith("red")) {
        holder.title.setTextColor(res.getColor(R.color.title_red));
      } else if (font.startsWith("orange")) {
        holder.title.setTextColor(res.getColor(R.color.title_orange));
      }
    }
  }
  @Override
  protected void onPostExecute(String result) {
    ActivityUtil.getInstance().dismiss();
    if (StringUtil.isEmpty(result)) return;

    String msg = StringUtil.getStringBetween(result, 0, "{\"0\":\"", "\"},\"time\"").result;
    // android.R.drawable.ic_search_category_default
    if (!StringUtil.isEmpty(msg)) {
      Toast.makeText(context, msg.trim(), Toast.LENGTH_SHORT).show();
    }
  }
  public static String convertToHtmlText(
      final ThreadRowInfo row,
      boolean showImage,
      int imageQuality,
      final String fgColorStr,
      final String bgcolorStr) {
    HashSet<String> imageURLSet = new HashSet<String>();
    String ngaHtml =
        StringUtil.decodeForumTag(row.getContent(), showImage, imageQuality, imageURLSet);
    if (row.get_isInBlackList()) {
      ngaHtml =
          "<HTML> <HEAD><META http-equiv=Content-Type content= \"text/html; charset=utf-8 \">"
              + "<body bgcolor= '#"
              + bgcolorStr
              + "'>"
              + "<font color='red' size='2'>["
              + blacklistban
              + "]</font>"
              + "</font></body>";
    } else {
      if (imageURLSet.size() == 0) {
        imageURLSet = null;
      }
      if (StringUtil.isEmpty(ngaHtml)) {
        ngaHtml = row.getAlterinfo();
      }
      if (StringUtil.isEmpty(ngaHtml)) {

        ngaHtml = "<font color='red'>[" + hide + "]</font>";
      }
      ngaHtml =
          ngaHtml
              + buildComment(row, fgColorStr, showImage, imageQuality)
              + buildAttachment(row, showImage, imageQuality, imageURLSet)
              + buildSignature(row, showImage, imageQuality)
              + buildVote(row);
      ngaHtml =
          "<HTML> <HEAD><META http-equiv=Content-Type content= \"text/html; charset=utf-8 \">"
              + buildHeader(row, fgColorStr)
              + "<body bgcolor= '#"
              + bgcolorStr
              + "'>"
              + "<font color='#"
              + fgColorStr
              + "' size='2'>"
              + ngaHtml
              + "</font></body>";
    }
    return ngaHtml;
  }
Пример #5
0
  @Override
  protected String doInBackground(String... params) {

    String host = "ngalocation.appspot.com";
    String ret = null;
    for (int i = 0; i < ips.length; ++i) {
      StringBuilder sb = new StringBuilder("https://");
      try {
        sb.append(ips[i])
            .append("/test?nick_name=")
            .append(URLEncoder.encode(name, "utf-8"))
            .append("&user_id=")
            .append(uid)
            .append("&longitude=")
            .append(longitude)
            .append("&latitude=")
            .append(latitude);
      } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        return null;
      }
      ret = HttpUtil.getHtml(sb.toString(), "", host, 8000);
      if (!StringUtil.isEmpty(ret)) break;
      else {
        this.publishProgress(i + 1, ips.length);
      }
    }

    return ret;
  }
 @Override
 protected void onResume() {
   if (action.equals("new")) {
     if (StringUtil.isEmpty(toText.getText().toString())) {
       toText.requestFocus();
     } else {
       titleText.requestFocus();
     }
   } else {
     bodyText.requestFocus();
   }
   if (uploadTask != null) {
     FileUploadTask temp = uploadTask;
     uploadTask = null;
     if (ActivityUtil.isGreaterThan_2_3_3()) {
       RunParallel(temp);
     } else {
       temp.execute();
     }
   }
   if (PhoneConfiguration.getInstance().fullscreen) {
     ActivityUtil.getInstance().setFullScreen(v);
   }
   super.onResume();
 }
  private void handleAvatar(ImageView avatarIV, ThreadRowInfo row) {

    final int lou = row.getLou();
    final String avatarUrl = FunctionUtil.parseAvatarUrl(row.getJs_escap_avatar()); //
    final String userId = String.valueOf(row.getAuthorid());
    if (PhoneConfiguration.getInstance().nikeWidth < 3) {
      avatarIV.setImageBitmap(null);
      return;
    }
    if (defaultAvatar == null
        || defaultAvatar.getWidth() != PhoneConfiguration.getInstance().nikeWidth) {
      Resources res = avatarIV.getContext().getResources();
      InputStream is = res.openRawResource(R.drawable.default_avatar);
      InputStream is2 = res.openRawResource(R.drawable.default_avatar);
      this.defaultAvatar = ImageUtil.loadAvatarFromStream(is, is2);
    }

    Object tagObj = avatarIV.getTag();
    if (tagObj instanceof AvatarTag) {
      AvatarTag origTag = (AvatarTag) tagObj;
      if (origTag.isDefault == false) {
        ImageUtil.recycleImageView(avatarIV);
        // Log.d(TAG, "recycle avatar:" + origTag.lou);
      } else {
        // Log.d(TAG, "default avatar, skip recycle");
      }
    }

    AvatarTag tag = new AvatarTag(lou, true);
    avatarIV.setImageBitmap(defaultAvatar);
    avatarIV.setTag(tag);
    if (!StringUtil.isEmpty(avatarUrl)) {
      final String avatarPath = ImageUtil.newImage(avatarUrl, userId);
      if (avatarPath != null) {
        File f = new File(avatarPath);
        if (f.exists() && !isPending(avatarUrl)) {

          Bitmap bitmap = ImageUtil.loadAvatarFromSdcard(avatarPath);
          if (bitmap != null) {
            avatarIV.setImageBitmap(bitmap);
            tag.isDefault = false;
          } else f.delete();
          long date = f.lastModified();
          if ((System.currentTimeMillis() - date) / 1000 > 30 * 24 * 3600) {
            f.delete();
          }

        } else {
          final boolean downImg =
              isInWifi() || PhoneConfiguration.getInstance().isDownAvatarNoWifi();

          new AvatarLoadTask(avatarIV, null, downImg, lou, this)
              .execute(avatarUrl, avatarPath, userId);
        }
      }
    }
  }
  public SpinnerUserListAdapter(Context context) {
    super();
    this.context = context;
    SharedPreferences share = context.getSharedPreferences(PERFERENCE, Context.MODE_PRIVATE);

    String userListString = share.getString(USER_LIST, "");

    // new ArrayList<User>();
    if (StringUtil.isEmpty(userListString)) {
      userList = new ArrayList<User>();
    } else {
      userList = JSON.parseArray(userListString, User.class);
    }
  }
 @Override
 protected MeiziTopicMData doInBackground(String... params) {
   String url = params[0];
   String htmlString;
   if (!StringUtil.isEmpty(PhoneConfiguration.getInstance().getDb_Cookie())) {
     htmlString = HttpUtil.getHtmlForDbmeizi(url, PhoneConfiguration.getInstance().getDb_Cookie());
   } else {
     htmlString = HttpUtil.getHtmlForDbmeizi(url, PhoneConfiguration.getInstance().getDb_Cookie());
   }
   if (!StringUtil.isEmpty(htmlString)) {
     MeiziTopicMData resulTopicM = null;
     if (url.toLowerCase(Locale.US).indexOf("baozhao") > 0) {
       BaozhaoTopicDecoder mDecoder = new BaozhaoTopicDecoder();
       resulTopicM = mDecoder.decode(htmlString);
     } else {
       TopicDecoder mDecoder = new TopicDecoder();
       resulTopicM = mDecoder.decode(htmlString);
     }
     return resulTopicM;
   } else {
     return null;
   }
 }
  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

    if (!dualScreen) {
      if (null == onItemClickNewActivity) {
        onItemClickNewActivity = new EnterJsonArticle(this);
      }
      onItemClickNewActivity.onItemClick(parent, view, position, id);

    } else {
      String guid = (String) parent.getItemAtPosition(position);
      if (StringUtil.isEmpty(guid)) return;

      guid = guid.trim();

      int pid = StringUtil.getUrlParameter(guid, "pid");
      int tid = StringUtil.getUrlParameter(guid, "tid");
      int authorid = StringUtil.getUrlParameter(guid, "authorid");
      ArticleContainerFragment f = ArticleContainerFragment.create(tid, pid, authorid);
      FragmentManager fm = getSupportFragmentManager();
      FragmentTransaction ft = fm.beginTransaction();

      ft.replace(R.id.item_detail_container, f);
      Fragment f1 = fm.findFragmentById(R.id.item_list);
      f1.setHasOptionsMenu(false);
      f.setHasOptionsMenu(true);
      ft.commit();

      ListView listview = (ListView) parent;
      Object a = parent.getAdapter();
      TopicListAdapter adapter = null;
      if (a instanceof TopicListAdapter) {
        adapter = (TopicListAdapter) a;
      } else if (a instanceof HeaderViewListAdapter) {
        HeaderViewListAdapter ha = (HeaderViewListAdapter) a;
        adapter = (TopicListAdapter) ha.getWrappedAdapter();
        position -= ha.getHeadersCount();
      }
      adapter.setSelected(position);
      listview.setItemChecked(position, true);
    }
  }
  private int getUrlParameter(String url, String paraName) {
    if (StringUtil.isEmpty(url)) {
      return 0;
    }
    final String pattern = paraName + "=";
    int start = url.indexOf(pattern);
    if (start == -1) return 0;
    start += pattern.length();
    int end = url.indexOf("&", start);
    if (end == -1) end = url.length();
    String value = url.substring(start, end);
    int ret = 0;
    try {
      ret = Integer.parseInt(value);
    } catch (Exception e) {
      Log.e(TAG, "invalid url:" + url);
    }

    return ret;
  }
  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    String guid = (String) parent.getItemAtPosition(position);
    if (StringUtil.isEmpty(guid)) return;

    guid = guid.trim();

    int pid = StringUtil.getUrlParameter(guid, "pid");
    int tid = StringUtil.getUrlParameter(guid, "tid");
    int authorid = StringUtil.getUrlParameter(guid, "authorid");

    Intent intent = new Intent();
    intent.putExtra("tab", "1");
    intent.putExtra("tid", tid);
    intent.putExtra("pid", pid);
    intent.putExtra("authorid", authorid);
    if (fromreplyactivity) {
      intent.putExtra("fromreplyactivity", 1);
    }
    ListView listview = (ListView) parent;
    Object a = parent.getAdapter();
    TopicListAdapter adapter = null;
    if (a instanceof TopicListAdapter) {
      adapter = (TopicListAdapter) a;
    } else if (a instanceof HeaderViewListAdapter) {
      HeaderViewListAdapter ha = (HeaderViewListAdapter) a;
      adapter = (TopicListAdapter) ha.getWrappedAdapter();
      position -= ha.getHeadersCount();
    }
    adapter.setSelected(position);
    listview.setItemChecked(position, true);

    intent.setClass(activity, PhoneConfiguration.getInstance().articleActivityClass);
    activity.startActivity(intent);
    if (PhoneConfiguration.getInstance().showAnimation)
      activity.overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
  }
    @Override
    public MeiziTopicMData decode(String html) {
      MeiziTopicMData resulTopicM = new MeiziTopicMData();

      Document document = Jsoup.parse(html);

      // get title string
      resulTopicM.title = document.select("div.main-header h2").html().trim();
      // get doubanPosterUrl and doubanTopicurl
      Elements urlElements = document.select("ul.clx li.widgets-views a");
      if (urlElements.size() >= 1) {
        resulTopicM.doubanTopicUrl = urlElements.get(0).attr("href");
      }
      String dateString = document.select("div.main-meta.clx span.post-span").html().trim();
      try {
        if (!StringUtil.isEmpty(dateString)) resulTopicM.date = MeiziDateUtil.getDate(dateString);
      } catch (ParseException e) {
      }

      // get the main content, pictures and messages
      Elements contentElements = document.select("div.main-body").first().children();

      for (int i = 0; i < contentElements.size(); i++) {
        Element element = contentElements.get(i);
        String tagName = element.tagName();
        if (tagName.equals("p")) {
          // in case incorrect syntax
          Elements pImgElements = element.select("img");
          if (pImgElements.size() != 0) {
            for (int j = 0; j < pImgElements.size(); j++) {
              TopicContentItem item = new TopicContentItem();
              item.type = ContentItemType.IMAGE;
              item.imgUrl = pImgElements.get(j).attr("src");

              if (!TextUtils.isEmpty(item.imgUrl)) {
                resulTopicM.content.add(item);
              }
            }
          } else {
            TopicContentItem item = new TopicContentItem();
            item.type = ContentItemType.MSG;
            String pContent = contentElements.get(i).html();
            item.msg = Html.fromHtml(pContent).toString().trim();

            if (!TextUtils.isEmpty(item.msg)) {
              resulTopicM.content.add(item);
            }
          }
        } else if (tagName.equals("div")) {
          TopicContentItem item = new TopicContentItem();
          item.type = ContentItemType.IMAGE;
          Elements divElements = element.select("img");
          Element imgElement = divElements.first();
          if (imgElement != null) {
            item.imgUrl = imgElement.attr("src");
          }

          if (!TextUtils.isEmpty(item.imgUrl)) {
            resulTopicM.content.add(item);
          }
        } else if (tagName.equals("img")) {
          TopicContentItem item = new TopicContentItem();
          item.type = ContentItemType.IMAGE;
          item.imgUrl = element.attr("src");

          if (!TextUtils.isEmpty(item.imgUrl)) {
            resulTopicM.content.add(item);
          }
        }
      }

      return resulTopicM;
    }
  public View getView(int position, View view, ViewGroup parent) {
    final ThreadRowInfo row = data.getRowList().get(position);

    int lou = -1;
    if (row != null) lou = row.getLou();
    ViewHolder holder = null;
    boolean needin = false;
    SoftReference<View> ref = viewCache.get(position);
    View cachedView = null;
    if (ref != null) {
      cachedView = ref.get();
    }
    if (cachedView != null) {
      if (((ViewHolder) cachedView.getTag()).position == position) {
        Log.d(TAG, "get view from cache ,floor " + lou);
        return cachedView;
      } else {
        view = LayoutInflater.from(activity).inflate(R.layout.relative_aritclelist, parent, false);
        holder = initHolder(view);
        holder.position = position;
        view.setTag(holder);
        viewCache.put(position, new SoftReference<View>(view));
      }
    } else {
      view = LayoutInflater.from(activity).inflate(R.layout.relative_aritclelist, parent, false);
      holder = initHolder(view);
      holder.position = position;
      view.setTag(holder);
      viewCache.put(position, new SoftReference<View>(view));
    }
    if (!PhoneConfiguration.getInstance().showReplyButton) {
      holder.viewBtn.setVisibility(View.GONE);
    } else {
      MyListenerForReply myListenerForReply = new MyListenerForReply(position, data, activity);
      holder.viewBtn.setOnClickListener(myListenerForReply);
    }
    ThemeManager theme = ThemeManager.getInstance();
    int colorId = theme.getBackgroundColor(position);
    view.setBackgroundResource(colorId);

    // colorId = theme.getBackgroundColor(2);

    if (row == null) {
      return view;
    }

    handleAvatar(holder.avatarIV, row);

    int fgColorId = ThemeManager.getInstance().getForegroundColor();
    final int fgColor = parent.getContext().getResources().getColor(fgColorId);

    FunctionUtil.handleNickName(row, fgColor, holder.nickNameTV, activity);

    final int bgColor = parent.getContext().getResources().getColor(colorId);

    final WebView contentTV = holder.contentTV;

    final String floor = String.valueOf(lou);
    TextView floorTV = holder.floorTV;
    floorTV.setText("[" + floor + " 楼]");
    floorTV.setTextColor(fgColor);

    if (!StringUtil.isEmpty(row.getFromClientModel())) {
      MyListenerForClient myListenerForClient =
          new MyListenerForClient(position, data, activity, parent);
      String from_client_model = row.getFromClientModel();
      if (from_client_model.equals("ios")) {
        holder.clientBtn.setImageResource(R.drawable.ios); // IOS
      } else if (from_client_model.equals("wp")) {
        holder.clientBtn.setImageResource(R.drawable.wp); // WP
      } else if (from_client_model.equals("unknown")) {
        holder.clientBtn.setImageResource(R.drawable.unkonwn); // 未知orBB
      }
      holder.clientBtn.setVisibility(View.VISIBLE);
      holder.clientBtn.setOnClickListener(myListenerForClient);
    }
    if (ActivityUtil.isLessThan_4_3()) {
      new Thread(
              new Runnable() {
                public void run() {
                  FunctionUtil.handleContentTV(
                      contentTV, row, bgColor, fgColor, activity, null, client);
                }
              })
          .start();
    } else if (ActivityUtil.isLessThan_4_4()) {
      ((Activity) parent.getContext())
          .runOnUiThread(
              new Runnable() {
                public void run() {
                  FunctionUtil.handleContentTV(
                      contentTV, row, bgColor, fgColor, activity, null, client);
                }
              });
    } else {
      FunctionUtil.handleContentTV(contentTV, row, bgColor, fgColor, activity, null, client);
    }
    TextView postTimeTV = holder.postTimeTV;
    postTimeTV.setText(row.getPostdate());
    postTimeTV.setTextColor(fgColor);
    if (needin) {
      view.invalidate();
    }
    return view;
  }
 private static String buildVote(ThreadRowInfo row) {
   if (row == null || StringUtil.isEmpty(row.getVote())) {
     return "";
   }
   return "<br/><hr/>" + "本楼有投票/投注内容,长按本楼在菜单中点击投票/投注按钮";
 }
  /*
   * (non-Javadoc)
   *
   * @see android.app.Activity#onCreate(android.os.Bundle)
   */
  @Override
  protected void onCreate(Bundle savedInstanceState) {

    int orentation = ThemeManager.getInstance().screenOrentation;
    if (orentation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
        || orentation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
      setRequestedOrientation(orentation);
    } else {
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
    }

    super.onCreate(savedInstanceState);
    v = this.getLayoutInflater().inflate(R.layout.messagereply, null);
    v.setBackgroundColor(getResources().getColor(ThemeManager.getInstance().getBackgroundColor()));
    this.setContentView(v);

    if (PhoneConfiguration.getInstance().uploadLocation
        && PhoneConfiguration.getInstance().location == null) {
      ActivityUtil.reflushLocation(this);
    }

    Intent intent = this.getIntent();
    prefix = intent.getStringExtra("prefix");
    // if(prefix!=null){
    // prefix=prefix.replaceAll("\\n\\n", "\n");
    // }
    tousername = intent.getStringExtra("to");
    action = intent.getStringExtra("action");
    mid = intent.getIntExtra("mid", 0);
    String title = intent.getStringExtra("title");

    titleText = (EditText) findViewById(R.id.reply_titile_edittext);
    toText = (EditText) findViewById(R.id.reply_titile_edittext_to);
    bodyText = (EditText) findViewById(R.id.reply_body_edittext);

    if (action.equals("new")) {
      getSupportActionBar().setTitle(R.string.new_message);
    } else if (action.equals("reply")) {
      getSupportActionBar().setTitle(R.string.reply_message);
    }
    titleText.setSelected(true);

    act = new MessagePostAction(mid, "", "");
    act.setAction_(action);
    this.act.set__ngaClientChecksum(FunctionUtil.getngaClientChecksum(this));
    loading = false;

    if (!StringUtil.isEmpty(tousername)) {
      toText.setText(tousername);
      if (!StringUtil.isEmpty(title)) {
        titleText.setText(title);
      }
    } else {
      if (!StringUtil.isEmpty(title)) {
        titleText.setText(title);
      }
    }
    if (prefix != null) {
      if (prefix.startsWith("[quote][pid=") && prefix.endsWith("[/quote]\n")) {
        SpannableString spanString = new SpannableString(prefix);
        spanString.setSpan(
            new BackgroundColorSpan(-1513240),
            0,
            prefix.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        spanString.setSpan(
            new StyleSpan(android.graphics.Typeface.BOLD),
            prefix.indexOf("[b]Post by"),
            prefix.indexOf("):[/b]") + 5,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        bodyText.append(spanString);
      } else {
        bodyText.append(prefix);
      }
      bodyText.setSelection(prefix.length());
    }
    ThemeManager tm = ThemeManager.getInstance();
    if (tm.getMode() == ThemeManager.MODE_NIGHT) {
      bodyText.setBackgroundResource(tm.getBackgroundColor());
      toText.setBackgroundResource(tm.getBackgroundColor());
      titleText.setBackgroundResource(tm.getBackgroundColor());
      int textColor = this.getResources().getColor(tm.getForegroundColor());
      bodyText.setTextColor(textColor);
      titleText.setTextColor(textColor);
      toText.setTextColor(textColor);
    }
  }
  @SuppressWarnings("deprecation")
  @Override
  public int finishUpload(String attachments, String attachmentsCheck, String picUrl, Uri uri) {
    String selectedImagePath2 = FunctionUtil.getPath(this, uri);
    final int index = bodyText.getSelectionStart();
    this.act.appendAttachments_(attachments);
    act.appendAttachments_check_(attachmentsCheck);
    String spantmp = "[img]./" + picUrl + "[/img]";
    if (!StringUtil.isEmpty(selectedImagePath2)) {
      BitmapFactory.Options options = new BitmapFactory.Options();
      options.inJustDecodeBounds = true;
      Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath2, options); // 此时返回 bm 为空
      options.inJustDecodeBounds = false;
      DisplayMetrics dm = new DisplayMetrics();
      getWindowManager().getDefaultDisplay().getMetrics(dm);
      int screenwidth = (int) (dm.widthPixels * 0.75);
      int screenheigth = (int) (dm.heightPixels * 0.75);
      int width = options.outWidth;
      int height = options.outHeight;
      float scaleWidth = ((float) screenwidth) / width;
      float scaleHeight = ((float) screenheigth) / height;
      if (scaleWidth < scaleHeight && scaleWidth < 1f) { // 不能放大啊,然后主要是哪个小缩放到哪个就行了
        options.inSampleSize = (int) (1 / scaleWidth);
      } else if (scaleWidth >= scaleHeight && scaleHeight < 1f) {
        options.inSampleSize = (int) (1 / scaleHeight);
      } else {
        options.inSampleSize = 1;
      }
      bitmap = BitmapFactory.decodeFile(selectedImagePath2, options);
      BitmapDrawable bd = new BitmapDrawable(bitmap);
      Drawable drawable = (Drawable) bd;
      drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
      SpannableString spanStringS = new SpannableString(spantmp);
      ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
      spanStringS.setSpan(span, 0, spantmp.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

      if (bodyText.getText().toString().replaceAll("\\n", "").trim().equals("")) { // NO INPUT DATA
        bodyText.append(spanStringS);
        bodyText.append("\n");
      } else {
        if (index <= 0 || index >= bodyText.length()) { // pos @ begin /
          // end
          if (bodyText.getText().toString().endsWith("\n")) {
            bodyText.append(spanStringS);
            bodyText.append("\n");
          } else {
            bodyText.append("\n");
            bodyText.append(spanStringS);
            bodyText.append("\n");
          }
        } else {
          bodyText.getText().insert(index, spanStringS);
        }
      }
    } else {
      if (bodyText.getText().toString().replaceAll("\\n", "").trim().equals("")) { // NO INPUT DATA
        bodyText.append("[img]./" + picUrl + "[/img]\n");
      } else {
        if (index <= 0 || index >= bodyText.length()) { // pos @ begin /
          // end
          if (bodyText.getText().toString().endsWith("\n")) {
            bodyText.append("[img]./" + picUrl + "[/img]\n");
          } else {
            bodyText.append("\n[img]./" + picUrl + "[/img]\n");
          }
        } else {
          bodyText.getText().insert(index, "[img]./" + picUrl + "[/img]");
        }
      }
    }
    InputMethodManager imm =
        (InputMethodManager) bodyText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
    return 1;
  }
Пример #18
0
  @Override
  public boolean onContextItemSelected(MenuItem item) {

    Log.d(TAG, "onContextItemSelected,tid=" + tid + ",page=" + page);
    PagerOwnner father = null;
    try {
      father = (PagerOwnner) getActivity();
    } catch (ClassCastException e) {
      Log.e(TAG, "father activity does not implements interface " + PagerOwnner.class.getName());
      return true;
    }

    if (father == null) return false;

    if (father.getCurrentPage() != page) {
      return false;
    }

    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
    int position = this.listview.getCheckedItemPosition();
    if (info != null) {
      position = info.position;
    }
    if (position < 0 || position >= listview.getAdapter().getCount()) {
      Toast.makeText(getActivity(), R.string.floor_error, Toast.LENGTH_LONG).show();
      position = 0;
    }
    StringBuffer postPrefix = new StringBuffer();
    String tidStr = String.valueOf(this.tid);

    ThreadRowInfo row = (ThreadRowInfo) listview.getItemAtPosition(position);
    if (row == null) {
      Toast.makeText(getActivity(), R.string.unknow_error, Toast.LENGTH_LONG).show();
      return true;
    }
    String content = row.getContent();
    final String name = row.getAuthor();
    String mention = null;
    Intent intent = new Intent();
    switch (item.getItemId())
    // if( REPLY_POST_ORDER ==item.getItemId())
    {
      case R.id.quote_subject:
        final String quote_regex = "\\[quote\\]([\\s\\S])*\\[/quote\\]";
        final String replay_regex =
            "\\[b\\]Reply to \\[pid=\\d+,\\d+,\\d+\\]Reply\\[/pid\\] Post by .+?\\[/b\\]";
        content = content.replaceAll(quote_regex, "");
        content = content.replaceAll(replay_regex, "");
        final String postTime = row.getPostdate();

        if (!content.trim().endsWith("[/url]")) {
          if (content.length() > 100) content = content.substring(0, 99) + ".......";
        }
        content = StringUtil.unEscapeHtml(content);

        if (row.getPid() != 0) {
          mention = name;
          postPrefix.append("[quote][pid=");
          postPrefix.append(row.getPid());
          postPrefix.append(',').append(tidStr).append(",").append(page);
          postPrefix.append("]"); // Topic
          postPrefix.append("Reply");
          postPrefix.append("[/pid] [b]Post by ");
          postPrefix.append(name);
          postPrefix.append(" (");
          postPrefix.append(postTime);
          postPrefix.append("):[/b]\n");
          postPrefix.append(content);
          postPrefix.append("[/quote]\n");
        }

        // case R.id.r:

        if (!StringUtil.isEmpty(mention)) intent.putExtra("mention", mention);
        intent.putExtra("prefix", StringUtil.removeBrTag(postPrefix.toString()));
        intent.putExtra("tid", tidStr);
        intent.putExtra("action", "reply");
        intent.setClass(getActivity(), PostActivity.class);
        startActivity(intent);
        if (PhoneConfiguration.getInstance().showAnimation)
          getActivity().overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
        break;
      case R.id.edit:
        if (isComment(row)) {
          Toast.makeText(getActivity(), R.string.cannot_eidt_comment, Toast.LENGTH_SHORT).show();
          break;
        }
        Intent intentModify = new Intent();
        intentModify.putExtra("prefix", StringUtil.unEscapeHtml(StringUtil.removeBrTag(content)));
        intentModify.putExtra("tid", tidStr);
        String pid = String.valueOf(row.getPid()); // getPid(map.get("url"));
        intentModify.putExtra("pid", pid);
        intentModify.putExtra("title", StringUtil.unEscapeHtml(row.getSubject()));
        intentModify.putExtra("action", "modify");
        intentModify.setClass(getActivity(), PostActivity.class);
        startActivity(intentModify);
        if (PhoneConfiguration.getInstance().showAnimation)
          getActivity().overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
        break;
      case R.id.copy_to_clipboard:
        // if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB )
        // {
        android.text.ClipboardManager cbm =
            (android.text.ClipboardManager)
                getActivity().getSystemService(Activity.CLIPBOARD_SERVICE);
        cbm.setText(StringUtil.removeBrTag(content));
        // }else{
        // android.content.ClipboardManager  cbm = (android.content.ClipboardManager)
        // getSystemService(CLIPBOARD_SERVICE);
        // cbm.setPrimaryClip(ClipData.newPlainText("content", content));
        // }

        Toast.makeText(getActivity(), R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show();
        break;
      case R.id.show_this_person_only:
        Intent intentThis = new Intent();
        intentThis.putExtra("tab", "1");
        intentThis.putExtra("tid", tid);
        intentThis.putExtra("authorid", row.getAuthorid());

        intentThis.setClass(getActivity(), PhoneConfiguration.getInstance().articleActivityClass);
        startActivity(intentThis);
        if (PhoneConfiguration.getInstance().showAnimation)
          getActivity().overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);

        // restNotifier.reset(0, row.getAuthorid());
        // ActivityUtil.getInstance().noticeSaying(getActivity());

        break;
      case R.id.show_whole_thread:
        ResetableArticle restNotifier = null;
        try {
          restNotifier = (ResetableArticle) getActivity();
        } catch (ClassCastException e) {
          Log.e(
              TAG,
              "father activity does not implements interface " + ResetableArticle.class.getName());
          return true;
        }
        restNotifier.reset(0, 0, row.getLou());
        ActivityUtil.getInstance().noticeSaying(getActivity());
        break;
      case R.id.post_comment:
        final String dialog_tag = "post comment";
        FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
        Fragment prev = getActivity().getSupportFragmentManager().findFragmentByTag(dialog_tag);
        if (prev != null) {
          ft.remove(prev);
        }
        DialogFragment df = new PostCommentDialogFragment();
        Bundle b = new Bundle();
        b.putInt("pid", row.getPid());
        b.putInt("tid", this.tid);
        df.setArguments(b);
        df.show(ft, dialog_tag);

        break;
      case R.id.report:
        handleReport(row);
        break;
      case R.id.search_post:
        intent.putExtra("searchpost", 1);
      case R.id.search_subject:
        intent.putExtra("authorid", row.getAuthorid());
        intent.setClass(getActivity(), PhoneConfiguration.getInstance().topicActivityClass);
        startActivity(intent);
        if (PhoneConfiguration.getInstance().showAnimation)
          getActivity().overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);

        break;
      case R.id.item_share:
        intent.setAction(Intent.ACTION_SEND);
        intent.setType("text/plain");
        String shareUrl = "http://bbs.ngacn.cc/read.php?";
        if (row.getPid() != 0) {
          shareUrl = shareUrl + "pid=" + row.getPid();
        } else {
          shareUrl = shareUrl + "tid=" + tid;
        }
        intent.putExtra(Intent.EXTRA_TEXT, shareUrl);
        String text = getResources().getString(R.string.share);
        getActivity().startActivity(Intent.createChooser(intent, text));
        break;
    }
    return true;
  }
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.upload:
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, REQUEST_CODE_SELECT_PIC);
        break;
      case R.id.emotion:
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        Fragment prev = getSupportFragmentManager().findFragmentByTag(EMOTION_CATEGORY_TAG);
        if (prev != null) {
          ft.remove(prev);
        }

        DialogFragment newFragment = new EmotionCategorySelectFragment();
        newFragment.show(ft, EMOTION_CATEGORY_TAG);
        break;
      case R.id.supertext:
        FunctionUtil.handleSupertext(bodyText, this, v);
        break;
      case R.id.send:
        if (StringUtil.isEmpty(toText.getText().toString())) {
          if (toast != null) {
            toast.setText("请输入收件人");
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.show();
          } else {
            toast = Toast.makeText(MessagePostActivity.this, "请输入收件人", Toast.LENGTH_SHORT);
            toast.show();
          }
        } else if (StringUtil.isEmpty(titleText.getText().toString())) {
          if (toast != null) {
            toast.setText("请输入标题");
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.show();
          } else {
            toast = Toast.makeText(MessagePostActivity.this, "请输入标题", Toast.LENGTH_SHORT);
            toast.show();
          }
        } else if (StringUtil.isEmpty(bodyText.getText().toString())) {
          if (toast != null) {
            toast.setText("请输入内容");
            toast.setDuration(Toast.LENGTH_SHORT);
            toast.show();
          } else {
            toast = Toast.makeText(MessagePostActivity.this, "请输入内容", Toast.LENGTH_SHORT);
            toast.show();
          }
        } else {
          if (commitListener == null) {
            commitListener = new ButtonCommitListener(REPLY_URL);
          }
          commitListener.onClick(null);
        }
        break;
      default:
        finish();
    }
    return true;
  } // OK