cn.zhangls.android.weibo.ui.edit.EditActivity.java Source code

Java tutorial

Introduction

Here is the source code for cn.zhangls.android.weibo.ui.edit.EditActivity.java

Source

/*
 * MIT License
 *
 * Copyright (c) 2017 zhangls2014
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package cn.zhangls.android.weibo.ui.edit;

import android.content.Context;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatImageView;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;

import com.bumptech.glide.Glide;
import com.sina.weibo.sdk.auth.AuthInfo;

import java.util.ArrayList;

import cn.zhangls.android.weibo.Constants;
import cn.zhangls.android.weibo.R;
import cn.zhangls.android.weibo.common.SwipeActivity;
import cn.zhangls.android.weibo.databinding.ActivityEditBinding;
import cn.zhangls.android.weibo.network.api.StatusesAPI;
import cn.zhangls.android.weibo.network.models.Comment;
import cn.zhangls.android.weibo.network.models.Status;
import cn.zhangls.android.weibo.ui.edit.share.ShareActivity;
import cn.zhangls.android.weibo.utils.SharedPreferenceInfo;
import cn.zhangls.android.weibo.utils.TextUtil;
import cn.zhangls.android.weibo.utils.ToastUtil;

public class EditActivity extends SwipeActivity implements EditContract.EditView {

    private final static String DATA_NAME = "data_name";
    private final static String TYPE_CONTENT = "type_content";
    private final static String COMMENT_INFO = "comment_info";
    /**
     * start ShareActivity request code
     */
    private final static int REQUEST_CODE_SHARE = 1;
    /**
     * start ShareActivity result code
     */
    private final static int RESULT_CODE_SHARE = 1;
    /**
     * EditActivity 0???1??2??3??
     */
    public final static int TYPE_CONTENT_REPOST = 0;
    public final static int TYPE_CONTENT_REPLY = 1;
    public final static int TYPE_CONTENT_COMMENT = 2;
    public final static int TYPE_CONTENT_UPDATE_STATUS = 3;
    /**
     * EditPresenter
     */
    private EditContract.EditPresenter mEditPresenter;
    /**
     * SharedPreferenceInfo
     */
    private SharedPreferenceInfo mPreferenceInfo;
    /**
     * ?
     */
    private Status mStatus;
    /**
     * EditActivity 
     */
    private int mContentType;
    /**
     * MentionComment
     */
    private Comment mComment;
    /**
     * ActivityRepostBinding
     */
    private ActivityEditBinding mBinding;
    /**
     * ???
     */
    private boolean isCommentRepost = false;
    /**
     * Topic ?
     */
    ArrayList<TextUtil.StrHolder> mTopicList;
    /**
     * Name ?
     */
    ArrayList<TextUtil.StrHolder> mNameList;

    /**
     * 
     *
     * @param context     
     * @param status      ??
     * @param contentType EditActivity 
     * @param comment     
     */
    public static void actionStart(Context context, Status status, int contentType, Comment comment) {
        Intent intent = new Intent(context, EditActivity.class);
        intent.putExtra(DATA_NAME, status);
        intent.putExtra(TYPE_CONTENT, contentType);
        intent.putExtra(COMMENT_INFO, comment);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mStatus = getIntent().getParcelableExtra(DATA_NAME);
        mContentType = getIntent().getIntExtra(TYPE_CONTENT, 0);
        mComment = getIntent().getParcelableExtra(COMMENT_INFO);

        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_edit);
        mBinding.setStatus(mStatus);

        new EditPresenter(this.getApplicationContext(), this);
        mEditPresenter.start();

        mPreferenceInfo = new SharedPreferenceInfo(this);

        initialize();
    }

    /**
     * Take care of popping the fragment back stack or finishing the activity
     * as appropriate.
     */
    @Override
    public void onBackPressed() {
        finish();
    }

    /**
     * ??
     */
    private void initialize() {
        // set toolbar
        setSupportActionBar(mBinding.acEditToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setSubTitle();
        // ?"?"
        isCommentRepost = mBinding.acEditCommentRepost.isChecked();
        mBinding.acEditCommentRepost.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isCommentRepost = isChecked;
            }
        });
        switch (mContentType) {
        case TYPE_CONTENT_REPOST:
            mBinding.acEditCommentRepost.setText(R.string.ac_edit_comment);
            getSupportActionBar().setTitle(R.string.activity_repost);
            mBinding.acRepostWeiboSummaryCard.setVisibility(View.VISIBLE);
            mBinding.acEditWeiboVisible.setVisibility(View.VISIBLE);
            mBinding.acEditText.setHint(getString(R.string.ac_edit_edit_text_repost_hint));
            if (mComment == null) {
                setText("//@" + mStatus.getUser().getScreen_name() + ":" + mStatus.getText(), false);
            } else {
                setText("//@" + mComment.getUser().getScreen_name() + ":" + mComment.getText(), true);
            }
            // ???
            setGroup();
            // ???
            setWeiboCard();
            break;
        case TYPE_CONTENT_REPLY:
            mBinding.acEditCommentRepost.setText(R.string.ac_edit_repost);
            getSupportActionBar().setTitle(R.string.activity_reply);
            mBinding.acRepostWeiboSummaryCard.setVisibility(View.GONE);
            mBinding.acEditWeiboVisible.setVisibility(View.GONE);
            if (mComment != null) {
                mBinding.acEditText.setHint(getString(R.string.ac_edit_edit_text_reply_hint) + "@"
                        + mComment.getUser().getScreen_name());
            }
            break;
        case TYPE_CONTENT_COMMENT:
            mBinding.acEditCommentRepost.setText(R.string.ac_edit_repost);
            getSupportActionBar().setTitle(R.string.activity_comment);
            mBinding.acRepostWeiboSummaryCard.setVisibility(View.GONE);
            mBinding.acEditWeiboVisible.setVisibility(View.GONE);
            mBinding.acEditText.setHint(getString(R.string.ac_edit_edit_text_comment_hint));
            break;
        case TYPE_CONTENT_UPDATE_STATUS:
            mBinding.acEditCommentRepost.setVisibility(View.GONE);
            getSupportActionBar().setTitle(R.string.activity_edit_update);
            mBinding.acRepostWeiboSummaryCard.setVisibility(View.GONE);
            mBinding.acEditWeiboVisible.setVisibility(View.VISIBLE);
            mBinding.acEditText.setHint(getString(R.string.ac_edit_edit_text_update_status_hint));
            break;
        }
    }

    /**
     * ????
     */
    private void setWeiboCard() {
        String url;
        if (mStatus.getRetweeted_status() != null) {
            if (mStatus.getRetweeted_status().getPic_urls() != null
                    && mStatus.getRetweeted_status().getPic_urls().size() > 0) {
                //  url ?? url
                url = replaceUrl(mStatus.getRetweeted_status().getPic_urls().get(0).getThumbnail_pic());
            } else {
                url = mStatus.getRetweeted_status().getUser().getAvatar_large();
            }
            mBinding.acRepostWeiboSummaryCard.setTitle(mStatus.getRetweeted_status().getUser().getScreen_name());
            mBinding.acRepostWeiboSummaryCard.setContent(mStatus.getRetweeted_status().getText());
        } else {
            if (mStatus.getPic_urls() != null && mStatus.getPic_urls().size() > 0) {
                //  url ?? url
                url = replaceUrl(mStatus.getPic_urls().get(0).getThumbnail_pic());
            } else {
                url = mStatus.getUser().getAvatar_large();
            }
            mBinding.acRepostWeiboSummaryCard.setTitle(mStatus.getUser().getScreen_name());
            mBinding.acRepostWeiboSummaryCard.setContent(mStatus.getText());
        }
        showPic(url,
                (AppCompatImageView) mBinding.acRepostWeiboSummaryCard.findViewById(R.id.item_summary_picture));
    }

    /**
     * ?
     */
    private void setText(String text, boolean isComment) {
        if (isComment) {
            mBinding.acEditText.setText(TextUtil.convertText(this, text,
                    ContextCompat.getColor(this, R.color.colorAccent), (int) mBinding.acEditText.getTextSize()));
            return;
        }

        if (mStatus.getRetweeted_status() != null) // ?
            mBinding.acEditText.setText(TextUtil.convertText(this, text,
                    ContextCompat.getColor(this, R.color.colorAccent), (int) mBinding.acEditText.getTextSize()));
        // ???????
        mTopicList = TextUtil.findRegexString(mBinding.acEditText.getText().toString(),
                Constants.RegularExpression.TopicRegex);
        mNameList = TextUtil.findRegexString(mBinding.acEditText.getText().toString(),
                Constants.RegularExpression.NameRegex);

        // ? UserName  Topic 
        mBinding.acEditText.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // 
                return keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN
                        && (setSelection(mBinding.acEditText, mTopicList, true)
                                || setSelection(mBinding.acEditText, mNameList, true));
            }
        });
        // EditText ? UserName  Topic ? UserName  Topic ?
        mBinding.acEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // ? Topic Name 
                boolean topic = setSelection(mBinding.acEditText, mTopicList, false);
                if (!topic) {
                    setSelection(mBinding.acEditText, mNameList, false);
                }
            }
        });
    }

    /**
     * 
     *
     * @param editText   EditText 
     * @param list       ????
     * @param isSelected ?
     * @return ??
     */
    private boolean setSelection(AppCompatEditText editText, ArrayList<TextUtil.StrHolder> list,
            boolean isSelected) {
        int selectionStart = editText.getSelectionStart();
        // ?
        if (list == null || list.size() <= 0) {
            return false;
        }
        // ????,
        if (editText.getSelectionStart() != editText.getSelectionEnd() && isSelected) {
            return false;
        }
        int lastPos = 0;
        for (TextUtil.StrHolder strHolder : list) {
            lastPos = editText.getText().toString().indexOf(strHolder.getName(), lastPos);
            if (lastPos != -1) {
                if (selectionStart > lastPos && selectionStart <= lastPos + strHolder.getName().length()) {
                    if (isSelected) {
                        editText.setSelection(lastPos, lastPos + strHolder.getName().length());
                    } else {
                        editText.setSelection(lastPos + strHolder.getName().length());
                    }
                    return true;
                } else {
                    lastPos = lastPos + strHolder.getName().length();
                }
            }
        }
        return false;
    }

    /**
     * ???
     */
    private void setGroup() {
        mBinding.acEditWeiboVisible.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShareActivity.actionStart(EditActivity.this, REQUEST_CODE_SHARE);
            }
        });
    }

    /**
     * 
     *
     * @param picUrl    
     * @param imageView  ImageView
     */
    private void showPic(String picUrl, AppCompatImageView imageView) {
        Glide.with(this).load(picUrl).asBitmap().centerCrop().error(R.drawable.pic_bg)
                .placeholder(R.drawable.pic_bg).into(imageView);
    }

    /**
     * ?URL
     *
     * @param thumbnailUrl URL
     * @return  URL
     */
    private String replaceUrl(String thumbnailUrl) {
        return thumbnailUrl.replace("thumbnail", "bmiddle");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_ac_edit, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            finish();
            break;
        case R.id.ac_edit_menu_send:
            submit();
            break;
        case R.id.ac_edit_menu_open_in_weibo:
            //                openInWeibo();
            break;
        }
        return true;
    }

    /**
     * ???
     */
    private void submit() {
        if (mBinding.acEditText.getText().toString().isEmpty()) {
            ToastUtil.showLongToast(this, "??");
            return;
        }
        switch (mContentType) {
        case TYPE_CONTENT_REPOST:
            mEditPresenter.repost(mStatus.getId(), mBinding.acEditText.getText().toString(),
                    isCommentRepost ? StatusesAPI.COMMENTS_NONE : StatusesAPI.COMMENTS_BOTH, null);
            break;
        case TYPE_CONTENT_REPLY:
            mEditPresenter.reply(mComment.getId(), mStatus.getId(), mBinding.acEditText.getText().toString(), 0, 0);
            break;
        case TYPE_CONTENT_COMMENT:
            mEditPresenter.create(mBinding.acEditText.getText().toString(), mStatus.getId(), 0);
            break;
        case TYPE_CONTENT_UPDATE_STATUS:
            mEditPresenter.updateStatus(mBinding.acEditText.getText().toString(), StatusesAPI.STATUS_VISIBLE_ALL,
                    null);
            break;
        }
    }

    /**
     * ??
     */
    private void openInWeibo() {
        AuthInfo authInfo = new AuthInfo(EditActivity.this, Constants.APP_KEY, Constants.REDIRECT_URL,
                Constants.SCOPE);
        //        WeiboPageUtils
        //                .getInstance(EditActivity.this, authInfo)
        //                .commentWeibo(, false);
    }

    @Override
    public void setSubTitle() {
        String userName = mPreferenceInfo.getUserName();
        if (userName != null && !userName.isEmpty()) {
            getSupportActionBar().setSubtitle(userName);
        } else {
            mEditPresenter.getUserByService();
        }
    }

    /**
     * ???
     */
    @Override
    public void submitCompleted() {
        onBackPressed();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SHARE && resultCode == RESULT_CODE_SHARE) {

        }
    }

    /**
     * Presenter
     *
     * @param presenter presenter
     */
    @Override
    public void setPresenter(EditContract.EditPresenter presenter) {
        mEditPresenter = presenter;
    }

    /**
     *  Snackbar
     */
    @Override
    public void showLoginSnackbar() {
        showLoginSnackbar(mBinding.acEditToolbar);
    }
}