Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

源碼剖析(五):KeyboardFragment 打造文字與表情評論發表面板

編輯:關於 Android 程式設計

說白了就是這個大家都很熟悉的功能:

這個功能牽扯到不少類別,我一個一個來拆解。

KeyboardFragment 類別

/** 底部帶 emotion 面板的文字和表情評論功能的 Fragment **/
public class KeyboardFragment extends BaseTabNavFragment {
    @Bind(R.id.et_input) EditText mInput;          // 輸入框
    @Bind(R.id.emotion_layout) LinearLayout mEmoLayout; // 表情的布局
    @Bind(R.id.iv_emotion) ImageView mIvEmotion;   // 發布評論的圖片
    private Comment mReplyCmm;                     // 回復的對象
    private KeyboardActionDelegation mDelegatioin; // 委托類,管理鍵盤、emotion 按鈕、輸入框、emotion 面板之間的相互操作

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_keyboard, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ButterKnife.bind(this, view);
        mDelegatioin = new KeyboardActionDelegation(mContext, mInput, mIvEmotion, mEmoLayout);
        initSubscribers();
        mViewPager.setCurrentItem(0);
    }

    /** 注冊事件訂閱者 */
    private void initSubscribers() {
        // 接收用戶選中某個表情的事件
        RxBus.with(this)
            .setEvent(Events.EventEnum.DELIVER_SELECT_EMOTION)
            .setEndEvent(FragmentEvent.DESTROY)
            .onNext((events -> {
                EmotionRules emotion = events.getMessage();
                mDelegatioin.onEmotionItemSelected(emotion);
            })).create();
        // 接收返回事件:顯示表情面板則隱藏,顯示軟鍵盤則隱藏,顯示回復某人則隱藏
        RxBus.with(this)
            .setEvent(Events.EventEnum.DELIVER_GO_BACK)
            .setEndEvent(FragmentEvent.DESTROY)
            .onNext((events -> {
                if (mReplyCmm != null) {
                    mInput.setHint(getResources().getString(R.string.please_say_something));
                    mReplyCmm = null;
                    return;
                }
                if (!mDelegatioin.onTurnBack()) return;
                RxBus.getInstance().send(Events.EventEnum.WE_HIDE_ALL, null);
            })).create();
        // 接收回復某人的事件
        RxBus.with(this)
            .setEvent(Events.EventEnum.DELIVER_REPLY_SOMEONE)
            .setEndEvent(FragmentEvent.DESTROY)
            .onNext((events -> {
                mReplyCmm = events.getMessage();
                mInput.setHint("回復 @" + mReplyCmm.getAuthor());
            })).create();
        // 接收清空輸入框事件
        RxBus.with(this)
            .setEvent(Events.EventEnum.DELIVER_CLEAR_IMPUT)
            .setEndEvent(FragmentEvent.DESTROY)
            .onNext((events -> {
                mInput.setHint(getResources().getString(R.string.please_say_something));
                mInput.setText(null);
            })).create();
    }

    @Override
    public View setupTabItemView(String title) {
        ImageView view = new ImageView(mContext);
        view.setImageResource(R.mipmap.icon_emotion_color);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MATCH_PARENT);
        params.weight = 1;
        view.setLayoutParams(params);
        return view;
    }

    @Override
    public void onSetupTabs() {
        addTab(getResources().getString(R.string.emotion_qq), EmotionPanelFragment.class);
    }

    /** 總在前面添加元素,跟默認基類做法相悖,所以復寫 */
    @Override
    public void addTab(String title, Class fragment) {
        mTabs.add(0, new ViewPageInfo(title, Fragment.instantiate(getActivity(), fragment.getName())));
        View view = setupTabItemView(title);
        mNavLayout.addView(view, 0);
        mTabs.get(0).view = view;
    }

    @OnClick(R.id.iv_backspace)
    public void removeEmotion() {
        InputHelper.backspace(mInput);
    }

    @OnClick(R.id.iv_send)
    public void sendComment() {
        if (Utilities.isEmpty(mInput.getText().toString())) {
            Toast.makeText(mContext, "別鬧,寫點東西再發", Toast.LENGTH_SHORT).show();
            return;
        }
        if (AppManager.LOCAL_LOGINED_USER == null) {
            UIManager.jump2login(mContext);
            return;
        }
        Comment comment = new Comment();
        if (mReplyCmm == null) {
            comment.setId(-1L);
        } else {
            comment.setId(mReplyCmm.getId());
            comment.setAuthorId(mReplyCmm.getAuthorId());
        }
        comment.setContent(mInput.getText().toString());
        Events<Comment> events = Events.just(comment);
        events.what = Events.EventEnum.DELIVER_SEND_COMMENT;
        RxBus.getInstance().send(events);
    }
}

