Android仿新浪微博发布微博界面设计(5)

Android仿新浪微博发布微博界面设计(5),第1张

概述本教程为大家分享了Android发布微博、添加表情等功能的具体代码,供大家参考,具体内容如下

本教程为大家分享了AndroID发布微博、添加表情等功能的具体代码,供大家参考,具体内容如下

发布一条新微博接口:http://open.weibo.com/wiki/2/statuses/update
上传图片并发布一条新微博接口:http://open.weibo.com/wiki/2/statuses/upload

1.根据有没有图片来选择相应的接口。
2.根据输入框的改变判断文字数。
3.创建一个girlvIEw显示发送的图片,最最多9张,此处由于请求参数的的原因,最多上传一张图片,选择多张图片时,上传最后一张图片。(官方Demo与网络多个Demo均只能上传一张图片。如有看官解决多图上传,请务必联系我!)
4.显示表情的实现:用正则表达式遍历文字内容,代获取与表情相符的内容后, 用SpannableString将对于的表情图片显示在TextVIEw中。
5.表情面板的实现:创建显示表情的GrIDVIEw,将表情分组放入其中,监听GrIDVIEw点击事件,将表情显示输入到EditText中。具体表情功能的实现请参考:https://www.oudahe.com/p/27351/
5.最终发送的文字,表情,图片数量,根据按钮触发时各个参数的状态而决定。
6.删除选中的图片,获取其位置使用imageItem.remove(position)再将其在ArrayList移除。

