在Android聊天中列出视图控制消息文本

时间:2015-10-19 14:13:30

标签: listview arraylist android-listview chat listviewitem

我正在开发一款聊天应用。 gcm服务正如预期的那样工作,聊天活动,但我现在遇到的问题是,每当设备向另一台设备发送消息时,我都会正确收到消息通知,但当我点击消息时我只看到一个空白列表发件人消息的视图。这些是我的代码:

Messaging Activity

        public class Messaging extends Activity {

        private static final String TAG = "ChatActivity";

        private static final int MESSAGE_CANNOT_BE_SENT = 0;
        private EditText messageText;
        // private EditText messageHistoryText;

        private ListView messageHistoryText;

        private EditText chatText;

        private ListView listView;
        private ChatArrayAdapter chatArrayAdapter;

        private Button sendMessageButton;
        private IAppManager imService;

        private boolean side = false;


        private FriendInfo friend = new FriendInfo();

        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 = (ListView) findViewById(R.id.listView1); //ListView


            chatArrayAdapter = new ChatArrayAdapter(getApplicationContext(), R.layout.activity_chat_singlemessage);
            messageHistoryText.setAdapter(chatArrayAdapter);


            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);
            final String msg = extras.getString(FriendInfo.MESSAGE);


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

            messageText.setOnKeyListener(new OnKeyListener() {
                public boolean onKey(View v, int keyCode, KeyEvent event) {
                    if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                        return sendChatMessage(friend.userName, msg);
                    }
                    return false;
                }
            });






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





            sendMessageButton.setOnClickListener(new View.OnClickListener() {
                CharSequence message;
                Handler handler = new Handler();
              @Override
                public void onClick(View arg0) {

                      sendChatMessage(imService.getUsername(), message.toString());

                  }

             }
             });



            messageHistoryText.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
            messageHistoryText.setAdapter(chatArrayAdapter);



            //to scroll the list view to bottom on data change
            chatArrayAdapter.registerDataSetObserver(new DataSetObserver() {
                @Override
                public void onChanged() {
                    super.onChanged();
                    messageHistoryText.setSelection(chatArrayAdapter.getCount() - 1);
                }
            });


        }



        @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(FriendInfo.USERNAME);         
                String message = extra.getString(FriendInfo.MESSAGE);

                if (username != null && message != null)
                {
                    if (friend.userName.equals(username)) {
                        sendChatMessage(username, message); //Edit
                    }
                    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();





        private boolean sendChatMessage(String username, String message) {

                chatArrayAdapter.add(new ChatMessage(side, messageText.getText().toString()));
            messageText.setText("");

           side = !side;

            return true;
        }
        }




 message_chat.xml


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

        <TextView   android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="10dip"
                    android:text="Messages:"
            android:id="@+id/textView" />

        <ListView
            android:id="@+id/listView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="80dp"
            >
        </ListView>


        <RelativeLayout android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
                      android:layout_weight="4"
            android:weightSum="1"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true">

            <EditText   android:id="@+id/message"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_alignParentBottom="true"
                    android:layout_alignParentLeft="true"
                    android:layout_alignParentStart="true"
                            android:gravity="top"
                android:layout_toLeftOf="@+id/sendMessageButton"
                android:layout_toStartOf="@+id/sendMessageButton" />


            <Button android:id="@+id/sendMessageButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
        android:text="Send"
                android:layout_gravity="right"
                android:layout_alignParentBottom="true"
                android:layout_alignParentRight="true"
                android:layout_alignParentEnd="true" />

        </RelativeLayout>

    </RelativeLayout>


ChatArrayAdapter Class 


        public class ChatArrayAdapter extends ArrayAdapter<ChatMessage> {

        private TextView messagel;
        private List<ChatMessage> chatMessageList = new ArrayList<ChatMessage>();
        private LinearLayout singleMessageContainer;

        @Override
        public void add(ChatMessage object) {
            chatMessageList.add(object);
            super.add(object);
        }

        public ChatArrayAdapter(Context context, int textViewResourceId) {
            super(context, textViewResourceId);
        }

        public int getCount() {
            return this.chatMessageList.size();
        }

        public ChatMessage getItem(int index) {
            return this.chatMessageList.get(index);
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ChatMessage chatMessageObj = getItem(position);
            View row = convertView;
            if (row == null) {

                LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);


            if (chatMessageObj.left) {
                row = inflater.inflate(R.layout.right, parent, false);
            }else{
                row = inflater.inflate(R.layout.left, parent, false);
            }


           }


            messagel = (TextView) row.findViewById(R.id.msgr);
            messagel.setText(chatMessageObj.message);

            return row;
        }

        public Bitmap decodeToBitmap(byte[] decodedByte) {
            return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
        }    }


Chat Message Class

            public class ChatMessage {

        public boolean left;
        public String message;

        public ChatMessage(boolean left, String message) {
            super();
            this.left = left;
            this.message = message;
        }    }


left.xml is same as right.xml in code just layout_gravity difference
            <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/msgr"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="left"
            android:layout_marginBottom="5dp"
            android:layout_marginRight="20dp"
            android:background="@drawable/textview"
            android:paddingBottom="8dp"
            android:paddingLeft="10dp"
            android:paddingRight="10dp"
            android:paddingTop="5dp"
            android:text="Sampleleft"
            android:textColor="#000" />
    </RelativeLayout>

提前致谢。亲切的问候,史蒂夫。

0 个答案:

没有答案