天天看点

android仿微信聊天页面,以及实现语音功能

本demo为模仿微信聊天界面UI设计,文字发送以及语言录制UI。

觉得还行,转过来分享给大家:

先看效果图我们:

1先看效果图:

android仿微信聊天页面,以及实现语音功能
android仿微信聊天页面,以及实现语音功能
android仿微信聊天页面,以及实现语音功能
android仿微信聊天页面,以及实现语音功能
android仿微信聊天页面,以及实现语音功能

第一:chat.xml设计

Xml代码  

android仿微信聊天页面,以及实现语音功能
android仿微信聊天页面,以及实现语音功能
  1. <?xml version=“1.0” encoding=“utf-8”?>  
  2. <RelativeLayout xmlns:android=“http://schemas.android.com/apk/res/android”  
  3.     android:layout_width=“fill_parent”  
  4.     android:layout_height=“fill_parent”  
  5.     android:background=“@drawable/chat_bg_default” >  
  6.     <!– 标题栏 –>  
  7.     <RelativeLayout  
  8.         android:id=“@+id/rl_layout”  
  9.         android:layout_width=“fill_parent”  
  10.         android:layout_height=“45dp”  
  11.         android:background=“@drawable/title_bar”  
  12.         android:gravity=“center_vertical” >  
  13.         <Button  
  14.             android:id=“@+id/btn_back”  
  15.             android:layout_width=“70dp”  
  16.             android:layout_height=“wrap_content”  
  17.             android:layout_centerVertical=“true”  
  18.             android:background=“@drawable/title_btn_back”  
  19.             android:onClick=“chat_back”  
  20.             android:text=“返回”  
  21.             android:textColor=“#fff”  
  22.             android:textSize=“14sp” />  
  23.         <TextView  
  24.             android:layout_width=“wrap_content”  
  25.             android:layout_height=“wrap_content”  
  26.             android:layout_centerInParent=“true”  
  27.             android:text=“白富美”  
  28.             android:textColor=“#ffffff”  
  29.             android:textSize=“20sp” />  
  30.         <ImageButton  
  31.             android:id=“@+id/right_btn”  
  32.             android:layout_width=“67dp”  
  33.             android:layout_height=“wrap_content”  
  34.             android:layout_alignParentRight=“true”  
  35.             android:layout_centerVertical=“true”  
  36.             android:layout_marginRight=“5dp”  
  37.             android:background=“@drawable/title_btn_right”  
  38.             android:src=“@drawable/mm_title_btn_contact_normal” />  
  39.     </RelativeLayout>  
  40.     <!– 底部按钮以及 编辑框 –>  
  41.     <RelativeLayout  
  42.         android:id=“@+id/rl_bottom”  
  43.         android:layout_width=“fill_parent”  
  44.         android:layout_height=“wrap_content”  
  45.         android:layout_alignParentBottom=“true”  
  46.         android:background=“@drawable/chat_footer_bg” >  
  47.         <ImageView  
  48.             android:id=“@+id/ivPopUp”  
  49.             android:layout_width=“wrap_content”  
  50.             android:layout_height=“wrap_content”  
  51.             android:layout_alignParentLeft=“true”  
  52.             android:layout_centerVertical=“true”  
  53.             android:layout_marginLeft=“10dip”  
  54.             android:src=“@drawable/chatting_setmode_msg_btn” />  
  55.         <RelativeLayout  
  56.             android:id=“@+id/btn_bottom”  
  57.             android:layout_width=“fill_parent”  
  58.             android:layout_height=“wrap_content”  
  59.             android:layout_alignParentRight=“true”  
  60.             android:layout_centerVertical=“true”  
  61.             android:layout_toRightOf=“@+id/ivPopUp” >  
  62.             <Button  
  63.                 android:id=“@+id/btn_send”  
  64.                 android:layout_width=“60dp”  
  65.                 android:layout_height=“40dp”  
  66.                 android:layout_alignParentRight=“true”  
  67.                 android:layout_centerVertical=“true”  
  68.                 android:layout_marginRight=“10dp”  
  69.                 android:background=“@drawable/chat_send_btn”  
  70.                 android:text=“发送” />  
  71.             <EditText  
  72.                 android:id=“@+id/et_sendmessage”  
  73.                 android:layout_width=“fill_parent”  
  74.                 android:layout_height=“40dp”  
  75.                 android:layout_centerVertical=“true”  
  76.                 android:layout_marginLeft=“10dp”  
  77.                 android:layout_marginRight=“10dp”  
  78.                 android:layout_toLeftOf=“@id/btn_send”  
  79.                 android:background=“@drawable/login_edit_normal”  
  80.                 android:singleLine=“true”  
  81.                 android:textSize=“18sp” />  
  82.         </RelativeLayout>  
  83.         <TextView  
  84.             android:id=“@+id/btn_rcd”  
  85.             android:layout_width=“fill_parent”  
  86.             android:layout_height=“40dp”  
  87.             android:layout_alignParentRight=“true”  
  88.             android:layout_centerVertical=“true”  
  89.             android:layout_marginLeft=“10dp”  
  90.             android:layout_marginRight=“10dp”  
  91.             android:layout_toRightOf=“@+id/ivPopUp”  
  92.             android:background=“@drawable/chat_send_btn”  
  93.             android:gravity=“center”  
  94.             android:text=“按住说话”  
  95.             android:visibility=“gone” />  
  96.     </RelativeLayout>  
  97.     <!– 聊天内容 listview –>  
  98.     <ListView  
  99.         android:id=“@+id/listview”  
  100.         android:layout_width=“fill_parent”  
  101.         android:layout_height=“fill_parent”  
  102.         android:layout_above=“@id/rl_bottom”  
  103.         android:layout_below=“@id/rl_layout”  
  104.         android:cacheColorHint=“#0000”  
  105.         android:divider=“@null”  
  106.         android:dividerHeight=“5dp”  
  107.         android:scrollbarStyle=“outsideOverlay”  
  108.         android:stackFromBottom=“true” />  
  109.     <!– 录音显示UI层 –>  
  110.     <LinearLayout  
  111.         android:id=“@+id/rcChat_popup”  
  112.         android:layout_width=“fill_parent”  
  113.         android:layout_height=“fill_parent”  
  114.         android:gravity=“center”  
  115.         android:visibility=“gone” >  
  116.         <include  
  117.             android:layout_width=“wrap_content”  
  118.             android:layout_height=“wrap_content”  
  119.             android:layout_gravity=“center”  
  120.             layout=“@layout/voice_rcd_hint_window” />  
  121.     </LinearLayout>  
  122. </RelativeLayout>  
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/chat_bg_default" >

    <!-- 标题栏 -->
    <RelativeLayout
        android:id="@+id/rl_layout"
        android:layout_width="fill_parent"
        android:layout_height="45dp"
        android:background="@drawable/title_bar"
        android:gravity="center_vertical" >

        <Button
            android:id="@+id/btn_back"
            android:layout_width="70dp"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:background="@drawable/title_btn_back"
            android:onClick="chat_back"
            android:text="返回"
            android:textColor="#fff"
            android:textSize="14sp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="白富美"
            android:textColor="#ffffff"
            android:textSize="20sp" />

        <ImageButton
            android:id="@+id/right_btn"
            android:layout_width="67dp"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="5dp"
            android:background="@drawable/title_btn_right"
            android:src="@drawable/mm_title_btn_contact_normal" />
    </RelativeLayout>

    <!-- 底部按钮以及 编辑框 -->
    <RelativeLayout
        android:id="@+id/rl_bottom"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@drawable/chat_footer_bg" >

        <ImageView
            android:id="@+id/ivPopUp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dip"
            android:src="@drawable/chatting_setmode_msg_btn" />

        <RelativeLayout
            android:id="@+id/btn_bottom"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_toRightOf="@+id/ivPopUp" >

            <Button
                android:id="@+id/btn_send"
                android:layout_width="60dp"
                android:layout_height="40dp"
                android:layout_alignParentRight="true"
                android:layout_centerVertical="true"
                android:layout_marginRight="10dp"
                android:background="@drawable/chat_send_btn"
                android:text="发送" />

            <EditText
                android:id="@+id/et_sendmessage"
                android:layout_width="fill_parent"
                android:layout_height="40dp"
                android:layout_centerVertical="true"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_toLeftOf="@id/btn_send"
                android:background="@drawable/login_edit_normal"
                android:singleLine="true"
                android:textSize="18sp" />
        </RelativeLayout>

        <TextView
            android:id="@+id/btn_rcd"
            android:layout_width="fill_parent"
            android:layout_height="40dp"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_toRightOf="@+id/ivPopUp"
            android:background="@drawable/chat_send_btn"
            android:gravity="center"
            android:text="按住说话"
            android:visibility="gone" />
    </RelativeLayout>

    <!-- 聊天内容 listview -->
    <ListView
        android:id="@+id/listview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_above="@id/rl_bottom"
        android:layout_below="@id/rl_layout"
        android:cacheColorHint="#0000"
        android:divider="@null"
        android:dividerHeight="5dp"
        android:scrollbarStyle="outsideOverlay"
        android:stackFromBottom="true" />

    <!-- 录音显示UI层 -->
    <LinearLayout
        android:id="@+id/rcChat_popup"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:visibility="gone" >

        <include
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            layout="@layout/voice_rcd_hint_window" />
    </LinearLayout>