public class WriteActivity extends Activity implements AdapterVIEw.OnItemClickListener { private button onput,addExpression; private EditText write; private GrIDVIEw grIDVIEw; private TextVIEw total_text_num = null; private linearLayout ll_emotion_dashboard; private VIEwPager vp_emotion_dashboard; // 发送图片的路径 private String image_path; private Bitmap bmp; private ArrayList<String> imagepaths; private ArrayList<HashMap<String,Object>> imageItem; private SimpleAdapter simpleAdapter; //适配器 private Tools tools; private EmotionPagerAdapter emotionPagerGvAdapter; @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.write); imagepaths = new ArrayList<>(); write = (EditText) findVIEwByID(R.ID.write); total_text_num = (TextVIEw) findVIEwByID(R.ID.total_text_num); onput = (button) findVIEwByID(R.ID.onput); addExpression = (button) findVIEwByID(R.ID.addExpression); ll_emotion_dashboard = (linearLayout) findVIEwByID(R.ID.ll_emotion_dashboard); vp_emotion_dashboard = (VIEwPager) findVIEwByID(R.ID.vp_emotion_dashboard); /**  * 注册输入框内容监听器  */ write.addTextChangedListener(new TextWatcher() {  @OverrIDe  public voID beforeTextChanged(CharSequence s,int start,int count,int after) {  }  /**  * 当输入框的内容变化的时候执行  */  @OverrIDe  public voID onTextChanged(CharSequence s,int before,int count) {  boolean flag = false;  String mText = write.getText().toString();  int len = mText.length();  if (len > 140) {   total_text_num.setTextcolor(color.RED);  } else {   total_text_num.setTextcolor(color.GREEN);  }  total_text_num.setText(String.valueOf(140 - len));  }  @OverrIDe  public voID afterTextChanged(Editable s) {  } }); grIDVIEw = (GrIDVIEw) findVIEwByID(R.ID.images); bmp = BitmapFactory.decodeResource(getResources(),R.drawable.add); imageItem = new ArrayList<HashMap<String,Object>>(); HashMap<String,Object> map = new HashMap<String,Object>(); map.put("itemImage",bmp); imageItem.add(map); simpleAdapter = new SimpleAdapter(this,imageItem,R.layout.grIDitem_addpic,new String[]{"itemImage"},new int[]{R.ID.imageVIEw}); simpleAdapter.setVIEwBinder(new SimpleAdapter.VIEwBinder() {  @OverrIDe  public boolean setVIEwValue(VIEw vIEw,Object data,String textRepresentation) {  if (vIEw instanceof ImageVIEw && data instanceof Bitmap) {   ImageVIEw i = (ImageVIEw) vIEw;   i.setimageBitmap((Bitmap) data);   return true;  }  return false;  } }); grIDVIEw.setAdapter(simpleAdapter); /**  * 监听GrIDVIEw点击事件  */ grIDVIEw.setonItemClickListener(new AdapterVIEw.OnItemClickListener() {  @OverrIDe  public voID onItemClick(AdapterVIEw<?> parent,VIEw v,int position,long ID) {  if (imageItem.size() == 10) { //第一张为默认图片   Toast.makeText(WriteActivity.this,"图片数9张已满",Toast.LENGTH_SHORT).show();  } else if (position == 0) { //点击图片位置为+ 0对应0张图片   //选择图片   Intent intent = new Intent(Intent.ACTION_PICK,androID.provIDer.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);   startActivityForResult(intent,1);   //通过onResume()刷新数据  } else {   dialog(position);  }  } }); /**  * 监听发表按钮点击事件  */ tools = Tools.getInstance(); onput.setonClickListener(new VIEw.OnClickListener() {  @OverrIDe  public voID onClick(VIEw v) {  //对文字进行处理  String mText = write.getText().toString();  int len = mText.length();  if (len == 0) {   Toast.makeText(WriteActivity.this,"内容不能为空!",Toast.LENGTH_SHORT).show();  } else if (len > 140) {   Toast.makeText(WriteActivity.this,"超出字数限制!",Toast.LENGTH_SHORT).show();  } else {   if (imagepaths.size() > 0) {   tools.postwhitTextandImages(WriteActivity.this,mText,imagepaths);   //进入微博主界面   Intent intent = new Intent(WriteActivity.this,MainActivity.class);   startActivity(intent);   WriteActivity.this.finish();   } else {   tools.postwhitText(WriteActivity.this,mText);   //进入微博主界面   Intent intent = new Intent(WriteActivity.this,MainActivity.class);   startActivity(intent);   WriteActivity.this.finish();   }  }  } }); /**  * 表情按钮及功能  */ addExpression.setonClickListener(new VIEw.OnClickListener() {  @OverrIDe  public voID onClick(VIEw v) {  // 隐藏或显示表情面板  ll_emotion_dashboard.setVisibility(   ll_emotion_dashboard.getVisibility() == VIEw.VISIBLE ?    VIEw.GONE : VIEw.VISIBLE);  } }); initEmotion(); } //获取图片路径 响应startActivityForResult protected voID onActivityResult(int requestCode,int resultCode,Intent data) { super.onActivityResult(requestCode,resultCode,data); //打开图片 if (resultCode == RESulT_OK && requestCode == 1) {  Uri uri = data.getData();  if (!TextUtils.isEmpty(uri.getAuthority())) {  //查询选择图片  Cursor cursor = getContentResolver().query(   uri,new String[]{MediaStore.Images.Media.DATA},null,null);  //返回 没找到选择图片  if (null == cursor) {   return;  }  //光标移动至开头 获取图片路径  cursor.movetoFirst();  image_path = cursor.getString(cursor   .getColumnIndex(MediaStore.Images.Media.DATA));  } } //end if 打开图片 } //刷新图片 @OverrIDe protected voID onResume() { super.onResume(); if (!TextUtils.isEmpty(image_path)) {  Bitmap addbmp = BitmapFactory.decodefile(image_path);  HashMap<String,Object>();  map.put("itemImage",addbmp);  imageItem.add(map);  simpleAdapter = new SimpleAdapter(this,new int[]{R.ID.imageVIEw});  simpleAdapter.setVIEwBinder(new SimpleAdapter.VIEwBinder() {  @OverrIDe  public boolean setVIEwValue(VIEw vIEw,String textRepresentation) {   if (vIEw instanceof ImageVIEw && data instanceof Bitmap) {   ImageVIEw i = (ImageVIEw) vIEw;   i.setimageBitmap((Bitmap) data);   return true;   }   return false;  }  });  grIDVIEw.setAdapter(simpleAdapter);  simpleAdapter.notifyDataSetChanged();  imagepaths.add(image_path);  //刷新后释放防止手机休眠后自动添加  image_path = null; } } /** * Dialog对话框提示用户删除 *** 作 * position为删除图片位置 */ protected voID dialog(final int position) { AlertDialog.Builder builder = new AlertDialog.Builder(WriteActivity.this); builder.setMessage("确认移除已添加图片吗?"); builder.setTitle("提示"); builder.setPositivebutton("确认",new DialogInterface.OnClickListener() {  @OverrIDe  public voID onClick(DialogInterface dialog,int which) {  dialog.dismiss();  imageItem.remove(position);  imagepaths.remove(position - 1);  simpleAdapter.notifyDataSetChanged();  } }); builder.setNegativebutton("取消",int which) {  dialog.dismiss();  } }); builder.create().show(); } /** * 初始化表情面板内容 */ private voID initEmotion() { // 获取屏幕宽度 int gvWIDth = displayUtils.getScreenWIDthPixels(this); // 表情边距 int spacing = displayUtils.dp2px(this,8); // GrIDVIEw中item的宽度 int itemWIDth = (gvWIDth - spacing * 8) / 7; int gvHeight = itemWIDth * 3 + spacing * 4; List<GrIDVIEw> gvs = new ArrayList<GrIDVIEw>(); List<String> emotionnames = new ArrayList<String>(); // 遍历所有的表情名字 for (String emojiname : EmotionUtils.emojiMap.keySet()) {  emotionnames.add(emojiname);  // 每20个表情作为一组,同时添加到VIEwPager对应的vIEw集合中  if (emotionnames.size() == 20) {  GrIDVIEw gv = createEmotionGrIDVIEw(emotionnames,gvWIDth,spacing,itemWIDth,gvHeight);  gvs.add(gv);  // 添加完一组表情,重新创建一个表情名字集合  emotionnames = new ArrayList<String>();  } } // 检查最后是否有不足20个表情的剩余情况 if (emotionnames.size() > 0) {  GrIDVIEw gv = createEmotionGrIDVIEw(emotionnames,gvHeight);  gvs.add(gv); } // 将多个GrIDVIEw添加显示到VIEwPager中 emotionPagerGvAdapter = new EmotionPagerAdapter(gvs); vp_emotion_dashboard.setAdapter(emotionPagerGvAdapter); linearLayout.LayoutParams params = new linearLayout.LayoutParams(gvWIDth,gvHeight); vp_emotion_dashboard.setLayoutParams(params); } /** * 创建显示表情的GrIDVIEw */ private GrIDVIEw createEmotionGrIDVIEw(List<String> emotionnames,int gvWIDth,int padding,int itemWIDth,int gvHeight) { // 创建GrIDVIEw GrIDVIEw gv = new GrIDVIEw(this); gv.setBackgroundcolor(color.rgb(233,233,233)); gv.setSelector(androID.R.color.transparent); gv.setNumColumns(7); gv.setpadding(padding,padding,padding); gv.setHorizontalSpacing(padding); gv.setVerticalSpacing(padding); LayoutParams params = new LayoutParams(gvWIDth,gvHeight); gv.setLayoutParams(params); // 给GrIDVIEw设置表情图片 EmotionGvAdapter adapter = new EmotionGvAdapter(this,emotionnames,itemWIDth); gv.setAdapter(adapter); gv.setonItemClickListener(this); return gv; } @OverrIDe public voID onItemClick(AdapterVIEw<?> parent,VIEw vIEw,long ID) { Object itemAdapter = parent.getAdapter(); if (itemAdapter instanceof EmotionGvAdapter) {  // 点击的是表情  EmotionGvAdapter emotionGvAdapter = (EmotionGvAdapter) itemAdapter;  if (position == emotionGvAdapter.getCount() - 1) {  // 如果点击了最后一个回退按钮,则调用删除键事件  write.dispatchKeyEvent(new KeyEvent(   KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_DEL));  } else {  // 如果点击了表情,则添加到输入框中  String emotionname = emotionGvAdapter.getItem(position);  // 获取当前光标位置,在指定位置上添加表情图片文本  int curposition = write.getSelectionStart();  StringBuilder sb = new StringBuilder(write.getText().toString());  sb.insert(curposition,emotionname);  // 特殊文字处理,将表情等转换一下  write.setText(StringUtils.getEmotionContent(   this,write,sb.toString()));  // 将光标设置到新增完表情的右侧  write.setSelection(curposition + emotionname.length());  } } }}

发布微博的方法位于Tools.java中。由于上传的数据采用multipart/form-data编码方式,此处引入第三方httptmime.jar包对请求参数进行处理。

