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

記事本實戰:在富文本裡點擊查看原圖與播放錄音

編輯:關於 Android 程式設計

本文為學習筆記,歡迎轉載,但請保留出處。

前面已經實現了圖文混排與錄音插入,這次來補上「查看」:在編輯或瀏覽記事時,點擊圖片打開一個自定義 Activity 查看原圖(而不是縮略圖);點擊錄音則打開自定義 Activity 播放音頻。

一、查看圖片的 Activity

布局 activity_show_picture.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/iv_showPic"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitCenter" />
</LinearLayout>
public class ShowPicture extends Activity {

    private ImageView img;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.activity_show_picture);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_add);

        ((TextView) findViewById(R.id.tv_title)).setText("查看圖片");

        Button bt_back = (Button) findViewById(R.id.bt_back);
        bt_back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                ShowPicture.this.finish();
            }
        });

        img = (ImageView) findViewById(R.id.iv_showPic);
        // 路徑由上一個 Activity 傳入
        String imgPath = getIntent().getStringExtra("imgPath");
        Bitmap bm = BitmapFactory.decodeFile(imgPath);
        img.setImageBitmap(bm);
    }
}

思路很直白:用 ImageView 顯示指定路徑的圖片。這裡只實現了返回,縮放與旋轉留待後續。

二、播放錄音的 Activity

布局 activity_show_record.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center"
        android:layout_centerInParent="true" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:gravity="center"
            android:layout_margin="5dp" >

            <ImageView
                android:id="@+id/iv_record_wave_left"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:background="@anim/record_wave_left" />

            <ImageView
                android:id="@+id/iv_microphone"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:src="@drawable/record_microphone_icon" />

            <ImageView
                android:id="@+id/iv_record_wave_right"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="5dp"
                android:background="@anim/record_wave_right" />
        </LinearLayout>

        <TextView
            android:id="@+id/tv_recordTime"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="#499df7"
            android:textSize="20sp"
            android:text="00:00:00"
            android:gravity="center"
            android:layout_margin="5dp" />
    </LinearLayout>
</RelativeLayout>
public class ShowRecord extends Activity {

    private String audioPath;
    private int isPlaying = 0;
    private AnimationDrawable ad_left, ad_right;
    private Timer mTimer;
    private MediaPlayer mPlayer = null;
    private ImageView iv_microphone, iv_record_wave_left, iv_record_wave_right;
    private TextView tv_recordTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.activity_show_record);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_add);

        ((TextView) findViewById(R.id.tv_title)).setText("查看錄音");

        Button bt_back = (Button) findViewById(R.id.bt_back);
        bt_back.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (isPlaying == 1) {
                    mPlayer.stop();
                    mPlayer.release();
                }
                ShowRecord.this.finish();
            }
        });

        audioPath = getIntent().getStringExtra("audioPath");

        iv_microphone = (ImageView) findViewById(R.id.iv_microphone);
        iv_microphone.setOnClickListener(new ClickEvent());

        iv_record_wave_left = (ImageView) findViewById(R.id.iv_record_wave_left);
        iv_record_wave_right = (ImageView) findViewById(R.id.iv_record_wave_right);
        ad_left = (AnimationDrawable) iv_record_wave_left.getBackground();
        ad_right = (AnimationDrawable) iv_record_wave_right.getBackground();

        tv_recordTime = (TextView) findViewById(R.id.tv_recordTime);
    }

    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what != 1) return;
            String time[] = tv_recordTime.getText().toString().split(":");
            int hour = Integer.parseInt(time[0]);
            int minute = Integer.parseInt(time[1]);
            int second = Integer.parseInt(time[2]);

            if (second < 59) {
                second++;
            } else if (minute < 59) {
                minute++; second = 0;
            } else if (hour < 98) {
                hour++; minute = 0; second = 0;
            }

            time[0] = hour < 10 ? "0" + hour : "" + hour;
            time[1] = minute < 10 ? "0" + minute : "" + minute;
            time[2] = second < 10 ? "0" + second : "" + second;
            tv_recordTime.setText(time[0] + ":" + time[1] + ":" + time[2]);
        }
    };

    class ClickEvent implements OnClickListener {
        @Override
        public void onClick(View arg0) {
            if (isPlaying == 0) {
                // 開始試聽
                isPlaying = 1;
                mPlayer = new MediaPlayer();
                tv_recordTime.setText("00:00:00");
                mTimer = new Timer();
                mPlayer.setOnCompletionListener(new MediaCompletion());

                try {
                    mPlayer.setDataSource(audioPath);
                    mPlayer.prepare();
                    mPlayer.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                // 每秒刷新一次播放時長
                mTimer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        Message message = new Message();
                        message.what = 1;
                        handler.sendMessage(message);
                    }
                }, 1000, 1000);

                ad_left.start();
                ad_right.start();
            } else {
                // 結束試聽
                isPlaying = 0;
                mPlayer.stop();
                mPlayer.release();
                mPlayer = null;
                mTimer.cancel();
                mTimer = null;
                ad_left.stop();
                ad_right.stop();
            }
        }
    }

    class MediaCompletion implements OnCompletionListener {
        @Override
        public void onCompletion(MediaPlayer mp) {
            mTimer.cancel();
            mTimer = null;
            isPlaying = 0;
            ad_left.stop();
            ad_right.stop();
            Toast.makeText(ShowRecord.this, "播放完畢", Toast.LENGTH_SHORT).show();
            tv_recordTime.setText("00:00:00");
        }
    }
}

