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

自定義控件實戰:組合出帶書簽的 PDF 閱讀器

編輯:關於 Android 程式設計

前言

Android 端展示文檔,常見做法是轉成 HTML 塞進 WebView。這條路徑的優點是能配合 HTML5、CSS、JS 做出精美排版,缺點是門檻不低。本文換個思路:基於開源的 AndroidTreeView 與 AndroidPdfViewer,組合出一個「帶書簽的 PDF 閱讀器」控件,點擊書簽可展開收起並跳轉到對應頁面。

自定義 View 的兩條路

組合控件:把現有基礎控件拼裝起來達成複用,例如本文的 MyPDFViewer。難點在業務邏輯的組織。

完全自定義控件:直接繼承 View、TextureView 或 SurfaceView,按需重寫 onMeasure、onLayout、onDraw、onTouchEvent 等回調。難點在設計、性能優化與排版計算。

步驟一:建項目與加依賴

新建 Android Phone and Tablet 項目,再添加一個 Android Library 模塊,控件實現在庫中,便於複用。庫模塊的 build.gradle 加入:

compile 'com.github.barteksc:android-pdf-viewer:2.1.0'
compile 'com.github.bmelnychuk:atv:1.2.+'

步驟二:聲明自定義屬性

控件需要三個屬性:是否顯示書簽、書簽佔的權重、內容佔的權重。

<resources>
    <declare-styleable name="MyPDFView">
        <attr name="bookmark_visiable" format="boolean" />
        <attr name="bookmark_weight" format="dimension" />
        <attr name="content_weight" format="dimension" />
    </declare-styleable>
</resources>

步驟三:書簽節點 Holder

AndroidTreeView 要求自定義節點繼承 TreeNode.BaseNodeViewHolder 並重寫 createNodeView()。節點由一個 TextView 加兩個 ImageView 組成:箭頭表示展開狀態,書籤圖標做裝飾,葉節點隱藏箭頭。

public class BookMarkTreeItemHolder extends TreeNode.BaseNodeViewHolder {

    public BookMarkTreeItemHolder(Context context) { super(context); }

    @Override
    public View createNodeView(TreeNode node, IconTreeItem value) {
        View view = LayoutInflater.from(context).inflate(R.layout.layout_bookmark_node, null, false);
        TextView tvValue = view.findViewById(R.id.node_value);
        tvValue.setText(value.text);
        ImageView arrowView = view.findViewById(R.id.arrow_icon);
        if (value.isLeaf) {
            arrowView.setVisibility(View.INVISIBLE);
        }
        return view;
    }

    @Override
    public void toggle(boolean active) {
        if (mNode.isLeaf()) {
            arrowView.setVisibility(View.INVISIBLE);
        } else {
            arrowView.setVisibility(View.VISIBLE);
            arrowView.setRotation(active ? 90 : 0);
        }
    }

    @Override
    public int getContainerStyle() { return R.style.TreeNodeStyleCustom; }

    public static class IconTreeItem {
        public boolean isLeaf;
        public long pageIndex;
        public String text;
        public IconTreeItem(boolean isLeaf, long pageIndex, String text) {
            this.isLeaf = isLeaf; this.pageIndex = pageIndex; this.text = text;
        }
    }
}

步驟四:組合 MyPDFViewer

繼承 LinearLayout 並實現 OnLoadCompleteListener,在構造方法中通過 TypedArray 讀取屬性,代碼構建左右兩塊布局:

public class MyPDFViewer extends LinearLayout implements OnLoadCompleteListener {
    private LinearLayout bookMarkContainer;
    private PDFView pdfView;
    private boolean bookMarkVisiable = true;
    private int bookMarkWeight = 1;
    private int contentWeight = 3;

    public MyPDFViewer(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOrientation(HORIZONTAL);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyPDFViewer);
        bookMarkVisiable = ta.getBoolean(R.styleable.MyPDFViewer_bookmark_visiable, true);
        bookMarkWeight = ta.getInteger(R.styleable.MyPDFViewer_bookmark_weight, 1);
        contentWeight = ta.getInteger(R.styleable.MyPDFViewer_content_weight, 3);

        bookMarkContainer = new LinearLayout(getContext());
        bookMarkContainer.setOrientation(VERTICAL);
        pdfView = new PDFView(getContext(), null);
        addView(bookMarkContainer);
        addView(pdfView);
    }

    public void load() {
        bookMarkContainer.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, bookMarkWeight));
        bookMarkContainer.setVisibility(bookMarkVisiable ? VISIBLE : GONE);
        pdfView.setLayoutParams(new LayoutParams(0, LayoutParams.MATCH_PARENT, contentWeight));

        pdfView.fromFile(new File(pdfPath))
                .enableSwipe(true)
                .swipeHorizontal(false)
                .enableDoubletap(true)
                .defaultPage(0)
                .password(passWord)
                .onLoad(this)
                .load();
    }

    @Override
    public void loadComplete(int nbPages) {
        TreeNode root = TreeNode.root();
        List bookmarks = pdfView.getTableOfContents();
        for (int i = 0; i < bookmarks.size(); i++) {
            TreeNode parent = buildNode(bookmarks.get(i));
            appendChildren(bookmarks.get(i).getChildren(), parent);
            root.addChild(parent);
        }
        AndroidTreeView treeView = new AndroidTreeView(getContext(), root);
        treeView.setDefaultNodeClickListener(nodeClickListener);
        bookMarkContainer.addView(treeView.getView());
    }

    private TreeNode.TreeNodeClickListener nodeClickListener = (node, value) ->
            pdfView.jumpTo((int) ((BookMarkTreeItemHolder.IconTreeItem) value).pageIndex);
}

書簽目錄往往有多層嵌套,因此構建節點時要用遞歸遍歷 getChildren(),直到葉節點為止。點擊回調裡取出 pageIndex 交給 pdfView.jumpTo() 即可完成跳轉。

步驟五:在頁面中使用

pdfView = findViewById(R.id.pdfView);
pdfView.setPdfPath(Environment.getExternalStorageDirectory().getPath() + "/Download/demo.pdf")
       .setBookMarkWeight(2)
       .setContentWeight(5)
       .load();

鏈式設置方法返回 this,調用起來很順手;加密 PDF 還可以再鏈上 setPassWord()。

一點感想

組合控件的價值在於「站在開源輪子之上」:PDF 渲染、樹形展示這些複雜能力交給成熟庫,自己只專注於交互邏輯與屬性封裝。這類控件代碼量不大,卻非常實用,也很適合作為自定義 View 的入門練習。

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