Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android仿新浪微博發布微博界面設計(5)

Android仿新浪微博發布微博界面設計(5)

編輯:關於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中。具體表情功能的實現請參考:http://www.jb51.net/article/97862.htm
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 start, 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,
   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 = new HashMap<String, Object>();
  map.put("itemImage", addbmp);
  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);
  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("取消", new DialogInterface.OnClickListener() {
  @Override
  public void onClick(DialogInterface dialog, 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, gvWidth, spacing, itemWidth, 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, 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, int position, 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();
   } else {
   Looper.prepare();
   Toast.makeText(context, "發表失敗", Toast.LENGTH_SHORT).show();
   Looper.loop();
   }
  } catch (ClientProtocolException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  }
 }.start();
 }

效果圖:

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持本站。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved