热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何在Android中自定义ListView?-HowtocustomizetheListViewinAndroid?

Iamworkingonachatapplicationandstuckatthispositionwherewhenausertypeshismessageit

I am working on a chat application and stuck at this position where when a user types his message it is displayed in the listview row , but i want to show it in a chat bubble , i am also posting here my complete code,

我正在开发一个聊天应用程序并停留在这个位置,当用户输入他的消息时,它显示在listview行中,但我想在聊天气泡中显示它,我也在这里发布我的完整代码,

enter image description here

i want to make something like this,

我想做这样的事,

but right now i can only post simple List elements with text written on them with send button press.

但是现在我只能发送简单的List元素,文字写在上面,按下发送按钮。

How can i achieve the desired result ? I have done a lot of research but none of the post was satisfactory.

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

Here is my

这是我的

chat.xml





    

Now here is the

现在这里是

chatactivity.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 itemArrey;
        private ArrayAdapter 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 {
        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();
        itemArrey.clear();

        itemAdapter = new ArrayAdapter(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();
    }



}

Any kind of help is appreciable !

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

I just need a Guidance , just show me the right path , i will travel the whole way by myself.

我只需要一个指导,只要告诉我正确的道路,我将自己一路旅行。

1 个解决方案

#1


0  

Make your own class extending BaseAdapter and define the behavior that you want. Also create your own list item layouts. I recommend you watch The World of ListView to undertsand everything you need to know about ListView

使您自己的类扩展BaseAdapter并定义所需的行为。还可以创建自己的列表项布局。我建议您观看ListView的World of underts以及您需要了解的有关ListView的所有信息


推荐阅读
  • 在一对一直播源码使用过程中,有时会出现软键盘切换闪屏问题,就是当切换表情的时候屏幕会跳动,因此要对一对一直播源码表情面板无缝切换进行优化。 ... [详细]
  • 本文介绍了使用kotlin实现动画效果的方法,包括上下移动、放大缩小、旋转等功能。通过代码示例演示了如何使用ObjectAnimator和AnimatorSet来实现动画效果,并提供了实现抖动效果的代码。同时还介绍了如何使用translationY和translationX来实现上下和左右移动的效果。最后还提供了一个anim_small.xml文件的代码示例,可以用来实现放大缩小的效果。 ... [详细]
  • ZSI.generate.Wsdl2PythonError: unsupported local simpleType restriction ... [详细]
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • Android系统移植与调试之如何修改Android设备状态条上音量加减键在横竖屏切换的时候的显示于隐藏
    本文介绍了如何修改Android设备状态条上音量加减键在横竖屏切换时的显示与隐藏。通过修改系统文件system_bar.xml实现了该功能,并分享了解决思路和经验。 ... [详细]
  • 本文介绍了Android 7的学习笔记总结,包括最新的移动架构视频、大厂安卓面试真题和项目实战源码讲义。同时还分享了开源的完整内容,并提醒读者在使用FileProvider适配时要注意不同模块的AndroidManfiest.xml中配置的xml文件名必须不同,否则会出现问题。 ... [详细]
  • 在Xamarin XAML语言中如何在页面级别构建ControlTemplate控件模板
    本文介绍了在Xamarin XAML语言中如何在页面级别构建ControlTemplate控件模板的方法和步骤,包括将ResourceDictionary添加到页面中以及在ResourceDictionary中实现模板的构建。通过本文的阅读,读者可以了解到在Xamarin XAML语言中构建控件模板的具体操作步骤和语法形式。 ... [详细]
  • MyBatis多表查询与动态SQL使用
    本文介绍了MyBatis多表查询与动态SQL的使用方法,包括一对一查询和一对多查询。同时还介绍了动态SQL的使用,包括if标签、trim标签、where标签、set标签和foreach标签的用法。文章还提供了相关的配置信息和示例代码。 ... [详细]
  • iOS超签签名服务器搭建及其优劣势
    本文介绍了搭建iOS超签签名服务器的原因和优势,包括不掉签、用户可以直接安装不需要信任、体验好等。同时也提到了超签的劣势,即一个证书只能安装100个,成本较高。文章还详细介绍了超签的实现原理,包括用户请求服务器安装mobileconfig文件、服务器调用苹果接口添加udid等步骤。最后,还提到了生成mobileconfig文件和导出AppleWorldwideDeveloperRelationsCertificationAuthority证书的方法。 ... [详细]
  • 本文讨论了在Spring 3.1中,数据源未能自动连接到@Configuration类的错误原因,并提供了解决方法。作者发现了错误的原因,并在代码中手动定义了PersistenceAnnotationBeanPostProcessor。作者删除了该定义后,问题得到解决。此外,作者还指出了默认的PersistenceAnnotationBeanPostProcessor的注册方式,并提供了自定义该bean定义的方法。 ... [详细]
  • 校园表白墙微信小程序,校园小情书、告白墙、论坛,大学表白墙搭建教程
    小程序的名字必须和你微信注册的名称一模一样在后台注册好小程序。mp.wx-union.cn后台域名https。mp.wx-union.cn ... [详细]
  • 网络安全是一个非常重要的课题,基本上你运行的服务后台越多,你就可能打开更多的安全漏洞.如果配置的恰当的话,Linux本身是非常安全可靠的,假使在Linux系统中有某个安全缺陷,由于Linu ... [详细]
  • 最近学习了关于使用最为流行的jquery发送请求,在实践中以最为简单的聊天室作为测验的辅助工具,对相关网页开发有一个初步的认识,希望大家能够一起学习进步。首先介绍一下 ... [详细]
  • 竟然可以检查微信是否被删了好友?(Android Accessibility 了解一下)
    前言最近在研究Android辅助服务,实现了这个小工具,也算是对最近学习的一个总结。原理通过Android无障碍辅助功能实现模拟点击 ... [详细]
  • 好友关系是社交IM中非常重要的一个模块,一般意义上的理解即是成为好友关系以后。才能进行聊天沟通但是对于融云来说只要你给了的userid,我知道了对方的userid就跟 ... [详细]
author-avatar
田小多
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有