</RelativeLayout>      

第二:语音录制类封装SoundMeter.java

Java代码  

android仿微信聊天页面,以及实现语音功能
android仿微信聊天页面,以及实现语音功能
  1. package com.example.voice_rcd;  
  2. import java.io.IOException;  
  3. import android.media.MediaRecorder;  
  4. import android.os.Environment;  
  5. public  class SoundMeter {  
  6.     static final private double EMA_FILTER = 0.6;  
  7.     private MediaRecorder mRecorder = null;  
  8.     private double mEMA = 0.0;  
  9.     public void start(String name) {  
  10.         if (!Environment.getExternalStorageState().equals(  
  11.                 android.os.Environment.MEDIA_MOUNTED)) {  
  12.             return;  
  13.         }  
  14.         if (mRecorder == null) {  
  15.             mRecorder = new MediaRecorder();  
  16.             mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);  
  17.             mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);  
  18.             mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);  
  19.             mRecorder.setOutputFile(android.os.Environment.getExternalStorageDirectory()+”/”+name);  
  20.             try {  
  21.                 mRecorder.prepare();  
  22.                 mRecorder.start();  
  23.                 mEMA = 0.0;  
  24.             } catch (IllegalStateException e) {  
  25.                 System.out.print(e.getMessage());  
  26.             } catch (IOException e) {  
  27.                 System.out.print(e.getMessage());  
  28.             }  
  29.         }  
  30.     }  
  31.     public void stop() {  
  32.         if (mRecorder != null) {  
  33.             mRecorder.stop();  
  34.             mRecorder.release();  
  35.             mRecorder = null;  
  36.         }  
  37.     }  
  38.     public void pause() {  
  39.         if (mRecorder != null) {  
  40.             mRecorder.stop();  
  41.         }  
  42.     }  
  43.     public void start() {  
  44.         if (mRecorder != null) {  
  45.             mRecorder.start();  
  46.         }  
  47.     }  
  48.     public double getAmplitude() {  
  49.         if (mRecorder != null)  
  50.             return (mRecorder.getMaxAmplitude() / 2700.0);  
  51.         else  
  52.             return 0;  
  53.     }  
  54.     public double getAmplitudeEMA() {  
  55.         double amp = getAmplitude();  
  56.         mEMA = EMA_FILTER * amp + (1.0 - EMA_FILTER) * mEMA;  
  57.         return mEMA;  
  58.     }  
  59. }  
package com.example.voice_rcd;

import java.io.IOException;

import android.media.MediaRecorder;
import android.os.Environment;

public  class SoundMeter {
    static final private double EMA_FILTER = 0.6;

    private MediaRecorder mRecorder = null;
    private double mEMA = 0.0;

    public void start(String name) {
        if (!Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            return;
        }
        if (mRecorder == null) {
            mRecorder = new MediaRecorder();
            mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
            mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            mRecorder.setOutputFile(android.os.Environment.getExternalStorageDirectory()+"/"+name);
            try {
                mRecorder.prepare();
                mRecorder.start();

                mEMA = 0.0;
            } catch (IllegalStateException e) {
                System.out.print(e.getMessage());
            } catch (IOException e) {
                System.out.print(e.getMessage());
            }

        }
    }

    public void stop() {
        if (mRecorder != null) {
            mRecorder.stop();
            mRecorder.release();
            mRecorder = null;
        }
    }

    public void pause() {
        if (mRecorder != null) {
            mRecorder.stop();
        }
    }

    public void start() {
        if (mRecorder != null) {
            mRecorder.start();
        }
    }

