个人仿制android QQ、android大作业

1、概要

这个作品有五个界面:首页、登录、注册、好友、聊天。实现了一些简易的功能,连接服务器进行登录和注册功能,显示了好友列表,借鉴别人的聊天页面。

试运行用户:

用户名:123

密码:     123

2、首页界面、

在这个页面进行应用打开缓冲,根据登录状态信息判断进行页面跳转,未登录-》登录界面、登录-》好友界面。

3、 登录界面

在这个界面进行登录信息输入,连接服务器验证信息,正确跳转到好友界面,并存储登录信息和状态,下次打开应用不必登录,错误进行提醒。如果无账号,点击新用户,进入注册页面

4、注册界面

该页面进行注册功能,连接服务器,进行注册,注册成功进入登录界面,也可以点击返回,返回登录界面

5、好友界面

显示好友消息,好友消息,如果不退出登录,下次打开应用进入此界面。点击退出登录,会清除登录信息,点击好友进入聊天页面。

6、聊天界面

该页面进行聊天,可发送字符和表情,未连接服务器。点击返回键返回好友界面。

7、代码简述

app应用

MainActivity

publicclass MainActivity extends Activity {

    @Override

    protectedvoid onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

       

        //登录信息检测

        String flag=user();

       /*flag="1";*/

       

        if(flag.equals("0")){

         

        Intent intent=new Intent(this,Login.class);

        startActivity(intent);

       

        }else {

       

        Intent intent=new Intent(this,Index.class);

       

        Bundle bundle=new Bundle();

        //传递name参数为tinyphp

        bundle.putString("username", flag);

        intent.putExtras(bundle);

       

        startActivity(intent);

       

      }

    }

    //登录信息查看

    public String user(){

      ContextotherAppsContext;

      Stringusername="";

      Stringflag="0";

      try {

        otherAppsContext = createPackageContext("com.example.qq", Context.CONTEXT_IGNORE_SECURITY);

        SharedPreferences sharedPreferences = otherAppsContext.getSharedPreferences("user", Context.MODE_WORLD_READABLE);

         username = sharedPreferences.getString("username", "0");

         flag = sharedPreferences.getString("flag", "0");

      } catch (NameNotFoundException e) {

        // TODO Auto-generatedcatch block

        e.printStackTrace();

      }

      if (flag.equals("0")) {

        return"0";

      } else {

        return username;

      }

     

    }

    @Override

    publicboolean onCreateOptionsMenu(Menu menu){

        // Inflate the menu; this adds items to the action bar if it is present.

        getMenuInflater().inflate(R.menu.main, menu);

        returntrue;

    }

    @Override

    publicboolean onOptionsItemSelected(MenuItemitem) {

        // Handle action bar item clicks here. The action bar will

        // automatically handle clicks on the Home/Up button, so long

        // as you specify a parent activity in AndroidManifest.xml.

        int id = item.getItemId();

        if (id == R.id.action_settings) {

            returntrue;

        }

        returnsuper.onOptionsItemSelected(item);

    }

}

Login.java

