Android 文本阅读以及TextView指定字符高亮显示

这里首先实现指定的txt文件的解析以及处理:
首先是解析方法:读取txt后根据关键字分章节分标题处理

package com.example.read_txt_highlight;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;

@SuppressLint("NewApi")
public class TxtReadMethod {
    public static final int UNIT=0;
    public static final int LESSON=1;
    public static final int CONTENT=2;

    /**
     * 通过一个InputStream获取内容
     * 
     * @param inputStream
     * @return
     */
    public static ArrayList getString(InputStream inputStream) {
        ArrayList unitDataList=new ArrayList();
        InputStreamReader inputStreamReader = null;
        try {
            inputStreamReader = new InputStreamReader(inputStream, "utf-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        BufferedReader reader = new BufferedReader(inputStreamReader);
        StringBuffer sb = new StringBuffer("");
        StringBuffer titleSb = new StringBuffer("");
        String line;

        String regularUnit = "Unit\\s*\\d";
        String regularLesson = "Lesson\\s*\\d";
        int unitId = 0;
        int lessonId = 0;
        boolean upLesson = false;
        boolean firstContent = false;

        int matchId;
        String matchContent;
        UnitData unitData=new UnitData();
        ArrayList
articleList=new ArrayList
(); Article article=new Article(); try { while ((line = reader.readLine()) != null) { TxtMatch matchGet = regularGroup(regularUnit, regularLesson, line); matchId = matchGet.getMatch(); matchContent=matchGet.getContent(); switch (matchId) { case UNIT: if(unitId!=0){ unitData.setArticle(articleList); unitDataList.add(unitData); articleList=new ArrayList
(); } unitId++; unitData=new UnitData(); unitData.setUnit(unitId); break; case LESSON: if(lessonId!=0){ article.setContent(sb.toString()); articleList.add(article); sb.delete(0,sb.length()-1); } lessonId++; //创建新的Article article=new Article(); upLesson=true; article.setLessonId(lessonId); break; case CONTENT: //赋值给标题或者正文 if(upLesson&&firstContent){ titleSb.append(" "); titleSb.append(matchContent.replaceAll(" ","")); article.setTitle(titleSb.toString()); titleSb.delete(0,titleSb.length()); upLesson=false; firstContent=false; }else if(upLesson){ titleSb.append(matchContent.trim()); firstContent=true; }else{ sb.append(matchContent); sb.append("\n"); upLesson=false; } break; default: break; } } } catch (IOException e) { e.printStackTrace(); } unitData.setArticle(articleList); unitDataList.add(unitData); return unitDataList; } //解析 private static TxtMatch regularGroup(String patternUnit,String patternLesson, String matcher) { TxtMatch txtMatch =new TxtMatch(); Pattern p = Pattern.compile(patternUnit, Pattern.CASE_INSENSITIVE); Matcher m = p.matcher(matcher); if (m.find()) { // 如果读到 txtMatch.setMatch(UNIT); txtMatch.setContent(m.group()); return txtMatch;// 返回捕获的数据 }else{ Pattern pL = Pattern.compile(patternLesson, Pattern.CASE_INSENSITIVE); Matcher mL = pL.matcher(matcher); if(mL.find()){ txtMatch.setMatch(LESSON); txtMatch.setContent(mL.group()); return txtMatch;// 返回捕获的数据 }else{ txtMatch.setMatch(CONTENT); txtMatch.setContent(matcher); return txtMatch; } } } }

然后是调用实现的Activity,这里的TextView使用开源的PinnedSectionListView

package com.example.read_txt_highlight;

import java.io.InputStream;
import java.util.ArrayList;

import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.example.read_txt_highlight.PinnedSectionListView.PinnedSectionListAdapter;

public class TxtReadActivity extends ListActivity {

    private static final String INTENT_CONTENT = "content";
    private static final String INTENT_TITLE = "title";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        InputStream inputStream = getResources().openRawResource(R.raw.new4);//需要读取的txt文档
        ArrayList unitDatas = TxtReadMethod.getString(inputStream);
        setListAdapter(new SimpleAdapter(this,
                android.R.layout.simple_list_item_1, android.R.id.text1,
                unitDatas));

    }

    /**
     * 使用PinnedListview实现效果
     *
     */
    static class SimpleAdapter extends ArrayAdapter implements
            PinnedSectionListAdapter {

        ArrayList unitDatas = new ArrayList();
        private static final int[] COLORS = new int[] { R.color.orange_light,
                R.color.blue_light, R.color.red_light };//章节颜色背景

        public SimpleAdapter(Context context, int resource,
                int textViewResourceId, ArrayList unitDatas) {
            super(context, resource, textViewResourceId);
            this.unitDatas = unitDatas;
            generateDataset('1', '3', false);//需要根据具体需求修改

        }

        public void generateDataset(char from, char to, boolean clear) {

            if (clear)
                clear();

            final int sectionsNumber = to - from + 1;
            prepareSections(sectionsNumber);

            int sectionPosition = 0, listPosition = 0;
            for (char i = 0; i < sectionsNumber; i++) {
                UnitData unitData = unitDatas.get(i);
                Item section = new Item(Item.SECTION, "Unit "
                        + String.valueOf(i + 1), "");
                section.sectionPosition = sectionPosition;
                section.listPosition = listPosition++;
                onSectionAdded(section, sectionPosition);
                add(section);

                ArrayList
articles = unitData.getArticle(); int itemsNumber = articles.size(); for (int j = 0; j < itemsNumber; j++) { Article article = articles.get(j); Item item = new Item(Item.ITEM, article.getTitle(), article.getContent()); item.sectionPosition = sectionPosition; item.listPosition = listPosition++; add(item); } sectionPosition++; } } protected void prepareSections(int sectionsNumber) { } protected void onSectionAdded(Item section, int sectionPosition) { } //由于没有图片等资源 此处未进行Listview优化,实际使用时需要对此进行优化 @Override public View getView(int position, View convertView, ViewGroup parent) { TextView view = (TextView) super.getView(position, convertView, parent); view.setTextColor(Color.DKGRAY); view.setTag("" + position); Item item = getItem(position); if (item.type == Item.SECTION) { view.setBackgroundColor(parent.getResources().getColor( COLORS[item.sectionPosition % COLORS.length])); } else { view.setTextSize(14); } return view; } @Override public int getViewTypeCount() { return 2; } @Override public int getItemViewType(int position) { return getItem(position).type; } @Override public boolean isItemViewTypePinned(int viewType) { return viewType == Item.SECTION; } } @Override protected void onListItemClick(ListView l, View v, int position, long id) { Item item = (Item) getListView().getAdapter().getItem(position); if (item != null && !(item.content).equals("")) { Intent contentIntent = new Intent(TxtReadActivity.this, ArticleContentActivity.class); contentIntent.putExtra(INTENT_CONTENT, item.content); contentIntent.putExtra(INTENT_TITLE, item.title); startActivity(contentIntent); } } }

接下来是词库中或者你指定的字符集在TextView中的高亮显示:

/**
     * 根据等级匹配对应单词 并高亮显示
     * 
     * @param level
     */
    private void spanWord(int level) {
        SpannableStringBuilder style = new SpannableStringBuilder(mContent
                .getText().toString());
        for (int i = 0; i < level; i++) {

            ArrayList arrayList = wordList.get(i);
            for (int j = 0; j < arrayList.size(); j++) {
                Pattern p = Pattern.compile(arrayList.get(j));

                Matcher m = p.matcher(style);

                while (m.find()) {
                    int start = m.start();
                    int end = m.end();
                    style.setSpan(new ForegroundColorSpan(Color.RED), start,
                            end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                }
            }
        }
        mContent.setText(style);

    }

这个可以将文本以及词库存储到本地数据库,加快访问速度和效率,这里只提供了大致思路,如有更佳方案,欢迎留言。

你可能感兴趣的:(android)