    public double getAmplitude() {
        if (mRecorder != null)
            return (mRecorder.getMaxAmplitude() / 2700.0);
        else
            return 0;

    }

    public double getAmplitudeEMA() {
        double amp = getAmplitude();
        mEMA = EMA_FILTER * amp + (1.0 - EMA_FILTER) * mEMA;
        return mEMA;
    }
}
           

 第三:主界面Activity源码,没写太多解释,相对比较简单的自己研究下:

Java代码  

android仿微信聊天页面,以及实现语音功能
android仿微信聊天页面,以及实现语音功能
  1. package com.example.voice_rcd;  
  2. import java.io.File;  
  3. import java.util.ArrayList;  
  4. import java.util.Calendar;  
  5. import java.util.List;  
  6. import android.app.Activity;  
  7. import android.os.Bundle;  
  8. import android.os.Environment;  
  9. import android.os.Handler;  
  10. import android.os.SystemClock;  
  11. import android.view.MotionEvent;  
  12. import android.view.View;  
  13. import android.view.View.OnClickListener;  
  14. import android.view.View.OnTouchListener;  
  15. import android.view.WindowManager;  
  16. import android.view.animation.Animation;  
  17. import android.view.animation.AnimationUtils;  
  18. import android.widget.Button;  
  19. import android.widget.EditText;  
  20. import android.widget.ImageView;  
  21. import android.widget.LinearLayout;  
  22. import android.widget.ListView;  
  23. import android.widget.RelativeLayout;  
  24. import android.widget.TextView;  
  25. import android.widget.Toast;  
  26. public class MainActivity extends Activity implements OnClickListener {  
  27.     private Button mBtnSend;  
  28.     private TextView mBtnRcd;  
  29.     private Button mBtnBack;  
  30.     private EditText mEditTextContent;  
  31.     private RelativeLayout mBottom;  
  32.     private ListView mListView;  
  33.     private ChatMsgViewAdapter mAdapter;  
  34.     private List<ChatMsgEntity> mDataArrays = new ArrayList<ChatMsgEntity>();  
  35.     private boolean isShosrt = false;  
  36.     private LinearLayout voice_rcd_hint_loading, voice_rcd_hint_rcding,  
  37.             voice_rcd_hint_tooshort;  
  38.     private ImageView img1, sc_img1;  
  39.     private SoundMeter mSensor;  
  40.     private View rcChat_popup;  
  41.     private LinearLayout del_re;  
  42.     private ImageView chatting_mode_btn, volume;  
  43.     private boolean btn_vocie = false;  
  44.     private int flag = 1;  
  45.     private Handler mHandler = new Handler();  
  46.     private String voiceName;  
  47.     private long startVoiceT, endVoiceT;  
  48.     public void onCreate(Bundle savedInstanceState) {  
  49.         super.onCreate(savedInstanceState);  
  50.         setContentView(R.layout.chat);  
  51.         // 启动activity时不自动弹出软键盘  
  52.         getWindow().setSoftInputMode(  
  53.                 WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);  
  54.         initView();  
  55.         initData();  
  56.     }  
  57.     public void initView() {  
  58.         mListView = (ListView) findViewById(R.id.listview);  
  59.         mBtnSend = (Button) findViewById(R.id.btn_send);  
  60.         mBtnRcd = (TextView) findViewById(R.id.btn_rcd);  
  61.         mBtnSend.setOnClickListener(this);  
  62.         mBtnBack = (Button) findViewById(R.id.btn_back);  
  63.         mBottom = (RelativeLayout) findViewById(R.id.btn_bottom);  
  64.         mBtnBack.setOnClickListener(this);  
  65.         chatting_mode_btn = (ImageView) this.findViewById(R.id.ivPopUp);  
  66.         volume = (ImageView) this.findViewById(R.id.volume);  
  67.         rcChat_popup = this.findViewById(R.id.rcChat_popup);  
  68.         img1 = (ImageView) this.findViewById(R.id.img1);  
  69.         sc_img1 = (ImageView) this.findViewById(R.id.sc_img1);  
  70.         del_re = (LinearLayout) this.findViewById(R.id.del_re);  
  71.         voice_rcd_hint_rcding = (LinearLayout) this  
  72.                 .findViewById(R.id.voice_rcd_hint_rcding);  
  73.         voice_rcd_hint_loading = (LinearLayout) this  
  74.                 .findViewById(R.id.voice_rcd_hint_loading);  
  75.         voice_rcd_hint_tooshort = (LinearLayout) this  
  76.                 .findViewById(R.id.voice_rcd_hint_tooshort);  
  77.         mSensor = new SoundMeter();  
  78.         mEditTextContent = (EditText) findViewById(R.id.et_sendmessage);  
  79.         //语音文字切换按钮  
  80.         chatting_mode_btn.setOnClickListener(new OnClickListener() {  
  81.             public void onClick(View v) {  
  82.                 if (btn_vocie) {  
  83.                     mBtnRcd.setVisibility(View.GONE);  
  84.                     mBottom.setVisibility(View.VISIBLE);  
  85.                     btn_vocie = false;  
  86.                     chatting_mode_btn  
  87.                             .setImageResource(R.drawable.chatting_setmode_msg_btn);  
  88.                 } else {  
  89.                     mBtnRcd.setVisibility(View.VISIBLE);  
  90.                     mBottom.setVisibility(View.GONE);  
  91.                     chatting_mode_btn  
  92.                             .setImageResource(R.drawable.chatting_setmode_voice_btn);  
  93.                     btn_vocie = true;  
  94.                 }  
  95.             }  
  96.         });  
  97.         mBtnRcd.setOnTouchListener(new OnTouchListener() {  
  98.             public boolean onTouch(View v, MotionEvent event) {  
  99.                 //按下语音录制按钮时返回false执行父类OnTouch  
  100.                 return false;  
  101.             }  
  102.         });  
  103.     }  
  104.     private String[] msgArray = new String[] { “有人就有恩怨”,“有恩怨就有江湖”,“人就是江湖”,“你怎么退出? ”,“生命中充满了巧合”,“两条平行线也会有相交的一天。”};  
  105.     private String[] dataArray = new String[] { “2012-10-31 18:00”,  
  106.             ”2012-10-31 18:10”, “2012-10-31 18:11”, “2012-10-31 18:20”,  
  107.             ”2012-10-31 18:30”, “2012-10-31 18:35”};  
  108.     private final static int COUNT = 6;  
  109.     public void initData() {  
  110.         for (int i = 0; i < COUNT; i++) {  
  111.             ChatMsgEntity entity = new ChatMsgEntity();  
  112.             entity.setDate(dataArray[i]);  
  113.             if (i % 2 == 0) {  
  114.                 entity.setName(”白富美”);  
  115.                 entity.setMsgType(true);  
  116.             } else {  
  117.                 entity.setName(”高富帅”);  
  118.                 entity.setMsgType(false);  
  119.             }  
  120.             entity.setText(msgArray[i]);  
  121.             mDataArrays.add(entity);  
  122.         }  
  123.         mAdapter = new ChatMsgViewAdapter(this, mDataArrays);  
  124.         mListView.setAdapter(mAdapter);  
  125.     }  
  126.     public void onClick(View v) {  
  127.         // TODO Auto-generated method stub  
  128.         switch (v.getId()) {  
  129.         case R.id.btn_send:  
  130.             send();  
  131.             break;  
  132.         case R.id.btn_back:  
  133.             finish();  
  134.             break;  
  135.         }  
  136.     }  
  137.     private void send() {  
  138.         String contString = mEditTextContent.getText().toString();  
  139.         if (contString.length() > 0) {  
  140.             ChatMsgEntity entity = new ChatMsgEntity();  
  141.             entity.setDate(getDate());  
  142.             entity.setName(”高富帅”);  
  143.             entity.setMsgType(false);  
  144.             entity.setText(contString);  
  145.             mDataArrays.add(entity);  
  146.             mAdapter.notifyDataSetChanged();  
  147.             mEditTextContent.setText(”“);  
  148.             mListView.setSelection(mListView.getCount() - 1);  
  149.         }  
  150.     }  
  151.     private String getDate() {  
  152.         Calendar c = Calendar.getInstance();  
  153.         String year = String.valueOf(c.get(Calendar.YEAR));  
  154.         String month = String.valueOf(c.get(Calendar.MONTH));  
  155.         String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH) + 1);  
  156.         String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));  
  157.         String mins = String.valueOf(c.get(Calendar.MINUTE));  
  158.         StringBuffer sbBuffer = new StringBuffer();  
  159.         sbBuffer.append(year + ”-“ + month + “-“ + day + “ ” + hour + “:”  
  160.                 + mins);  
  161.         return sbBuffer.toString();  
  162.     }  
  163.     //按下语音录制按钮时  
  164.     @Override  
  165.     public boolean onTouchEvent(MotionEvent event) {  
  166.         if (!Environment.getExternalStorageDirectory().exists()) {  
  167.             Toast.makeText(this, “No SDCard”, Toast.LENGTH_LONG).show();  
  168.             return false;  
  169.         }  
  170.         if (btn_vocie) {  
  171.             System.out.println(”1”);  
  172.             int[] location = new int[2];  
  173.             mBtnRcd.getLocationInWindow(location); // 获取在当前窗口内的绝对坐标  
  174.             int btn_rc_Y = location[1];  
  175.             int btn_rc_X = location[0];  
  176.             int[] del_location = new int[2];  
  177.             del_re.getLocationInWindow(del_location);  
  178.             int del_Y = del_location[1];  
  179.             int del_x = del_location[0];  
  180.             if (event.getAction() == MotionEvent.ACTION_DOWN && flag == 1) {  
  181.                 if (!Environment.getExternalStorageDirectory().exists()) {  
  182.                     Toast.makeText(this, “No SDCard”, Toast.LENGTH_LONG).show();  
  183.                     return false;  
  184.                 }  
  185.                 System.out.println(”2”);  
  186.                 if (event.getY() > btn_rc_Y && event.getX() > btn_rc_X) {//判断手势按下的位置是否是语音录制按钮的范围内  
  187.                     System.out.println(”3”);  
  188.                     mBtnRcd.setBackgroundResource(R.drawable.voice_rcd_btn_pressed);  
  189.                     rcChat_popup.setVisibility(View.VISIBLE);  
  190.                     voice_rcd_hint_loading.setVisibility(View.VISIBLE);  
  191.                     voice_rcd_hint_rcding.setVisibility(View.GONE);  
  192.                     voice_rcd_hint_tooshort.setVisibility(View.GONE);  
  193.                     mHandler.postDelayed(new Runnable() {  
  194.                         public void run() {  
  195.                             if (!isShosrt) {  
  196.                                 voice_rcd_hint_loading.setVisibility(View.GONE);  
  197.                                 voice_rcd_hint_rcding  
  198.                                         .setVisibility(View.VISIBLE);  
  199.                             }  
  200.                         }  
  201.                     }, 300);  
  202.                     img1.setVisibility(View.VISIBLE);  
  203.                     del_re.setVisibility(View.GONE);  
  204.                     startVoiceT = SystemClock.currentThreadTimeMillis();  
  205.                     voiceName = startVoiceT + ”.amr”;  
  206.                     start(voiceName);  
  207.                     flag = 2;  
  208.                 }  
  209.             } else if (event.getAction() == MotionEvent.ACTION_UP && flag == 2) {//松开手势时执行录制完成  
  210.                 System.out.println(”4”);  
  211.                 mBtnRcd.setBackgroundResource(R.drawable.voice_rcd_btn_nor);  
  212.                 if (event.getY() >= del_Y  
  213.                         && event.getY() <= del_Y + del_re.getHeight()  
  214.                         && event.getX() >= del_x  
  215.                         && event.getX() <= del_x + del_re.getWidth()) {  
  216.                     rcChat_popup.setVisibility(View.GONE);  
  217.                     img1.setVisibility(View.VISIBLE);  
  218.                     del_re.setVisibility(View.GONE);  
  219.                     stop();  
  220.                     flag = 1;  
  221.                     File file = new File(android.os.Environment.getExternalStorageDirectory()+“/”  
  222.                                     + voiceName);  
  223.                     if (file.exists()) {  
  224.                         file.delete();  
  225.                     }  
  226.                 } else {  
  227.                     voice_rcd_hint_rcding.setVisibility(View.GONE);  
  228.                     stop();  
  229.                     endVoiceT = SystemClock.currentThreadTimeMillis();  
  230.                     flag = 1;  
  231.                     int time = (int) ((endVoiceT - startVoiceT) / 1000);  
  232.                     if (time < 1) {  
  233.                         isShosrt = true;  
  234.                         voice_rcd_hint_loading.setVisibility(View.GONE);  
  235.                         voice_rcd_hint_rcding.setVisibility(View.GONE);  
  236.                         voice_rcd_hint_tooshort.setVisibility(View.VISIBLE);  
  237.                         mHandler.postDelayed(new Runnable() {  
  238.                             public void run() {  
  239.                                 voice_rcd_hint_tooshort  
  240.                                         .setVisibility(View.GONE);  
  241.                                 rcChat_popup.setVisibility(View.GONE);  
  242.                                 isShosrt = false;  
  243.                             }  
  244.                         }, 500);  
  245.                         return false;  
  246.                     }  
  247.                     ChatMsgEntity entity = new ChatMsgEntity();  
  248.                     entity.setDate(getDate());  
  249.                     entity.setName(”高富帅”);  
  250.                     entity.setMsgType(false);  
  251.                     entity.setTime(time+”\”“);  
  252.                     entity.setText(voiceName);  
  253.                     mDataArrays.add(entity);  
  254.                     mAdapter.notifyDataSetChanged();  
  255.                     mListView.setSelection(mListView.getCount() - 1);  
  256.                     rcChat_popup.setVisibility(View.GONE);  
  257.                 }  
  258.             }  
  259.             if (event.getY() < btn_rc_Y) {//手势按下的位置不在语音录制按钮的范围内  
  260.                 System.out.println(”5”);  
  261.                 Animation mLitteAnimation = AnimationUtils.loadAnimation(this,  
  262.                         R.anim.cancel_rc);  
  263.                 Animation mBigAnimation = AnimationUtils.loadAnimation(this,  
  264.                         R.anim.cancel_rc2);  
  265.                 img1.setVisibility(View.GONE);  
  266.                 del_re.setVisibility(View.VISIBLE);  
  267.                 del_re.setBackgroundResource(R.drawable.voice_rcd_cancel_bg);  
  268.                 if (event.getY() >= del_Y  
  269.                         && event.getY() <= del_Y + del_re.getHeight()  
  270.                         && event.getX() >= del_x  
  271.                         && event.getX() <= del_x + del_re.getWidth()) {  
  272.                     del_re.setBackgroundResource(R.drawable.voice_rcd_cancel_bg_focused);  
  273.                     sc_img1.startAnimation(mLitteAnimation);  
  274.                     sc_img1.startAnimation(mBigAnimation);  
  275.                 }  
  276.             } else {  
  277.                 img1.setVisibility(View.VISIBLE);  
  278.                 del_re.setVisibility(View.GONE);  
  279.                 del_re.setBackgroundResource(0);  
  280.             }  
  281.         }  
  282.         return super.onTouchEvent(event);  
  283.     }  
  284.     private static final int POLL_INTERVAL = 300;  
  285.     private Runnable mSleepTask = new Runnable() {  
  286.         public void run() {  
  287.             stop();  
  288.         }  
  289.     };  
  290.     private Runnable mPollTask = new Runnable() {  
  291.         public void run() {  
  292.             double amp = mSensor.getAmplitude();  
  293.             updateDisplay(amp);  
  294.             mHandler.postDelayed(mPollTask, POLL_INTERVAL);  
  295.         }  
  296.     };  
  297.     private void start(String name) {  
  298.         mSensor.start(name);  
  299.         mHandler.postDelayed(mPollTask, POLL_INTERVAL);  
  300.     }  
  301.     private void stop() {  
  302.         mHandler.removeCallbacks(mSleepTask);  
  303.         mHandler.removeCallbacks(mPollTask);  
  304.         mSensor.stop();  
  305.         volume.setImageResource(R.drawable.amp1);  
  306.     }  
  307.     private void updateDisplay(double signalEMA) {  
  308.         switch ((int) signalEMA) {  
  309.         case 0:  
  310.         case 1:  
  311.             volume.setImageResource(R.drawable.amp1);  
  312.             break;  
  313.         case 2:  
  314.         case 3:  
  315.             volume.setImageResource(R.drawable.amp2);  
  316.             break;  
  317.         case 4:  
  318.         case 5:  
  319.             volume.setImageResource(R.drawable.amp3);  
  320.             break;  
  321.         case 6:  
  322.         case 7:  
  323.             volume.setImageResource(R.drawable.amp4);  
  324.             break;  
  325.         case 8:  
  326.         case 9:  
  327.             volume.setImageResource(R.drawable.amp5);  
  328.             break;  
  329.         case 10:  
  330.         case 11:  
  331.             volume.setImageResource(R.drawable.amp6);  
  332.             break;  
  333.         default:  
  334.             volume.setImageResource(R.drawable.amp7);  
  335.             break;  
  336.         }  
  337.     }  
  338.     public void head_xiaohei(View v) { // 标题栏 返回按钮  
  339.     }  
  340. }  