這個類別主要負責搭建底部評論功能的布局(靠著強大的父類 BaseTabNavFragment,只要復寫 setupItemView()、onSetupTabs() 與 addTab() 即可),並用 RxBus 注冊了一連串與評論相關的事件接收者;點擊評論按鈕時,把評論內容封裝成物件後透過 RxBus 發送出去。

這個類別最精彩之處,就是一連串的 RxBus 用法,從中也能感受到 RxJava 的強大與順手。

代碼裡還有一個委托類物件,它相當關鍵,負責管理軟鍵盤、emotion 按鈕、輸入框與 emotion 面板之間的關聯操作:

mDelegatioin = new KeyboardActionDelegation(mContext, mInput, mIvEmotion, mEmoLayout);

KeyboardActionDelegation 類別

/** 鍵盤、emotion 按鈕、輸入框、emotion 面板之間的相互關系委派給這個類管理 */
public class KeyboardActionDelegation {
    private ImageView mBtnEmotion;   // Emotion 按鈕
    private EditText mInput;         // 輸入框
    private Context mContext;
    private ViewGroup mEmotionPanel; // Emotion 面板
    private boolean isShowSoftInput; // 是否顯示輸入法

    public KeyboardActionDelegation(Context context, EditText input, ImageView button, ViewGroup view) {
        this.mBtnEmotion = button;
        this.mInput = input;
        this.mContext = context;
        this.mEmotionPanel = view;
        init();
    }

    private void init() {
        mInput.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) hideEmotionPanel();
                else hideSoftKeyboard();
            }
        });
        mInput.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isEmotionPanelShowing()) return;
                hideEmotionPanel();
            }
        });
        mBtnEmotion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isEmotionPanelShowing()) hideEmotionPanel();
                else showEmotionPanel();
            }
        });
    }

    public void showEmotionPanel() {
        mBtnEmotion.setSelected(true);
        hideSoftKeyboard();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mEmotionPanel.setVisibility(View.VISIBLE);
            }
        }, 300);
    }

    private boolean isEmotionPanelShowing() {
        return mEmotionPanel.getVisibility() == View.VISIBLE;
    }

    private void hideSoftKeyboard() {
        DeviceManager.getSoftInputManager(mContext).hideSoftInputFromWindow(mInput.getWindowToken(), 0);
        isShowSoftInput = false;
    }

    private void hideEmotionPanel() {
        mEmotionPanel.setVisibility(View.GONE);
        mBtnEmotion.setSelected(false);
    }

    public boolean isShowSoftInput() {
        return isShowSoftInput;
    }

    /** Emotion 面板中 item 被選中 */
    public void onEmotionItemSelected(EmotionRules emotion) {
        if (mInput == null || emotion == null) return;
        int start = mInput.getSelectionStart();
        int end = mInput.getSelectionEnd();
        if (start == end) {
            mInput.append(InputHelper.insertEtn(mContext, emotion));
        } else {
            Spannable str = InputHelper.insertEtn(mContext, emotion);
            mInput.getText().replace(Math.min(start, end), Math.max(start, end), str, 0, str.length());
        }
    }

    /** 使用回退鍵時,讓 Emotion 面板和輸入法都隱藏 */
    public boolean onTurnBack() {
        if (isEmotionPanelShowing()) {
            hideEmotionPanel();
            return false;
        }
        if (isShowSoftInput()) {
            hideEmotionPanel();
            return false;
        }
        return true;
    }
}

這個類別其實就是在管理各種狀態的切換,判斷該顯示還是隱藏輸入法、Emotion 面板等等。其中比較關鍵的是 onEmotionItemSelected(),也就是表情被選中之後的處理邏輯:若編輯框裡有選中文字,就用表情替換它;若沒有選中,就直接插入到光標後面。這個方法在上面的 KeyboardFragment 中被調用。

InputHelper 類別

/** 輸入幫助類 */
public class InputHelper {
    /** 退格 */
    public static void backspace(EditText input) {
        if (input == null) return;
        KeyEvent event = new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_DEL, 0, 0, 0, 0, KeyEvent.KEYCODE_ENDCALL);
        input.dispatchKeyEvent(event);
    }

    /** 插入表情到文字中,使用 SpannableString 和 ImageSpan 實現圖文混排 */
    @SuppressWarnings("all")
    public static Spannable insertEtn(Context context, EmotionRules emotion) {
        String remote = emotion.getRemote();
        Spannable spannable = new SpannableString(remote);
        Drawable d = context.getResources().getDrawable(emotion.getMResId());
        d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
        ImageSpan iSpan = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
        spannable.setSpan(iSpan, 0, remote.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannable;
    }
}