publicclass Login extends Activity{

  

   privatestaticintF = 0;

   EditText eText1,eText2;

   String username="",password="",i="";

  

   @Override

   protectedvoid onCreate(Bundle savedInstanceState) {

      // TODO Auto-generatedmethod stub

      super.onCreate(savedInstanceState);

      setContentView(R.layout.activity_login);

     

      eText1=(EditText) findViewById(R.id.editText1);

      eText2=(EditText) findViewById(R.id.editText2);

     

     

     

   }

  

   //登录按钮点击方法

  

   publicvoid Btn1OnClick(View view){

     

     

      username=eText1.getText().toString();

      password=eText2.getText().toString();

     

      if(username.length()==0||password.length()==0){

        

         Toast.makeText(getApplicationContext(),"账号密码不能为空!",

             Toast.LENGTH_SHORT).show();

        

      }else{

         Runnable t = new Runnable(){                 //线程

           @Override

           publicvoid run() {

           // TODO Auto-generatedmethod stub

              i=login(username,password);

              System.out.println(i);

              F=1;

           }

           };

       

           new Thread(t).start();

          

           //等待服务器传来的结果

          

           while (F!=1) {

             

             

           }

           System.out.println(" i= "+i);

             

           //结果判定

          

              if(i.equals("1")){

                 System.out.println("-1-");

                 Toast.makeText(getApplicationContext(), "登录成功!",

                  Toast.LENGTH_SHORT).show();

                

                 userInfo(username, password, "1");

                

                 Intent intent=new Intent(this,Index.class);

                  Bundlebundle=new Bundle();

                      //传递name参数为tinyphp

                     bundle.putString("username", username);

                     intent.putExtras(bundle);

                     startActivity(intent);

                

                

              }else{

                 System.out.println("-0-");

                 Toast.makeText(getApplicationContext(), "账号或密码错误!",

                  Toast.LENGTH_SHORT).show();

                

              }

             

             

              System.out.println("---");

        

      }

       

    }

  

   //登录信息保存

  

   publicvoid userInfo(String username,String password,String flag){

      SharedPreferences sharedPreferences = getSharedPreferences("user", Context.MODE_PRIVATE);

      Editor editor = sharedPreferences.edit();//获取编辑器

      editor.putString("username", username);

      editor.putString("password", password);

      editor.putString("flag", flag);

      editor.commit();

   }

  

   //注册按钮

   publicvoid Btn2OnClick(View view){   

         

      Toast.makeText(getApplicationContext(), "欢迎新用户!",

             Toast.LENGTH_SHORT).show();

     

      Intent intent=new Intent(this,Regist.class);

          startActivity(intent);

    }

  

   //链接服务器

  

   private String login(String username,String password){

      //1  声明一些变量

      String flag="";

      URL url = null;

      HttpURLConnection conn=null;

      String requestBody="";//请求体

      String responseBody="";//响应体

     

      try {

        //url=newURL("http://10.0.2.2:8080/Chapter_13_Networking_server/servlet/LoginServlet");

        url = new URL("http://10.0.2.2:8080/QQ_Server/servlet/LoginServlet");

          

      } catch (MalformedURLException e) {

        // TODO Auto-generatedcatch block

        e.printStackTrace();

      }

      System.out.println("url=");

        //2 发送用户名和密码到服务器  post

      try{

      conn=(HttpURLConnection)url.openConnection();

       

      conn.setRequestMethod("POST");  //POST

      conn.setDoOutput(true);//设置请求体

       

      OutputStream os=conn.getOutputStream();

      System.out.println("username=");

      requestBody=new String("username="+username+"&password="+password);

      os.write(requestBody.getBytes("utf-8"));

      os.flush();

      os.close();

      }

      catch(Exception ex){

        ex.printStackTrace();

      }

      System.out.println("1");

      //5.接收数据

  try {

      InputStreamis=conn.getInputStream();

//      byte []buffer=new byte[1024];

//      while(in.available()!=0){

//         in.read(buffer);

//         responseBody=responseBody+buffer.toString();

//      }

//    //6  

//      String msg=new String(responseBody.getBytes("utf-8"));

//   

      byte  []temp  ;

     

     

       ByteArrayOutputStreamoutSteam = new ByteArrayOutputStream();

       System.out.println("1");

           byte[] buffer = newbyte[1024]; 

           int len = -1; 

           while ((len =is.read(buffer)) != -1) { 

              outSteam.write(buffer, 0, len); 

           } 

          outSteam.close(); 

           is.close(); 

           temp=outSteam.toByteArray();

     

     

     

        //获得响应头

        //responseHeader = getResponseHeader(conn);

       

       

        String msg = new String(temp,"UTF-8");

        

        System.out.println("---msg="+msg);

       

        flag=msg;

       

      } catch (IOException e) {

        // TODO Auto-generatedcatch block

        e.printStackTrace();

      }

  System.out.println("flag="+flag);

   return flag;

     

     

     

     

   }

  

  

  

   //返回键监听,返回桌面

   publicboolean onKeyDown(int keyCode, KeyEvent event) {

       if (keyCode ==KeyEvent.KEYCODE_BACK) {

           Intent home = new Intent(Intent.ACTION_MAIN);

          home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

          home.addCategory(Intent.CATEGORY_HOME);

           startActivity(home);

           returntrue;

       }

       returnsuper.onKeyDown(keyCode,event);

   }

  

  

  

}

