Android文档阅读之Txt文档阅读的方案实现

Android文档阅读之Txt文档阅读的方案实现

上两节说到了Office文档的阅读实现方案,通过NoHTTP将文档下载到本地,然后策略阅读,如果还没阅读到Office该篇的小伙伴们,可以先移步到上两节,因为这篇包括后面所写的都会用到这个NoHttp。

Android文档阅读之Office文档阅读的方案实现

首先需要引入第三方的框架,方便快速开发:

    //TXT阅读
    compile 'com.github.bifan-wei:HwTxtReader:V1.3.9'

需要记得在AndroidManifest.xml加入相应的权限:

    
    
    

该框架提供了一个TxtReaderView的类让我们免除手动解析的过程,自己感兴趣的小伙伴可以自己去解析处理,难度不大,通过读入流的方式和根据编码格式进行解析,然后draw到相应的View上,这样其实也就可以控制文字的大小、间距、背景等了,本文基于快速实现的原则,直接引用到该框架。

先看看主布局activity_txt.xml




    

    


layout_data_download为一个下载进度条,小伙伴们可以移步到我前篇文章了解,篇幅问题就不加进来这篇了。

TxtReaderActivity如下:


import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.format.Formatter;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bifan.txtreaderlib.bean.TxtMsg;
import com.bifan.txtreaderlib.interfaces.ILoadListener;
import com.bifan.txtreaderlib.interfaces.IPageChangeListener;
import com.bifan.txtreaderlib.interfaces.IPageEdgeListener;
import com.bifan.txtreaderlib.main.TxtReaderView;
import com.yanzhenjie.nohttp.Headers;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.download.DownloadListener;
import com.yanzhenjie.nohttp.download.DownloadRequest;

import java.io.File;
import java.text.DecimalFormat;

/**
 * @Description: Txt文本阅读
 * @Author: zzj
 * @Date: 2018/9/27 16:43
 * @Version: 1.0.0
 */
public class TxtReaderActivity extends Activity {
    private TxtReaderView txtReaderView;
    private static final String ROOT_PATH = "/mnt/sdcard/txt";
    private String url = "";//TXT文件的URL地址
    private String fileSize;
    private DownloadRequest downloadRequest;
    private RelativeLayout rlDownloadContainer;
    private TextView tvDlFileName;
    private TextView tvDlProgress;
    private ProgressBar pbDownload;
    private Button btnDownload;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_reader_txt);
        init();
        downloadTxt(url, title);
    }

    private void init() {
        txtReaderView = findViewById(R.id.txt_view);
    }

    /**
    * 初始化txt配置,设置背景与文字颜色、大小等
    */
    private void initTxtConfig() {
        txtReaderView.setPageChangeListener(iPageChangeListener);
        txtReaderView.setOnPageEdgeListener(iPageEdgeListener);
        txtReaderView.setStyle(Color.WHITE, Color.BLACK);
        txtReaderView.setTextSize(DisplayUtil.sp2px(16));
    }

    private void setTxt(String path) {
        txtReaderView.loadTxtFile(path, iLoadListener);
    }


    private void downloadTxt(String url, String fileName) {
        File file = new File(ROOT_PATH + "/" + fileName);
        //如果文本已经被下载本地,则直接打开,否则下载到本地
        if (file.exists()) {
            setTxt(file.getPath());
            return;
        }
        showDownloadView(fileName);
    }

    private void showDownloadView(String fileName) {
        rlDownloadContainer = findViewById(R.id.rl_download_container);
        tvDlFileName = findViewById(R.id.tv_file_name);
        tvDlProgress = findViewById(R.id.tv_download_progress);
        btnDownload = findViewById(R.id.btn_download);
        pbDownload = findViewById(R.id.pb_download);
        tvDlFileName.setText(fileName);
        rlDownloadContainer.setVisibility(View.VISIBLE);
        //R.string.download为“下载”
        btnDownload.setText(String.format("%s(%s)", getString(R.string.download), fileSize/*文件大小*/));
        btnDownload.setOnClickListener(v -> {
            if (downloadRequest == null) {
                downloadRequest = NoHttp.createDownloadRequest(url, ROOT_PATH , fileName, true, false);
                CallServer.getInstance().download(0, downloadRequest, downloadListener);
            }
        });
    }

    private ILoadListener iLoadListener = new ILoadListener() {
        @Override
        public void onSuccess() {
            if (txtReaderView.getVisibility() == View.GONE) {
                txtReaderView.setVisibility(View.VISIBLE);
            }
            initTxtConfig();
        }

        @Override
        public void onFail(TxtMsg txtMsg) {
            if (txtReaderView.getVisibility() == View.VISIBLE) {
                txtReaderView.setVisibility(View.GONE);
            }
          
            if (txtMsg == TxtMsg.FileNoExist) {
                showToast("文件不存在");
            } else {
                showToast("初始化出错");
            }
        }

        @Override
        public void onMessage(String s) {
            Log.d("zzj", "onMessage() " + s);
        }
    };

    private DecimalFormat decimalFormat = new DecimalFormat("0.00");
    private IPageChangeListener iPageChangeListener = new IPageChangeListener() {
        @Override
        public void onCurrentPage(float v) {
        	//decimalFormat.format(v * 100) + "%" ,当前的页面百分比,最后一页为100%
   			
        }
    };

    private IPageEdgeListener iPageEdgeListener = new IPageEdgeListener() {
        @Override
        public void onCurrentFirstPage() {
        }

        @Override
        public void onCurrentLastPage() {
            //最后一页
        }
    };

    private DownloadListener downloadListener = new DownloadListener() {
        @Override
        public void onDownloadError(int what, Exception exception) {
            txtReaderView.setVisibility(View.GONE);
            if (rlDownloadContainer != null) {
                rlDownloadContainer.setVisibility(View.GONE);
            }
        }

        @Override
        public void onStart(int what, boolean isResume, long rangeSize, Headers responseHeaders, long allCount) {
            if (btnDownload != null) {
                btnDownload.setVisibility(View.GONE);
                tvDlProgress.setVisibility(View.VISIBLE);
                pbDownload.setVisibility(View.VISIBLE);
            }
        }

        @Override
        public void onProgress(int what, int progress, long fileCount, long speed) {
            pbDownload.setProgress(progress);
            tvDlProgress.setText(String.format("%s(%s/%s)", 
            	getResources().getString(R.string.downloading), 
            	Formatter.formatFileSize(TxtReaderActivity.this, fileCount), fileSize));
        }

        @Override
        public void onFinish(int what, String filePath) {
            setTxt(filePath);
            if (txtReaderView.getVisibility() != View.VISIBLE) {
                txtReaderView.setVisibility(View.VISIBLE);
            }
            rlDownloadContainer.setVisibility(View.GONE);
        }

        @Override
        public void onCancel(int what) {
            txtReaderView.setVisibility(View.GONE);
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (downloadRequest != null) {
            downloadRequest.cancel();
        }
        //退出时需要清除对象,防止内存泄漏
        txtReaderView.getTxtReaderContext().Clear();
        txtReaderView = null;
    }
}

结语

TXT的Android阅读实现方式还是很多的,GitHub上面有一大堆已经实现的,但大多数都需要自己去抽离代码,本文能让你快速实现TXT的阅读。欢迎大家点赞拍砖转发分享。
 

 

 

你可能感兴趣的:(Android技术)