package com.example.voice_rcd;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.SystemClock;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {
    /** Called when the activity is first created. */

    private Button mBtnSend;
    private TextView mBtnRcd;
    private Button mBtnBack;
    private EditText mEditTextContent;
    private RelativeLayout mBottom;
    private ListView mListView;
    private ChatMsgViewAdapter mAdapter;
    private List<ChatMsgEntity> mDataArrays = new ArrayList<ChatMsgEntity>();
    private boolean isShosrt = false;
    private LinearLayout voice_rcd_hint_loading, voice_rcd_hint_rcding,
            voice_rcd_hint_tooshort;
    private ImageView img1, sc_img1;
    private SoundMeter mSensor;
    private View rcChat_popup;
    private LinearLayout del_re;
    private ImageView chatting_mode_btn, volume;
    private boolean btn_vocie = false;
    private int flag = 1;
    private Handler mHandler = new Handler();
    private String voiceName;
    private long startVoiceT, endVoiceT;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat);
        // 启动activity时不自动弹出软键盘
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        initView();

        initData();
    }

    public void initView() {
        mListView = (ListView) findViewById(R.id.listview);
        mBtnSend = (Button) findViewById(R.id.btn_send);
        mBtnRcd = (TextView) findViewById(R.id.btn_rcd);
        mBtnSend.setOnClickListener(this);
        mBtnBack = (Button) findViewById(R.id.btn_back);
        mBottom = (RelativeLayout) findViewById(R.id.btn_bottom);
        mBtnBack.setOnClickListener(this);
        chatting_mode_btn = (ImageView) this.findViewById(R.id.ivPopUp);
        volume = (ImageView) this.findViewById(R.id.volume);
        rcChat_popup = this.findViewById(R.id.rcChat_popup);
        img1 = (ImageView) this.findViewById(R.id.img1);
        sc_img1 = (ImageView) this.findViewById(R.id.sc_img1);
        del_re = (LinearLayout) this.findViewById(R.id.del_re);
        voice_rcd_hint_rcding = (LinearLayout) this
                .findViewById(R.id.voice_rcd_hint_rcding);
        voice_rcd_hint_loading = (LinearLayout) this
                .findViewById(R.id.voice_rcd_hint_loading);
        voice_rcd_hint_tooshort = (LinearLayout) this
                .findViewById(R.id.voice_rcd_hint_tooshort);
        mSensor = new SoundMeter();
        mEditTextContent = (EditText) findViewById(R.id.et_sendmessage);

        //语音文字切换按钮
        chatting_mode_btn.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                if (btn_vocie) {
                    mBtnRcd.setVisibility(View.GONE);
                    mBottom.setVisibility(View.VISIBLE);
                    btn_vocie = false;
                    chatting_mode_btn
                            .setImageResource(R.drawable.chatting_setmode_msg_btn);

                } else {
                    mBtnRcd.setVisibility(View.VISIBLE);
                    mBottom.setVisibility(View.GONE);
                    chatting_mode_btn
                            .setImageResource(R.drawable.chatting_setmode_voice_btn);
                    btn_vocie = true;
                }
            }
        });
        mBtnRcd.setOnTouchListener(new OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {
                //按下语音录制按钮时返回false执行父类OnTouch
                return false;
            }
        });
    }

    private String[] msgArray = new String[] { "有人就有恩怨","有恩怨就有江湖","人就是江湖","你怎么退出? ","生命中充满了巧合","两条平行线也会有相交的一天。"};

    private String[] dataArray = new String[] { "2012-10-31 18:00",
            "2012-10-31 18:10", "2012-10-31 18:11", "2012-10-31 18:20",
            "2012-10-31 18:30", "2012-10-31 18:35"};
    private final static int COUNT = 6;

    public void initData() {
        for (int i = 0; i < COUNT; i++) {
            ChatMsgEntity entity = new ChatMsgEntity();
            entity.setDate(dataArray[i]);
            if (i % 2 == 0) {
                entity.setName("白富美");
                entity.setMsgType(true);
            } else {
                entity.setName("高富帅");
                entity.setMsgType(false);
            }

            entity.setText(msgArray[i]);
            mDataArrays.add(entity);
        }

        mAdapter = new ChatMsgViewAdapter(this, mDataArrays);
        mListView.setAdapter(mAdapter);

    }

    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.btn_send:
            send();
            break;
        case R.id.btn_back:
            finish();
            break;
        }
    }

    private void send() {
        String contString = mEditTextContent.getText().toString();
        if (contString.length() > 0) {
            ChatMsgEntity entity = new ChatMsgEntity();
            entity.setDate(getDate());
            entity.setName("高富帅");
            entity.setMsgType(false);
            entity.setText(contString);

            mDataArrays.add(entity);
            mAdapter.notifyDataSetChanged();

            mEditTextContent.setText("");

            mListView.setSelection(mListView.getCount() - 1);
        }
    }

    private String getDate() {
        Calendar c = Calendar.getInstance();

        String year = String.valueOf(c.get(Calendar.YEAR));
        String month = String.valueOf(c.get(Calendar.MONTH));
        String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH) + 1);
        String hour = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
        String mins = String.valueOf(c.get(Calendar.MINUTE));

        StringBuffer sbBuffer = new StringBuffer();
        sbBuffer.append(year + "-" + month + "-" + day + " " + hour + ":"
                + mins);

        return sbBuffer.toString();
    }

    //按下语音录制按钮时
    @Override
    public boolean onTouchEvent(MotionEvent event) {

        if (!Environment.getExternalStorageDirectory().exists()) {
            Toast.makeText(this, "No SDCard", Toast.LENGTH_LONG).show();
            return false;
        }

        if (btn_vocie) {
            System.out.println("1");
            int[] location = new int[2];
            mBtnRcd.getLocationInWindow(location); // 获取在当前窗口内的绝对坐标
            int btn_rc_Y = location[1];
            int btn_rc_X = location[0];
            int[] del_location = new int[2];
            del_re.getLocationInWindow(del_location);
            int del_Y = del_location[1];
            int del_x = del_location[0];
            if (event.getAction() == MotionEvent.ACTION_DOWN && flag == 1) {
                if (!Environment.getExternalStorageDirectory().exists()) {
                    Toast.makeText(this, "No SDCard", Toast.LENGTH_LONG).show();
                    return false;
                }
                System.out.println("2");
                if (event.getY() > btn_rc_Y && event.getX() > btn_rc_X) {//判断手势按下的位置是否是语音录制按钮的范围内
                    System.out.println("3");
                    mBtnRcd.setBackgroundResource(R.drawable.voice_rcd_btn_pressed);
                    rcChat_popup.setVisibility(View.VISIBLE);
                    voice_rcd_hint_loading.setVisibility(View.VISIBLE);
                    voice_rcd_hint_rcding.setVisibility(View.GONE);
                    voice_rcd_hint_tooshort.setVisibility(View.GONE);
                    mHandler.postDelayed(new Runnable() {
                        public void run() {
                            if (!isShosrt) {
                                voice_rcd_hint_loading.setVisibility(View.GONE);
                                voice_rcd_hint_rcding
                                        .setVisibility(View.VISIBLE);
                            }
                        }
                    }, 300);
                    img1.setVisibility(View.VISIBLE);
                    del_re.setVisibility(View.GONE);
                    startVoiceT = SystemClock.currentThreadTimeMillis();
                    voiceName = startVoiceT + ".amr";
                    start(voiceName);
                    flag = 2;
                }
            } else if (event.getAction() == MotionEvent.ACTION_UP && flag == 2) {//松开手势时执行录制完成
                System.out.println("4");
                mBtnRcd.setBackgroundResource(R.drawable.voice_rcd_btn_nor);
                if (event.getY() >= del_Y
                        && event.getY() <= del_Y + del_re.getHeight()
                        && event.getX() >= del_x
                        && event.getX() <= del_x + del_re.getWidth()) {
                    rcChat_popup.setVisibility(View.GONE);
                    img1.setVisibility(View.VISIBLE);
                    del_re.setVisibility(View.GONE);
                    stop();
                    flag = 1;
                    File file = new File(android.os.Environment.getExternalStorageDirectory()+"/"
                                    + voiceName);
                    if (file.exists()) {
                        file.delete();
                    }
                } else {

                    voice_rcd_hint_rcding.setVisibility(View.GONE);
                    stop();
                    endVoiceT = SystemClock.currentThreadTimeMillis();
                    flag = 1;
                    int time = (int) ((endVoiceT - startVoiceT) / 1000);
                    if (time < 1) {
                        isShosrt = true;
                        voice_rcd_hint_loading.setVisibility(View.GONE);
                        voice_rcd_hint_rcding.setVisibility(View.GONE);
                        voice_rcd_hint_tooshort.setVisibility(View.VISIBLE);
                        mHandler.postDelayed(new Runnable() {
                            public void run() {
                                voice_rcd_hint_tooshort
                                        .setVisibility(View.GONE);
                                rcChat_popup.setVisibility(View.GONE);
                                isShosrt = false;
                            }
                        }, 500);
                        return false;
                    }
                    ChatMsgEntity entity = new ChatMsgEntity();
                    entity.setDate(getDate());
                    entity.setName("高富帅");
                    entity.setMsgType(false);
                    entity.setTime(time+"\"");
                    entity.setText(voiceName);
                    mDataArrays.add(entity);
                    mAdapter.notifyDataSetChanged();
                    mListView.setSelection(mListView.getCount() - 1);
                    rcChat_popup.setVisibility(View.GONE);

                }
            }
            if (event.getY() < btn_rc_Y) {//手势按下的位置不在语音录制按钮的范围内
                System.out.println("5");
                Animation mLitteAnimation = AnimationUtils.loadAnimation(this,
                        R.anim.cancel_rc);
                Animation mBigAnimation = AnimationUtils.loadAnimation(this,
                        R.anim.cancel_rc2);
                img1.setVisibility(View.GONE);
                del_re.setVisibility(View.VISIBLE);
                del_re.setBackgroundResource(R.drawable.voice_rcd_cancel_bg);
                if (event.getY() >= del_Y
                        && event.getY() <= del_Y + del_re.getHeight()
                        && event.getX() >= del_x
                        && event.getX() <= del_x + del_re.getWidth()) {
                    del_re.setBackgroundResource(R.drawable.voice_rcd_cancel_bg_focused);
                    sc_img1.startAnimation(mLitteAnimation);
                    sc_img1.startAnimation(mBigAnimation);
                }
            } else {

                img1.setVisibility(View.VISIBLE);
                del_re.setVisibility(View.GONE);
                del_re.setBackgroundResource(0);
            }
        }
        return super.onTouchEvent(event);
    }

    private static final int POLL_INTERVAL = 300;

    private Runnable mSleepTask = new Runnable() {
        public void run() {
            stop();
        }
    };
    private Runnable mPollTask = new Runnable() {
        public void run() {
            double amp = mSensor.getAmplitude();
            updateDisplay(amp);
            mHandler.postDelayed(mPollTask, POLL_INTERVAL);

        }
    };

    private void start(String name) {
        mSensor.start(name);
        mHandler.postDelayed(mPollTask, POLL_INTERVAL);
    }

    private void stop() {
        mHandler.removeCallbacks(mSleepTask);
        mHandler.removeCallbacks(mPollTask);
        mSensor.stop();
        volume.setImageResource(R.drawable.amp1);
    }

    private void updateDisplay(double signalEMA) {

        switch ((int) signalEMA) {
        case 0:
        case 1:
            volume.setImageResource(R.drawable.amp1);
            break;
        case 2:
        case 3:
            volume.setImageResource(R.drawable.amp2);

            break;
        case 4:
        case 5:
            volume.setImageResource(R.drawable.amp3);
            break;
        case 6:
        case 7:
            volume.setImageResource(R.drawable.amp4);
            break;
        case 8:
        case 9:
            volume.setImageResource(R.drawable.amp5);
            break;
        case 10:
        case 11:
            volume.setImageResource(R.drawable.amp6);
            break;
        default:
            volume.setImageResource(R.drawable.amp7);
            break;
        }
    }

    public void head_xiaohei(View v) { // 标题栏 返回按钮

    }
}
           

 第四:自定义的显示适配器:

Java代码  

android仿微信聊天页面,以及实现语音功能
android仿微信聊天页面,以及实现语音功能
  1. package com.example.voice_rcd;  
  2. import java.util.List;  
  3. import android.content.Context;  
  4. import android.media.MediaPlayer;  
  5. import android.media.MediaPlayer.OnCompletionListener;  
  6. import android.view.LayoutInflater;  
  7. import android.view.View;  
  8. import android.view.View.OnClickListener;  
  9. import android.view.ViewGroup;  
  10. import android.widget.BaseAdapter;  
  11. import android.widget.TextView;  
  12. public class ChatMsgViewAdapter extends BaseAdapter {  
  13.     public static interface IMsgViewType {  
  14.         int IMVT_COM_MSG = 0;  
  15.         int IMVT_TO_MSG = 1;  
  16.     }  
  17.     private static final String TAG = ChatMsgViewAdapter.class.getSimpleName();  
  18.     private List<ChatMsgEntity> coll;  
  19.     private Context ctx;  
  20.     private LayoutInflater mInflater;  
  21.     private MediaPlayer mMediaPlayer = new MediaPlayer();  
  22.     public ChatMsgViewAdapter(Context context, List<ChatMsgEntity> coll) {  
  23.         ctx = context;  
  24.         this.coll = coll;  
  25.         mInflater = LayoutInflater.from(context);  
  26.     }  
  27.     public int getCount() {  
  28.         return coll.size();  
  29.     }  
  30.     public Object getItem(int position) {  
  31.         return coll.get(position);  
  32.     }  
  33.     public long getItemId(int position) {  
  34.         return position;  
  35.     }  
  36.     public int getItemViewType(int position) {  
  37.         // TODO Auto-generated method stub  
  38.         ChatMsgEntity entity = coll.get(position);  
  39.         if (entity.getMsgType()) {  
  40.             return IMsgViewType.IMVT_COM_MSG;  
  41.         } else {  
  42.             return IMsgViewType.IMVT_TO_MSG;  
  43.         }  
  44.     }  
  45.     public int getViewTypeCount() {  
  46.         // TODO Auto-generated method stub  
  47.         return 2;  
  48.     }  
  49.     public View getView(int position, View convertView, ViewGroup parent) {  
  50.         final ChatMsgEntity entity = coll.get(position);  
  51.         boolean isComMsg = entity.getMsgType();  
  52.         ViewHolder viewHolder = null;  
  53.         if (convertView == null) {  
  54.             if (isComMsg) {  
  55.                 convertView = mInflater.inflate(  
  56.                         R.layout.chatting_item_msg_text_left, null);  
  57.             } else {  
  58.                 convertView = mInflater.inflate(  
  59.                         R.layout.chatting_item_msg_text_right, null);  
  60.             }  
  61.             viewHolder = new ViewHolder();  
  62.             viewHolder.tvSendTime = (TextView) convertView  
  63.                     .findViewById(R.id.tv_sendtime);  
  64.             viewHolder.tvUserName = (TextView) convertView  
  65.                     .findViewById(R.id.tv_username);  
  66.             viewHolder.tvContent = (TextView) convertView  
  67.                     .findViewById(R.id.tv_chatcontent);  
  68.             viewHolder.tvTime = (TextView) convertView  
  69.                     .findViewById(R.id.tv_time);  
  70.             viewHolder.isComMsg = isComMsg;  
  71.             convertView.setTag(viewHolder);  
  72.         } else {  
  73.             viewHolder = (ViewHolder) convertView.getTag();  
  74.         }  
  75.         viewHolder.tvSendTime.setText(entity.getDate());  
  76.         if (entity.getText().contains(“.amr”)) {  
  77.             viewHolder.tvContent.setText(”“);  
  78.             viewHolder.tvContent.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.chatto_voice_playing, 0);  
  79.             viewHolder.tvTime.setText(entity.getTime());  
  80.         } else {  
  81.             viewHolder.tvContent.setText(entity.getText());           
  82.             viewHolder.tvContent.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);  
  83.             viewHolder.tvTime.setText(”“);  
  84.         }  
  85.         viewHolder.tvContent.setOnClickListener(new OnClickListener() {  
  86.             public void onClick(View v) {  
  87.                 if (entity.getText().contains(“.amr”)) {  
  88.                     playMusic(android.os.Environment.getExternalStorageDirectory()+”/”+entity.getText()) ;  
  89.                 }  
  90.             }  
  91.         });  
  92.         viewHolder.tvUserName.setText(entity.getName());  
  93.         return convertView;  
  94.     }  
  95.     static class ViewHolder {  
  96.         public TextView tvSendTime;  
  97.         public TextView tvUserName;  
  98.         public TextView tvContent;  
  99.         public TextView tvTime;  
  100.         public boolean isComMsg = true;  
  101.     }  
  102.     private void playMusic(String name) {  
  103.         try {  
  104.             if (mMediaPlayer.isPlaying()) {  
  105.                 mMediaPlayer.stop();  
  106.             }  
  107.             mMediaPlayer.reset();  
  108.             mMediaPlayer.setDataSource(name);  
  109.             mMediaPlayer.prepare();  
  110.             mMediaPlayer.start();  
  111.             mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {  
  112.                 public void onCompletion(MediaPlayer mp) {  
  113.                 }  
  114.             });  
  115.         } catch (Exception e) {  
  116.             e.printStackTrace();  
  117.         }  
  118.     }  
  119.     private void stop() {  
  120.     }  
  121. }  