Regist

publicclass Regist extends Activity{

   privatestaticintF = 0;

   EditText eText1,eText2;

   String username="",password="",i="";

  

   protectedvoid onCreate(Bundle savedInstanceState) {

      // TODO Auto-generatedmethod stub

      super.onCreate(savedInstanceState);

      requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

      setContentView(R.layout.activity_regist);

     

      //标题打开

      getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.regist_title);

     

      eText1=(EditText) findViewById(R.id.editText1);

      eText2=(EditText) findViewById(R.id.editText2);

     

   }

   //返回

   publicvoid BlackOnClick(View view){   

         

      Intent intent=new Intent(this,Login.class);

          startActivity(intent);

           Regist.this.finish();

    }

   //注册

   publicvoid RegistOnClick(View view){   

      

     

         username=eText1.getText().toString();

         password=eText2.getText().toString();

        

         if(username.length()==0||password.length()==0){

          

           Toast.makeText(getApplicationContext(),"账号密码不能为空!",

                Toast.LENGTH_SHORT).show();

          

         }else{

           Runnable t = new Runnable(){                 //线程

              @Override

              publicvoid run() {

              // TODO Auto-generatedmethod stub

                 i=regist(username,password);

                 System.out.println(i);

                 F=1;

              }

              };

          

              new Thread(t).start();

              //等待结果

              while (F!=1) {

                

                

              }

              System.out.println(" i= "+i);

                

                 if(i.equals("1")){

                    System.out.println("-1-");

                    Toast.makeText(getApplicationContext(), "注册成功!",

                     Toast.LENGTH_SHORT).show();

                   

                   

                   

                    Intent intent=new Intent(this,Login.class);

                        startActivity(intent);

                   

                   

                 }else{

                    System.out.println("-0-");

                    Toast.makeText(getApplicationContext(), "注册失败!",

                     Toast.LENGTH_SHORT).show();

                   

                 }

                

                

                 System.out.println("---");

           

         }

  

    }

  

   //注册服务器链接

   private String regist(String username,String password){

      //1  声明一些变量

      String flag="";

      URL url = null;

      HttpURLConnection conn=null;

      String requestBody="";//请求体

      String responseBody="";//响应体

     

      try {

        //url=new URL("http://10.0.2.2:8080/Chapter_13_Networking_server/servlet/LoginServlet");

        url = new URL("http://10.0.2.2:8080/QQ_Server/servlet/RegistServlet");

          

      } catch (MalformedURLException e) {

        // TODO Auto-generatedcatch block

        e.printStackTrace();

      }

      System.out.println("url=");

        //2 发送用户名和密码到服务器  post

      try{

      conn=(HttpURLConnection)url.openConnection();

       

      conn.setRequestMethod("POST");  //POST

      conn.setDoOutput(true);//设置请求体

       

      OutputStream os=conn.getOutputStream();

      System.out.println("username=");

      requestBody=new String("username="+username+"&password="+password);

      os.write(requestBody.getBytes("utf-8"));

      os.flush();

      os.close();

      }

      catch(Exception ex){

        ex.printStackTrace();

      }

      System.out.println("1");

      //5.接收数据

  try {

      InputStreamis=conn.getInputStream();

//      byte []buffer=new byte[1024];

//      while(in.available()!=0){

//         in.read(buffer);

//         responseBody=responseBody+buffer.toString();

//      }

//    //6  

//      String msg=new String(responseBody.getBytes("utf-8"));

//   

      byte  []temp  ;

     

     

       ByteArrayOutputStreamoutSteam = new ByteArrayOutputStream();

       System.out.println("1");

           byte[] buffer = newbyte[1024]; 

           int len = -1; 

           while ((len =is.read(buffer)) != -1) { 

              outSteam.write(buffer, 0, len); 

           } 

          outSteam.close(); 

           is.close(); 

           temp=outSteam.toByteArray();

     

     

     

        //获得响应头

        //responseHeader = getResponseHeader(conn);

       

       

        String msg = new String(temp,"UTF-8");

        

        System.out.println("---msg="+msg);

       

        flag=msg;

       

      } catch (IOException e) {

        // TODO Auto-generatedcatch block

        e.printStackTrace();

      }

  System.out.println("flag="+flag);

   return flag;

     

     

     

     

   }

  

   publicboolean onKeyDown(int keyCode, KeyEvent event) {

       if (keyCode ==KeyEvent.KEYCODE_BACK) {

           Intent home = new Intent(Intent.ACTION_MAIN);

          home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

          home.addCategory(Intent.CATEGORY_HOME);

           startActivity(home);

           returntrue;

       }

       returnsuper.onKeyDown(keyCode,event);

   }

}

