在Edittext中自定义文本以进行聊天

时间:2014-02-06 03:45:54

标签: java android

我想在聊天应用的edittext中自定义文本。我想为他的消息加粗用户名和普通字体。 例如;

usernamejay:嗨这是周杰伦。你好吗?

还会在usernamejay的消息后留出1个空格进行回复。我还想更改用户名的字体颜色。如果可能的话,还要为每条消息添加消息气球。

示例:

usernamejay:嗨这是周杰伦。你好吗?

usernameclark:我很好。我现在可以打电话给你开会吗?

任何人都可以帮助我。这是Java的代码

import java.io.UnsupportedEncodingException;
import com.example.healthhelpv2.*;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import at.vcity.androidim.interfaces.IAppManager;
import at.vcity.androidim.services.IMService;
import at.vcity.androidim.tools.FriendController;
import at.vcity.androidim.tools.LocalStorageHandler;
import at.vcity.androidim.types.FriendInfo;
import at.vcity.androidim.types.MessageInfo;


public class Messaging extends Activity {

    private static final int MESSAGE_CANNOT_BE_SENT = 0;
    public String username;
    private EditText messageText;
    private EditText messageHistoryText;
    private Button sendMessageButton;
    private IAppManager imService;
    private FriendInfo friend = new FriendInfo();
    private LocalStorageHandler localstoragehandler; 
    private Cursor dbCursor;

    private ServiceConnection mConnection = new ServiceConnection() {



        public void onServiceConnected(ComponentName className, IBinder service) {          
            imService = ((IMService.IMBinder)service).getService();
        }
        public void onServiceDisconnected(ComponentName className) {
            imService = null;
            Toast.makeText(Messaging.this, R.string.local_service_stopped,
                    Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);    

        setContentView(R.layout.messaging_screen); //messaging_screen);

        messageHistoryText = (EditText) findViewById(R.id.messageHistory);

        messageText = (EditText) findViewById(R.id.message);

        messageText.requestFocus();         

        sendMessageButton = (Button) findViewById(R.id.sendMessageButton);

        Bundle extras = this.getIntent().getExtras();


        friend.userName = extras.getString(FriendInfo.USERNAME);
        friend.ip = extras.getString(FriendInfo.IP);
        friend.port = extras.getString(FriendInfo.PORT);
        String msg = extras.getString(MessageInfo.MESSAGETEXT);



        setTitle("Messaging with " + friend.userName);


    //  EditText friendUserName = (EditText) findViewById(R.id.friendUserName);
    //  friendUserName.setText(friend.userName);


        localstoragehandler = new LocalStorageHandler(this);
        dbCursor = localstoragehandler.get(friend.userName, IMService.USERNAME );

        if (dbCursor.getCount() > 0){
        int noOfScorer = 0;
        dbCursor.moveToFirst();
            while ((!dbCursor.isAfterLast())&&noOfScorer<dbCursor.getCount()) 
            {
                noOfScorer++;

                this.appendToMessageHistory(dbCursor.getString(2) , dbCursor.getString(3));
                dbCursor.moveToNext();
            }
        }
        localstoragehandler.close();

        if (msg != null) 
        {
            this.appendToMessageHistory(friend.userName , msg);
            ((NotificationManager)getSystemService(NOTIFICATION_SERVICE)).cancel((friend.userName+msg).hashCode());
        }

        sendMessageButton.setOnClickListener(new OnClickListener(){
            CharSequence message;
            Handler handler = new Handler();
            public void onClick(View arg0) {
                message = messageText.getText();
                if (message.length()>0) 
                {       
                    appendToMessageHistory(imService.getUsername(), message.toString());

                    localstoragehandler.insert(imService.getUsername(), friend.userName, message.toString());

                    messageText.setText("");
                    Thread thread = new Thread(){                   
                        public void run() {
                            try {
                                if (imService.sendMessage(imService.getUsername(), friend.userName, message.toString()) == null)
                                {

                                    handler.post(new Runnable(){    

                                        public void run() {

                                            Toast.makeText(getApplicationContext(),R.string.message_cannot_be_sent, Toast.LENGTH_LONG).show();


                                            //showDialog(MESSAGE_CANNOT_BE_SENT);                                       
                                        }

                                    });
                                }
                            } catch (UnsupportedEncodingException e) {
                                Toast.makeText(getApplicationContext(),R.string.message_cannot_be_sent, Toast.LENGTH_LONG).show();

                                e.printStackTrace();
                            }
                        }                       
                    };
                    thread.start();

                }

            }});

        messageText.setOnKeyListener(new OnKeyListener(){
            public boolean onKey(View v, int keyCode, KeyEvent event) 
            {
                if (keyCode == 66){
                    sendMessageButton.performClick();
                    return true;
                }
                return false;
            }


        });

    }

    @Override
    protected Dialog onCreateDialog(int id) {
        int message = -1;
        switch (id)
        {
        case MESSAGE_CANNOT_BE_SENT:
            message = R.string.message_cannot_be_sent;
        break;
        }

        if (message == -1)
        {
            return null;
        }
        else
        {
            return new AlertDialog.Builder(Messaging.this)       
            .setMessage(message)
            .setPositiveButton(R.string.OK, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    /* User clicked OK so do some stuff */
                }
            })        
            .create();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(messageReceiver);
        unbindService(mConnection);

        FriendController.setActiveFriend(null);

    }