package com.example.voice_rcd;

import java.util.List;

import android.content.Context;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class ChatMsgViewAdapter extends BaseAdapter {

    public static interface IMsgViewType {
        int IMVT_COM_MSG = 0;
        int IMVT_TO_MSG = 1;
    }

    private static final String TAG = ChatMsgViewAdapter.class.getSimpleName();

    private List<ChatMsgEntity> coll;

    private Context ctx;

    private LayoutInflater mInflater;
    private MediaPlayer mMediaPlayer = new MediaPlayer();

    public ChatMsgViewAdapter(Context context, List<ChatMsgEntity> coll) {
        ctx = context;
        this.coll = coll;
        mInflater = LayoutInflater.from(context);
    }

    public int getCount() {
        return coll.size();
    }

    public Object getItem(int position) {
        return coll.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public int getItemViewType(int position) {
        // TODO Auto-generated method stub
        ChatMsgEntity entity = coll.get(position);

        if (entity.getMsgType()) {
            return IMsgViewType.IMVT_COM_MSG;
        } else {
            return IMsgViewType.IMVT_TO_MSG;
        }

    }

    public int getViewTypeCount() {
        // TODO Auto-generated method stub
        return 2;
    }

    public View getView(int position, View convertView, ViewGroup parent) {

        final ChatMsgEntity entity = coll.get(position);
        boolean isComMsg = entity.getMsgType();

        ViewHolder viewHolder = null;
        if (convertView == null) {
            if (isComMsg) {
                convertView = mInflater.inflate(
                        R.layout.chatting_item_msg_text_left, null);
            } else {
                convertView = mInflater.inflate(
                        R.layout.chatting_item_msg_text_right, null);
            }

            viewHolder = new ViewHolder();
            viewHolder.tvSendTime = (TextView) convertView
                    .findViewById(R.id.tv_sendtime);
            viewHolder.tvUserName = (TextView) convertView
                    .findViewById(R.id.tv_username);
            viewHolder.tvContent = (TextView) convertView
                    .findViewById(R.id.tv_chatcontent);
            viewHolder.tvTime = (TextView) convertView
                    .findViewById(R.id.tv_time);
            viewHolder.isComMsg = isComMsg;

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.tvSendTime.setText(entity.getDate());

        if (entity.getText().contains(".amr")) {
            viewHolder.tvContent.setText("");
            viewHolder.tvContent.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.chatto_voice_playing, 0);
            viewHolder.tvTime.setText(entity.getTime());
        } else {
            viewHolder.tvContent.setText(entity.getText());         
            viewHolder.tvContent.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
            viewHolder.tvTime.setText("");
        }
        viewHolder.tvContent.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                if (entity.getText().contains(".amr")) {
                    playMusic(android.os.Environment.getExternalStorageDirectory()+"/"+entity.getText()) ;
                }
            }
        });
        viewHolder.tvUserName.setText(entity.getName());

        return convertView;
    }

    static class ViewHolder {
        public TextView tvSendTime;
        public TextView tvUserName;
        public TextView tvContent;
        public TextView tvTime;
        public boolean isComMsg = true;
    }

    /**
     * @Description
     * @param name
     */
    private void playMusic(String name) {
        try {
            if (mMediaPlayer.isPlaying()) {
                mMediaPlayer.stop();
            }
            mMediaPlayer.reset();
            mMediaPlayer.setDataSource(name);
            mMediaPlayer.prepare();
            mMediaPlayer.start();
            mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
                public void onCompletion(MediaPlayer mp) {

                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void stop() {

    }

}
           

觉得很不错,看不明白,有疑问的留言,互相学习