Index.java

publicclass Index extends Activity{

  

   private List userInfos=new ArrayList();

   private ListAdapter adapter;

   private ListView mListView;

  

   EditText eText;

  

   protectedvoid onCreate(Bundle savedInstanceState) {

      // TODO Auto-generatedmethod stub

      super.onCreate(savedInstanceState);

      requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

      setContentView(R.layout.activity_index);

     

      //listview数据填充

     

      initView();

      //标题打开

      getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.index_title);

     

      //item点击方法

     

      mListView.setOnItemClickListener(new OnItemClickListener() {

        @Override

        publicvoid onItemClick(AdapterView parent, View view,

              int position, long id) {

           Intent intent=new Intent(Index.this,Chat.class);

            Bundle bundle=new Bundle();

                //传递name参数为tinyphp

               bundle.putString("chat",view.findViewById(R.id.name).toString());

               intent.putExtras(bundle);

               startActivity(intent);

          

        }

       

       

      }

           );

       

     

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

        //接收name值

        String username = bundle.getString("username");

       

        System.out.println(username);

       

       

      

       

       

  

   }

  

  

  

  

   privatevoid initView() {

      mListView = (ListView) findViewById(R.id.listView1);

      //新增數據

     

       

      UserInfo userInfo=new UserInfo(R.drawable.h1, "张辉", "在吗?");

      UserInfo userInfo1=new UserInfo(R.drawable.h2, "流浪", "附加费更痛苦");

      UserInfo userInfo2=new UserInfo(R.drawable.h3, "联想", "啊啊啊");

      UserInfo userInfo3=new UserInfo(R.drawable.h4, "作者", "ddd");

      UserInfo userInfo4=new UserInfo(R.drawable.h5, "0o搜索o0", "hello");

      UserInfo userInfo5=new UserInfo(R.drawable.h1, "书橱", "呜呜呜");

      userInfos.add(userInfo);

      userInfos.add(userInfo1);

      userInfos.add(userInfo2);

      userInfos.add(userInfo3);

      userInfos.add(userInfo4);

      userInfos.add(userInfo5);

     

     

      //初始化数据源

      adapter = new ListAdapter(this,userInfos);

      mListView.setAdapter(adapter);

     

     

      }

     

   //退出登录方法

  

   publicvoid LogoutOnClick(View view){   

         

     

      System.out.println(1);

      Context otherAppsContext;

      //清除登录数据

      try {

        otherAppsContext = createPackageContext("com.example.qq", Context.CONTEXT_IGNORE_SECURITY);

        SharedPreferences sharedPreferences =otherAppsContext.getSharedPreferences("user", Context.MODE_WORLD_READABLE);

        SharedPreferences.Editor editor = sharedPreferences.edit();

        editor.clear();

        editor.commit();

      } catch (NameNotFoundException e) {

        // TODO Auto-generatedcatch block

        e.printStackTrace();

      }

     

   System.out.println(2);

     

   Intent intent=new Intent(this,Login.class);

    startActivity(intent);

    Index.this.finish();

    }

  

  

  

  

   publicboolean onKeyDown(int keyCode, KeyEvent event) {

       if (keyCode ==KeyEvent.KEYCODE_BACK) {

           Intent home = new Intent(Intent.ACTION_MAIN);

          home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

          home.addCategory(Intent.CATEGORY_HOME);

           startActivity(home);

           returntrue;

       }

       returnsuper.onKeyDown(keyCode,event);

   }

}