三、難點:怎麼知道點到了哪個元素

有了這兩個 Activity,剩下的事就是「在點擊事件裡啟動它」。但真正的難題是:圖文混排的 EditText 中,如何判斷用戶點的是圖片、錄音還是普通文字?點到圖片的話,又是哪一張?

1. 記錄每個圖片/錄音的位置與路徑

用一個 List 保存「在文本中的起止位置」與「文件路徑」的映射。浏覽已存在的記事時,在加載數據的同時也要把這些信息記錄下來。

// 記錄 editText 中的圖片,用於單擊時判斷點的是哪一個
private List> imgList = new ArrayList>();

在 loadDate() 方法中追加:

Map map = new HashMap();
map.put("location", m.start() + "-" + m.end());
map.put("path", path);
imgList.add(map);

在 InsertBitmap() 方法中追加:

Map map = new HashMap();
map.put("location", selectionIndex + "-" + (selectionIndex + spannableString.length()));
map.put("path", imgPath);
imgList.add(map);

2. 給 EditText 掛監聽

private LineEditText et_Notes;
// ...
et_Notes.setOnClickListener(new TextClickEvent());

3~5. 判斷類型並跳轉

借助 Spanned 與 ImageSpan,判斷當前光標位置是否落在某個 ImageSpan 的區間內,再用該區間去 imgList 裡查出對應路徑,最後按後綴決定跳哪個 Activity:

class TextClickEvent implements OnClickListener {
    @Override
    public void onClick(View v) {
        Spanned s = et_Notes.getText();
        ImageSpan[] imageSpans = s.getSpans(0, s.length(), ImageSpan.class);
        int selectionStart = et_Notes.getSelectionStart();

        for (ImageSpan span : imageSpans) {
            int start = s.getSpanStart(span);
            int end = s.getSpanEnd(span);

            if (selectionStart >= start && selectionStart < end) {
                // 用位置查出對應的文件路徑
                String path = null;
                for (int i = 0; i < imgList.size(); i++) {
                    Map map = imgList.get(i);
                    if (map.get("location").equals(start + "-" + end)) {
                        path = imgList.get(i).get("path");
                        break;
                    }
                }
                if (path == null) return;

                if (path.substring(path.length() - 3).equals("amr")) {
                    // 錄音 → 試聽界面
                    Intent intent = new Intent(AddActivity.this, ShowRecord.class);
                    intent.putExtra("audioPath", path);
                    startActivity(intent);
                } else {
                    // 圖片 → 查看界面
                    Intent intent = new Intent(AddActivity.this, ShowPicture.class);
                    intent.putExtra("imgPath", path);
                    startActivity(intent);
                }
                return;
            }
        }

        // 點到空白處或文字,獲取焦點、彈出軟鍵盤
        imm.showSoftInput(et_Notes, 0);
    }
}

查看圖片其實有兩種做法:一種是直接調用系統圖庫

Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(new File(path));
intent.setDataAndType(uri, "image/*");

另一種就是上面用的自定義 Activity。前者省事但可控性差,後者能加縮放、旋轉、標註等能力,正式項目通常選後者。

小結

整個功能的關鍵不在於兩個展示 Activity 有多複雜,而在於用「位置區間 + 路徑」的映射表,把富文本裡的非文本元素變成可定位、可點擊的對象。這個思路可以直接遷移到任何需要處理混排內容的場景,比如聊天消息裡的圖片與語音。

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