    @Override
    protected void onResume() 
    {       
        super.onResume();
        bindService(new Intent(Messaging.this, IMService.class), mConnection , Context.BIND_AUTO_CREATE);

        IntentFilter i = new IntentFilter();
        i.addAction(IMService.TAKE_MESSAGE);

        registerReceiver(messageReceiver, i);

        FriendController.setActiveFriend(friend.userName);      


    }


    public class  MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) 
        {       
            Bundle extra = intent.getExtras();
            String username = extra.getString(MessageInfo.USERID);          
            String message = extra.getString(MessageInfo.MESSAGETEXT);

            if (username != null && message != null)
            {
                if (friend.userName.equals(username)) {
                    appendToMessageHistory(username, message);
                    localstoragehandler.insert(username,imService.getUsername(), message);

                }
                else {
                    if (message.length() > 15) {
                        message = message.substring(0, 15);
                    }
                    Toast.makeText(Messaging.this,  username + " says '"+
                                                    message + "'",
                                                    Toast.LENGTH_SHORT).show();     
                }
            }           
        }

    };
    private MessageReceiver messageReceiver = new MessageReceiver();

    public  void appendToMessageHistory(String username, String message) {
        if (username != null && message != null) {
            messageHistoryText.append(username + ":\n");                                
            messageHistoryText.append(message + "\n");
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (localstoragehandler != null) {
            localstoragehandler.close();
        }
        if (dbCursor != null) {
            dbCursor.close();
        }
    }


}

XML messaging_screen

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ccbfbf"
    android:orientation="vertical"
    android:padding="10dip" >

<!--    
    <TextView 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dip"
        android:text="Friend:"
    />

    <EditText android:id="@+id/friendUserName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:clickable="true"
        android:singleLine="true"
        android:editable="false" />
--> 
    <TextView   android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dip"
                android:text="Messages:"/>

    <EditText   android:id="@+id/messageHistory"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:clickable="true"    
                android:layout_weight="1"
                android:editable="false"
                android:gravity="top"
                android:scrollbars="vertical"
                android:scrollbarSize="10px"
                /> 

    <LinearLayout android:orientation="horizontal"
                  android:layout_width="fill_parent"
                  android:layout_height="fill_parent"
                  android:layout_weight="4">

            <EditText
                android:id="@+id/message"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_weight="1"
                android:gravity="top"
                android:hint="Type message here!" />

            <Button android:id="@+id/sendMessageButton"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:layout_weight="4"
                    android:text="Send"/>

    </LinearLayout>

</LinearLayout>

3 个答案:

答案 0 :(得分:0)

在Android上,您可以使用HTML在TextView中设置文本样式,请参阅此处http://daniel-codes.blogspot.pt/2011/04/html-in-textviews.html

答案 1 :(得分:0)

这样做希望这对你有用

EditText editText = (EditText)findViewById(R.id.editText);
        String userName = "usernamejay";
        String message = "Hi This is Jay. How are you?";
        String finalStr = "<b>"+userName+":</b> "+message+"";
        editText.setText(Html.fromHtml(finalStr));

答案 2 :(得分:0)

您也可以使用spannable字符串,也许您可​​以查看this answer中代码的一部分。

来自链接的代码摘录

 final SpannableString out0 = new SpannableString(source[position]);
 StyleSpan boldSpan = new StyleSpan(Typeface.BOLD);
 out0.setSpan(boldSpan, 6, 17, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
 holder.tv.setText(out0);

P.S:但请在开始在代码中应用内容之前阅读链接中的解决方案。