Chat.java

publicclass Chat extends Activity implements OnClickListener,OnRefreshListenerHeader{

   private ViewPager mViewPager;

   private LinearLayout mDotsLayout;

   private MyEditText input;

   private Button send;

   private DropdownListView mListView;

   private ChatLVAdapter mLvAdapter;

  

   private LinearLayout chat_face_container;

   private ImageView image_face;//表情图标

   // 7列3行

   privateintcolumns = 6;

   privateintrows = 4;

   private List views = new ArrayList();

   private List staticFacesList;

   private LinkedList infos = new LinkedList();

   private SimpleDateFormat sd;

  

   private String reply="";//模拟回复

   @SuppressLint("SimpleDateFormat")

   privatevoid initViews() {

      mListView = (DropdownListView) findViewById(R.id.message_chat_listview);

      sd=new SimpleDateFormat("MM-ddHH:mm");

      //模拟收到信息

      infos.add(getChatInfoFrom("你好啊!"));

      infos.add(getChatInfoFrom("认识你很高兴#[face/png/f_static_018.png]#"));

      mLvAdapter = new ChatLVAdapter(this, infos);

      mListView.setAdapter(mLvAdapter);

      //表情图标

      image_face=(ImageView) findViewById(R.id.image_face);

      //表情布局

      chat_face_container=(LinearLayout) findViewById(R.id.chat_face_container);

      mViewPager = (ViewPager) findViewById(R.id.face_viewpager);

      mViewPager.setOnPageChangeListener(new PageChange());

      //表情下小圆点

      mDotsLayout = (LinearLayout) findViewById(R.id.face_dots_container);

      input = (MyEditText) findViewById(R.id.input_sms);

      input.setOnClickListener(this);

      send = (Button) findViewById(R.id.send_sms);

      InitViewPager();

      //表情按钮

      image_face.setOnClickListener(this);

      // 发送

      send.setOnClickListener(this);

     

      mListView.setOnRefreshListenerHead(this);

      mListView.setOnTouchListener(new OnTouchListener() {

        @Override

        publicboolean onTouch(View arg0, MotionEvent arg1) {

           if(arg1.getAction()==MotionEvent.ACTION_DOWN){

              if(chat_face_container.getVisibility()==View.VISIBLE){

                 chat_face_container.setVisibility(View.GONE);

              }

           }

           returnfalse;

        }

      });

   }

  

   @Override

   publicvoid onClick(View arg0) {

      switch (arg0.getId()) {

      case R.id.input_sms://输入框

        if(chat_face_container.getVisibility()==View.VISIBLE){

           chat_face_container.setVisibility(View.GONE);

        }

        break;

      case R.id.image_face://表情

        hideSoftInputView();//隐藏软键盘

        if(chat_face_container.getVisibility()==View.GONE){

           chat_face_container.setVisibility(View.VISIBLE);

        }else{

           chat_face_container.setVisibility(View.GONE);

        }

        break;

      case R.id.send_sms://发送

        reply=input.getText().toString();

        if (!TextUtils.isEmpty(reply)) {

           infos.add(getChatInfoTo(reply));

           mLvAdapter.setList(infos);

           mLvAdapter.notifyDataSetChanged();

           mListView.setSelection(infos.size() - 1);

           new Handler().postDelayed(new Runnable() {

              @Override

              publicvoid run() {

                 infos.add(getChatInfoFrom(reply));

                 mLvAdapter.setList(infos);

                 mLvAdapter.notifyDataSetChanged();

                 mListView.setSelection(infos.size() - 1);

              }

           }, 1000);

           input.setText("");

        }

        break;

      default:

        break;

      }

   }

   /*

    * 初始表情 *

    */

   privatevoid InitViewPager() {

      // 获取页数

      for (int i = 0; i < getPagerCount(); i++) {

        views.add(viewPagerItem(i));

        LayoutParams params = new LayoutParams(16, 16);

        mDotsLayout.addView(dotsItem(i), params);

      }

      FaceVPAdapter mVpAdapter = new FaceVPAdapter(views);

      mViewPager.setAdapter(mVpAdapter);

      mDotsLayout.getChildAt(0).setSelected(true);

   }

   private View viewPagerItem(int position) {

      LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

      View layout = inflater.inflate(R.layout.face_gridview, null);//表情布局

      GridView gridview = (GridView) layout.findViewById(R.id.chart_face_gv);

      /**

       * 注:因为每一页末尾都有一个删除图标,所以每一页的实际表情columns *rows - 1; 空出最后一个位置给删除图标

       * */

      List subList = new ArrayList();

      subList.addAll(staticFacesList

           .subList(position * (columns * rows - 1),

                 (columns * rows - 1) * (position + 1) > staticFacesList

                      .size() ? staticFacesList.size() : (columns

                      * rows - 1)

                      * (position + 1)));

      /**

       * 末尾添加删除图标

       * */

      subList.add("emotion_del_normal.png");

      FaceGVAdapter mGvAdapter = new FaceGVAdapter(subList, this);

      gridview.setAdapter(mGvAdapter);

      gridview.setNumColumns(columns);

      // 单击表情执行的操作

      gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override

        publicvoid onItemClick(AdapterView parent, View view,int position, long id) {

           try {

              String png = ((TextView) ((LinearLayout) view).getChildAt(1)).getText().toString();

              if (!png.contains("emotion_del_normal")) {// 如果不是删除图标

                 insert(getFace(png));

              } else {

                 delete();

              }

           } catch (Exception e) {

              e.printStackTrace();

           }

        }

      });

     

      return gridview;

   }

   private SpannableStringBuilder getFace(String png) {

      SpannableStringBuilder sb = new SpannableStringBuilder();

      try {

        /**

         * 经过测试,虽然这里tempText被替换为png显示,但是但我单击发送按钮时,获取到輸入框的内容是tempText的值而不是png

         * 所以这里对这个tempText值做特殊处理

         * 格式:#[face/png/f_static_000.png]#,以方便判斷當前圖片是哪一個

         * */

        String tempText = "#[" + png + "]#";

        sb.append(tempText);

        sb.setSpan(

              new ImageSpan(Chat.this, BitmapFactory

                    .decodeStream(getAssets().open(png))),sb.length()

                    - tempText.length(), sb.length(),

              Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

      } catch (Exception e) {

        e.printStackTrace();

      }

      return sb;

   }

   /**

    * 向输入框里添加表情

    * */

   privatevoid insert(CharSequence text) {

      int iCursorStart = Selection.getSelectionStart((input.getText()));

      int iCursorEnd = Selection.getSelectionEnd((input.getText()));

      if (iCursorStart != iCursorEnd) {

        ((Editable) input.getText()).replace(iCursorStart, iCursorEnd, "");

      }

      int iCursor = Selection.getSelectionEnd((input.getText()));

      ((Editable) input.getText()).insert(iCursor, text);

   }

   /**

    * 删除图标执行事件

    * 注:如果删除的是表情,在删除时实际删除的是tempText即图片占位的字符串,所以必需一次性删除掉tempText,才能将图片删除

    * */

   privatevoid delete() {

      if (input.getText().length() != 0) {

        int iCursorEnd = Selection.getSelectionEnd(input.getText());

        int iCursorStart = Selection.getSelectionStart(input.getText());

        if (iCursorEnd > 0) {

           if (iCursorEnd == iCursorStart) {

              if (isDeletePng(iCursorEnd)) {

                 String st = "#[face/png/f_static_000.png]#";

                 ((Editable) input.getText()).delete(

                      iCursorEnd - st.length(), iCursorEnd);

              } else {

                 ((Editable) input.getText()).delete(iCursorEnd - 1,

                      iCursorEnd);

              }

           } else {

              ((Editable) input.getText()).delete(iCursorStart,

                    iCursorEnd);

           }

        }

      }

   }

   /**

    * 判断即将删除的字符串是否是图片占位字符串tempText 如果是:则讲删除整个tempText

    * **/

   privateboolean isDeletePng(int cursor) {

      String st = "#[face/png/f_static_000.png]#";

      String content = input.getText().toString().substring(0, cursor);

      if (content.length() >= st.length()) {

        String checkStr = content.substring(content.length() -st.length(),

              content.length());

        String regex = "(\\#\\[face/png/f_static_)\\d{3}(.png\\]\\#)";

        Pattern p = Pattern.compile(regex);

        Matcher m = p.matcher(checkStr);

        return m.matches();

      }

      returnfalse;

   }

   private ImageView dotsItem(int position) {

      LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

      View layout = inflater.inflate(R.layout.dot_image, null);

      ImageView iv = (ImageView) layout.findViewById(R.id.face_dot);

      iv.setId(position);

      return iv;

   }

   /**

    * 根据表情数量以及GridView设置的行数和列数计算Pager数量

    * @return

    */

   privateint getPagerCount() {

      int count = staticFacesList.size();

      return count % (columns * rows - 1) == 0 ? count / (columns * rows - 1)

           : count / (columns * rows - 1) + 1;

   }

   /**

    * 初始化表情列表staticFacesList

    */

   privatevoid initStaticFaces() {

      try {

        staticFacesList = new ArrayList();

        String[] faces = getAssets().list("face/png");

        //将Assets中的表情名称转为字符串一一添加进staticFacesList

        for (int i = 0; i < faces.length; i++) {

           staticFacesList.add(faces[i]);

        }

        //去掉删除图片

        staticFacesList.remove("emotion_del_normal.png");

      } catch (Exception e) {

        e.printStackTrace();

      }

   }

   /**

    * 表情页改变时,dots效果也要跟着改变

    * */

   class PageChange implements OnPageChangeListener {

      @Override

      publicvoid onPageScrollStateChanged(int arg0) {

      }

      @Override

      publicvoid onPageScrolled(int arg0, float arg1, int arg2) {

      }

      @Override

      publicvoid onPageSelected(int arg0) {

        for (int i = 0; i < mDotsLayout.getChildCount(); i++) {

           mDotsLayout.getChildAt(i).setSelected(false);

        }

        mDotsLayout.getChildAt(arg0).setSelected(true);

      }

   }

   /**

    * 发送的信息

    * @param message

    * @return

    */

   private ChatInfo getChatInfoTo(String message) {

      ChatInfo info = new ChatInfo();

      info.content = message;

      info.fromOrTo = 1;

      info.time=sd.format(new Date());

      return info;

   }

  

   /**

    * 接收的信息

    * @param message

    * @return

    */

   private ChatInfo getChatInfoFrom(String message) {

      ChatInfo info = new ChatInfo();

      info.content = message;

      info.fromOrTo = 0;

      info.time=sd.format(new Date());

      return info;

   }

  

   @SuppressLint("HandlerLeak")

   private Handler mHandler = new Handler() {

      @Override

      publicvoid handleMessage(Message msg) {

        switch (msg.what) {

        case 0:

           mLvAdapter.setList(infos);

           mLvAdapter.notifyDataSetChanged();

           mListView.onRefreshCompleteHeader();

           break;

        }

      }

   };

   @Override

   protectedvoid onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);

      setContentView(R.layout.chat_main);

      initStaticFaces();

      initViews();

   }

   @Override

   publicvoid onRefresh() {

      new Thread() {

        @Override

        publicvoid run() {

           try {

              sleep(1000);

              Message msg = mHandler.obtainMessage(0);

              mHandler.sendMessage(msg);

           } catch (InterruptedException e) {

              e.printStackTrace();

           }

        }

      }.start();

   }

  

   publicvoid hideSoftInputView() {

      InputMethodManager manager = ((InputMethodManager) this.getSystemService(Activity.INPUT_METHOD_SERVICE));

      if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {

        if (getCurrentFocus() != null)

           manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);

      }

   }

}

你可能感兴趣的:(安卓,Android,android,课程设计)