這個類別裡最重要的方法就是 InputHelper#insertEtn(),它藉助 SpannableString 與 ImageSpan 實現了圖文混排的效果。順帶說明一下 setSpan():what 傳入各種 Span 類型的實例,start 與 end 標記要替換的文字范圍,flags 則用來標識在 Span 范圍內前後輸入新字符時是否也套用這個效果,可傳入 SPAN_EXCLUSIVE_EXCLUSIVE、SPAN_INCLUSIVE_EXCLUSIVE、SPAN_EXCLUSIVE_INCLUSIVE、SPAN_INCLUSIVE_INCLUSIVE 幾種參數,INCLUSIVE 表示套用、EXCLUSIVE 表示不套用。

下面這段也可以算是一份模板代碼:

Drawable drawable = mContext.getResources().getDrawable(R.drawable.new_topic_drawable);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
ImageSpan imageSpan = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
spanString.setSpan(imageSpan, spanString.length() - 1, spanString.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);

EmotionPanelFragment 類別

顧名思義,這個類別就是 Emotion 面板的 Fragment,負責把表情填進面板,每一頁都是一個 ViewFragment。

/** Emotion 面板的 Fragment **/
public class EmotionPanelFragment extends BaseTabNavFragment {
    public static final int COLUMN = 7; // 7 列
    public static final int ROW = 3;    // 3 行

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setCurrentItem(0);
    }

    @Override
    public View setupTabItemView(String title) {
        TextView view = new TextView(mContext);
        int m4 = UIHelper.dip2px(mContext, 4);
        LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(m4, m4);
        int m5 = UIHelper.dip2px(mContext, 5);
        layout.setMargins(m5, m5, m5, m5);
        view.setLayoutParams(layout);
        view.setBackgroundResource(R.drawable.selector_dot_nav);
        return view;
    }

    /** 分頁填充表情 */
    @Override
    public void onSetupTabs() {
        EmotionRules[] rules = EmotionRules.values();
        int page_size = COLUMN * ROW;
        int page_count = (rules.length + page_size - 1) / page_size;
        int i;
        for (i = 0; i < page_count - 1; i++) {
            addTab("", initView(i * page_size, (i + 1) * page_size - 1));
        }
        addTab("", initView(i * page_size, rules.length - 1));
    }

    public void addTab(String title, View view) {
        addTab(title, new ViewFragment(view));
    }

    private View initView(int start, int end) {
        final EmotionRules[] rules = Arrays.copyOfRange(EmotionRules.values(), start, end + 1);
        GridView view = new GridView(mContext);
        GridView.LayoutParams params = new GridView.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        view.setLayoutParams(params);
        view.setNumColumns(COLUMN);
        view.setAdapter(new EmotionAdapter(rules));
        view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View view, int position, long id) {
                Events<EmotionRules> events = Events.just(rules[position]);
                events.what = Events.EventEnum.DELIVER_SELECT_EMOTION;
                RxBus.getInstance().send(events);
            }
        });
        return view;
    }

    @Override
    public FragmentManager getGenuineFragmentManager() {
        return getChildFragmentManager();
    }
}

ViewFragment 與 EmotionRules 類別

ViewFragment 內部持有一個 View 物件,可以簡單理解為把一個 View 轉化成 Fragment,特別適合輪播、ViewPager 這類場景。

@SuppressLint("ValidFragment")
public class ViewFragment extends BaseFragment {
    private View view;
    public ViewFragment(View view) { this.view = view; }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return view;
    }
}

至於 EmotionRules,則是一個枚舉類別,把每個表情的類型、圖片、文字含義與序號一一對應起來,命名相當貼切。

/** 定義了 emotion 規則:類型、圖片、文字含義、序號 */
public enum EmotionRules {
    EMOTION0(0, R.mipmap.smiley_0, "[微笑]", "[0]"),
    EMOTION1(0, R.mipmap.smiley_1, "[撇嘴]", "[1]"),
    // ……其餘表情依此類推
    EMOTION54(0, R.mipmap.smiley_54, "[可憐]", "[54]");

    private int type;
    private int mResId;
    private String name;
    private String remote;

    EmotionRules(int type, int mResId, String name, String remote) {
        this.type = type;
        this.mResId = mResId;
        this.name = name;
        this.remote = remote;
    }

    /** 判斷 emotion 的中文含義或序號是否包含指定字符串 */
    public static EmotionRules containOf(String s) {
        for (EmotionRules item : EmotionRules.values()) {
            if (item.getName().equals(s) || item.getRemote().equals(s)) return item;
        }
        return null;
    }
}

至此,這個能發送表情的評論面板功能就分析完畢了。to be continue…

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved