0

我正在开发一个聊天应用程序并停留在这个位置,当用户键入他的消息时,它会显示在列表视图行中,但我想在聊天气泡中显示它,我也在此处发布我的完整代码,

在此处输入图像描述

我想做这样的东西,

但现在我只能发布简单的列表元素,上面写有文本,按下发送按钮。

我怎样才能达到预期的结果?我做了很多研究,但没有一篇文章令人满意。

这是我的

聊天.xml

<?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="wrap_content"
    android:orientation="horizontal"
    android:background="#ffffff"
     >

    <Button 
        android:id="@+id/buttonchat"
        android:layout_width="50dip"
        android:layout_height="50dip" 
        android:background="@drawable/home"
        android:paddingBottom="2dip"
        android:layout_alignParentLeft="true"/>

    <TextView 
       android:layout_width="fill_parent"
        android:fillViewport="true"
        android:text="Talk"
        android:fontFamily="Sans-Seriff"
        android:textSize="32sp"
        android:gravity="center"
        android:textColor="#1d1d1d"
        android:layout_height="fill_parent"
        android:layout_toRightOf="@+id/buttonchat"
        android:layout_toLeftOf="@+id/buttonchat4" 
        android:layout_above="@+id/txtMessagesReceived"
        android:id="@+id/txtMessagesReceived2"
        />
    <Button
        android:id="@+id/buttonchat4"
        android:layout_width="60dip"
        android:layout_height="50dip"
        android:layout_alignParentRight="true"
        android:background="@drawable/but2"
        android:minHeight="45dp"
        android:minWidth="60dp" />



        <ListView

        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/txtMessagesReceived"
        android:layout_width="fill_parent"
        android:fillViewport="true"
        android:layout_height="fill_parent"
        android:background="#c8c8c8"
        android:layout_below="@+id/buttonchat"
        android:layout_above="@+id/buttonchat2"
        />




    <Button 
        android:id="@+id/buttonchat2"
        android:layout_width="50dip"
        android:layout_height="50dip" 
        android:layout_alignParentBottom="true"
        android:background="@drawable/camera" 
        android:layout_alignParentLeft="true"/>

    <EditText
        android:id="@+id/txtMessage"
        android:layout_width="fill_parent"
        android:layout_height="50dip"
        android:fillViewport="true"
        android:layout_toRightOf="@+id/buttonchat2"
        android:layout_toLeftOf="@+id/buttonchat3" 
        android:layout_below="@+id/txtMessagesReceived"
        android:layout_alignParentBottom="true"

        />

    <Button 
        android:layout_width="60dip"
        android:layout_height="50dip"
        android:id="@+id/buttonchat3"
        android:layout_alignParentBottom="true"
        android:background="@drawable/send"
        android:layout_alignParentRight="true"
        />




</RelativeLayout>

现在这里是

聊天活动.java

import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;



import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
//import android.view.Menu;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ChatScreenActivity extends Activity implements OnClickListener  {

    Button chatButton;
    EditText medit;
    ListView mView;
     private ArrayList<String> itemArrey;
        private ArrayAdapter<String> itemAdapter;



      private InputStream OpenHttpConnection(String urlString) throws IOException
        {
        InputStream in = null;
        int response = -1;
        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();
        if (!(conn instanceof HttpURLConnection))
        throw new IOException("Not an HTTP connection");
        try{
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setAllowUserInteraction(false);
        httpConn.setInstanceFollowRedirects(true);
        httpConn.setRequestMethod("GET");
        httpConn.connect();
        response = httpConn.getResponseCode();
        if (response == HttpURLConnection.HTTP_OK) {
        in = httpConn.getInputStream();
        }
        }
        catch (Exception ex)
        {
        Log.d("Networking", ex.getLocalizedMessage());
        throw new IOException("Error connecting");
        }
        return in;
        }

        private Bitmap DownloadImage(String URL)
        {
        Bitmap bitmap = null;
        InputStream in = null;
        try {
        in = OpenHttpConnection(URL);
        bitmap = BitmapFactory.decodeStream(in);
        in.close();
        } catch (IOException e1) {
        Log.d("NetworkingActivity", e1.getLocalizedMessage());
        }
        return bitmap;
        }
        private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        protected Bitmap doInBackground(String... urls) {
        return DownloadImage(urls[0]);
        }
        protected void onPostExecute(Bitmap result) {
        ImageView img = (ImageView) findViewById(R.id.img);
        img.setImageBitmap(result);
        }
        }

  //  static TextView txtMessagesReceived;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Remove title bar
                //this.requestWindowFeature(Window.FEATURE_NO_TITLE);

                //Remove notification bar
                //this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_chat_screen);



//      LinearLayout lView = new LinearLayout(this);

        /*TextView myText = new TextView(this);
        myText.setText("Connecting to server...");

        lView.addView(myText);

        setContentView(lView); */
         //LinearLayout lView = new LinearLayout(this);

        chatButton=(Button)findViewById(R.id.buttonchat3);
        chatButton.setOnClickListener(this);


    }

    private void setUpView() {
        // TODO Auto-generated method stub
        medit = (EditText)this.findViewById(R.id.txtMessage);
        chatButton = (Button)this.findViewById(R.id.buttonchat3);
        mView = (ListView)this.findViewById(R.id.txtMessagesReceived);


        itemArrey = new ArrayList<String>();
        itemArrey.clear();

        itemAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,itemArrey);
        mView.setAdapter(itemAdapter);


        chatButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

                addItemList();
            }
        });

        medit.setOnKeyListener(new View.OnKeyListener() {

            public boolean onKey(View v, int keyCode, KeyEvent event) {
                // TODO Auto-generated method stub

                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    addItemList();
                }
                return true;
            }
        });


    }


     protected void addItemList() {
            // TODO Auto-generated method stub

            // TODO Auto-generated method stub
        if (isInputValid(medit)) {
            itemArrey.add(0,medit.getText().toString());
            medit.setText("");

            itemAdapter.notifyDataSetChanged();

        }   

        }


      protected boolean isInputValid(EditText etInput2) {
            // TODO Auto-generatd method stub
            if (etInput2.getText().toString().trim().length()<1) {
                etInput2.setError("Please Enter Message");
                return false;
            } else {
                return true;
            }

        }


      private void chatbutton()
        {

          medit=(EditText)findViewById(R.id.txtMessage);

           String Str=medit.getText().toString();
           if(Str.equals("") || Str.equals(null) )
           {

               Toast.makeText(this,"Please Type Something...",Toast.LENGTH_LONG).show();
           }
           else
           {
           mView=(ListView)findViewById(R.id.txtMessagesReceived);
          // mView.append("Me: "+Sr+"\n");
           //Toast.makeText(this,"Me:"+Str,Toast.LENGTH_LONG).show();
           setUpView();

          // medit.setText("");
           }
           // connectServer();


        }


    public void onClick(View v2)
    {
        switch (v2.getId())
        {
        case R.id.buttonchat3:
        chatbutton();
        break;
        }
    }



    private void connectServer()
    {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet("http://members.webtitude.in/project/Android/android.php");
        try {
            HttpResponse response = httpclient.execute(httpget);
            if(response != null) {
                String line = "";
                InputStream inputstream = response.getEntity().getContent();
                line = convertStreamToString(inputstream);
                Toast.makeText(this, line, Toast.LENGTH_LONG).show();

            } else {
                Toast.makeText(this, "Unable to complete your request", Toast.LENGTH_LONG).show();
            }
        } catch (ClientProtocolException e) {
            Toast.makeText(this, "Caught ClientProtocolException", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            Toast.makeText(this, "Internet Seems to not work properly", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(this, "Did not get the url !", Toast.LENGTH_SHORT).show();
        }

    }

    private String convertStreamToString(InputStream is) {
        String line = "";
        StringBuilder total = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        try {
            while ((line = rd.readLine()) != null) {
                total.append(line);
            }
        } catch (Exception e) {
            Toast.makeText(this, "Stream Exception", Toast.LENGTH_SHORT).show();
        }
        return total.toString();
    }



}

任何形式的帮助都是可观的!

我只需要一个指导,告诉我正确的道路,我会自己走完整个路。

4

1 回答 1

0

使您自己的类扩展BaseAdapter并定义您想要的行为。还可以创建自己的列表项布局。我建议您观看ListView 的世界以了解您需要了解的所有内容ListView

于 2013-06-07T15:33:01.300 回答