 /** * 发布一条不含图片的微博 * * @param context * @param text */ public voID postwhitText(final Context context,final String text) { if (oAuth == null) {  oAuth = oAuth.getoAuth(context); } new Thread() {  @OverrIDe  public voID run() {  try {   httpPost post = new httpPost("https://API.weibo.com/2/statuses/update" +    ".Json");   List<nameValuePair> params = new ArrayList<nameValuePair>();   params.add(new BasicnameValuePair("access_token",oAuth.getAccesstoken()));   params.add(new BasicnameValuePair("status",text));   post.setEntity(new UrlEncodedFormEntity(params,http.UTF_8));   httpResponse response = httpClIEnt.execute(post);   if (response.getStatusline().getStatusCode() == 200) {   Looper.prepare();   Toast.makeText(context,"发表成功",Toast.LENGTH_SHORT).show();   Looper.loop();   } else {   Looper.prepare();   Toast.makeText(context,"发表失败",Toast.LENGTH_SHORT).show();   Looper.loop();   }  } catch (UnsupportedEnCodingException e) {   e.printstacktrace();  } catch (ClIEntProtocolException e) {   e.printstacktrace();  } catch (IOException e) {   e.printstacktrace();  }  } }.start(); } /** * 发布一条带图片的微博 * * @param context * @param */ public voID postwhitTextandImages(final Context context,final String text,final List<String> filesPath) { new Thread() {  @OverrIDe  public voID run() {  try {   //httpClIEnt对象   httpClIEnt httpClIEnt = new DefaulthttpClIEnt();   //采用POST的请求方式   httpPost httpPost = new httpPost("https://upload.API.weibo" +    ".com/2/statuses/upload.Json");   //multipartentity对象,需要httpmime-4.1.1.jar文件。   multipartentity multipartentity = new multipartentity();   //StringBody对象,参数   StringBody param = new StringBody(oAuth.getAccesstoken());   multipartentity.addPart("access_token",param);   StringBody param1 = new StringBody(URLEncoder.encode(text));   multipartentity.addPart("status",param1);   //filesPath为List<String>对象,里面存放的是需要上传的文件的地址   for (String path : filesPath) {   Log.i("------------",path);   //fileBody对象,需要上传的文件   Contentbody file = new fileBody(new file(path));   multipartentity.addPart("pic",file);   }   //将multipartentity对象赋值给httpPost   httpPost.setEntity(multipartentity);   httpResponse response = null;   //执行请求,并返回结果httpResponse   response = httpClIEnt.execute(httpPost);   if (response.getStatusline().getStatusCode() == 200) {   Looper.prepare();   Toast.makeText(context,Toast.LENGTH_SHORT).show();   Looper.loop();   }  } catch (ClIEntProtocolException e) {   e.printstacktrace();  } catch (IOException e) {   e.printstacktrace();  }  } }.start(); }

效果图:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。

总结

以上是内存溢出为你收集整理的Android仿新浪微博发布微博界面设计(5)全部内容,希望文章能够帮你解决Android仿新浪微博发布微博界面设计(5)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1147693.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存