code
stringlengths
3
1.18M
language
stringclasses
1 value
package com.outsourcing.bottle.ui; import java.util.HashMap; import oauth.facebook.AsyncFacebookRunner; import oauth.facebook.BaseRequestListener; import oauth.facebook.DialogError; import oauth.facebook.Facebook; import oauth.facebook.Facebook.DialogListener; import oauth.facebook.FacebookError; import oauth.facebook.SessionEvents; import oauth.facebook.SessionEvents.AuthListener; import oauth.facebook.Util; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.os.Handler; import android.os.Handler.Callback; import android.os.Message; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import com.outsourcing.bottle.BasicActivity; import com.outsourcing.bottle.R; import com.outsourcing.bottle.db.OtherConfigTable; import com.outsourcing.bottle.db.PlatformAccountTable; import com.outsourcing.bottle.domain.OtherConfigEntry; import com.outsourcing.bottle.domain.PlatformAccount; import com.outsourcing.bottle.domain.PlatformBindConfig; import com.outsourcing.bottle.domain.UrlConfig; import com.outsourcing.bottle.oauth.OAuth; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.HttpUtils; import com.outsourcing.bottle.util.UICore; /** * * @author 06peng * */ public class LoginPlatformActivity extends BasicActivity implements OnClickListener, Callback { private Button twitter; private Button facebook; private Button weibo; private Button tentcent; private Button qq; private Button renren; private Button douban; private Button registerBtn; private ImageView close; private String platform; public OAuth oauth; public static final String CALLBACKURL = "app:authorize"; public static final int HAS_BIND = 1; public static final int NOT_BIND = 2; private OtherConfigEntry entry; private final int oauth_tritter =28; private final int oauth_facebook = 29; private final int oauth_weibo = 30; private final int oauth_tencent = 31; private final int oauth_renren = 32; private final int oauth_douban = 33; private final int oauth_qq = 34; private Facebook mFacebook; private AsyncFacebookRunner mAsyncRunner; private SessionListener mSessionListener = new SessionListener(); private int regsiterEnable; private Handler handler; @Override protected void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); handler = new Handler(this); setContentView(R.layout.login_platform); try { initWidget(); OtherConfigTable ot = new OtherConfigTable(); entry = ot.getBottleOtherConfig(); regsiterEnable = entry.getRegister_enable(); if (regsiterEnable == 1) { registerBtn.setVisibility(View.VISIBLE); } else { registerBtn.setVisibility(View.GONE); } } catch (Exception e) { e.printStackTrace(); } } private void initWidget() { twitter = (Button) findViewById(R.id.login_twitter); twitter.setOnClickListener(this); facebook = (Button) findViewById(R.id.login_facebook); facebook.setOnClickListener(this); weibo = (Button) findViewById(R.id.login_weibo); weibo.setOnClickListener(this); tentcent = (Button) findViewById(R.id.login_tqq); tentcent.setOnClickListener(this); qq = (Button) findViewById(R.id.login_qq); qq.setOnClickListener(this); renren = (Button) findViewById(R.id.login_renren); renren.setOnClickListener(this); douban = (Button) findViewById(R.id.login_douban); douban.setOnClickListener(this); close = (ImageView) findViewById(R.id.close); close.setOnClickListener(this); registerBtn = (Button) findViewById(R.id.login_register); registerBtn.setOnClickListener(this); } @Override public void onClick(View v) { if (v == twitter) { if (entry.getTwitter_enable() == 0) { onToast(getString(R.string.platform_error)); return; } UICore.eventTask(this, this, oauth_tritter, "", null); } else if (v == facebook) { if (entry.getFacebook_enable() == 0) { onToast(getString(R.string.platform_error)); return; } platform = PlatformBindConfig.Facebook; mFacebook = new Facebook(PlatformBindConfig.Facebook_AppID); mAsyncRunner = new AsyncFacebookRunner(mFacebook); SessionEvents.addAuthListener(new SampleAuthListener()); SessionEvents.addAuthListener(mSessionListener); mFacebook.authorize((BasicActivity) AppContext.getContext(), new String[] {}, new LoginDialogListener()); } else if (v == weibo) { if (entry.getWeibo_enable() == 0) { onToast(getString(R.string.platform_error)); return; } UICore.eventTask(this, this, oauth_weibo, "", null); } else if (v == tentcent) { if (entry.getTencent_enable() == 0) { onToast(getString(R.string.platform_error)); return; } UICore.eventTask(this, this, oauth_tencent, "", null); } else if (v == qq) { if (entry.getQq_enable() == 0) { onToast(getString(R.string.platform_error)); return; } UICore.eventTask(this, this, oauth_qq, "", null); } else if (v == renren) { if (entry.getRenren_enable() == 0) { onToast(getString(R.string.platform_error)); return; } UICore.eventTask(this, this, oauth_renren, "", null); } else if (v == douban) { if (entry.getDouban_enable() == 0) { onToast(getString(R.string.platform_error)); return; } UICore.eventTask(this, this, oauth_douban, "", null); } else if (v == close) { finish(); } else if (v == registerBtn) { Intent register = new Intent(LoginPlatformActivity.this, BindRegisterActivity.class); startActivity(register); LoginPlatformActivity.this.finish(); } } @Override protected void onDestroy() { super.onDestroy(); if (OAuth.reciver != null) { unregisterReceiver(OAuth.reciver); } } @Override public void execute(int mes, Object obj) { switch (mes) { case oauth_douban: platform = PlatformBindConfig.Douban; oauth = new OAuth(this, handler, platform, PlatformBindConfig.Douban_AppKey, PlatformBindConfig.Douban_AppSecret); oauth.requestAccessToken(CALLBACKURL, PlatformBindConfig.Douban_Request_Token, PlatformBindConfig.Douban_Access_Token, PlatformBindConfig.Douban_Authorize); break; case oauth_facebook: PlatformAccount account = (PlatformAccount) obj; checkBind(account); break; case oauth_qq: platform = PlatformBindConfig.QQ; oauth = new OAuth(this, handler, platform); oauth.requestAccessTokenForOAuth2(PlatformBindConfig.QQ_Authorize); break; case oauth_renren: platform = PlatformBindConfig.Renren; oauth = new OAuth(this, handler, platform); oauth.requestAccessTokenForOAuth2(PlatformBindConfig.Renren_Authorize); break; case oauth_tencent: platform = PlatformBindConfig.Tencent; oauth = new OAuth(this, handler, platform); oauth.requestAccessTokenForOAuth2(PlatformBindConfig.Tencent_Authorize_2); break; case oauth_tritter: platform = PlatformBindConfig.Twitter; oauth = new OAuth(this, handler, PlatformBindConfig.Twitter, PlatformBindConfig.Twitter_ConsumerKey, PlatformBindConfig.Twitter_ConsumerSecret); oauth.requestAcccessTokenForTwitter(); break; case oauth_weibo: platform = PlatformBindConfig.Sina; oauth = new OAuth(this, handler, platform); oauth.requestAccessTokenForOAuth2(PlatformBindConfig.Sina_Authorize2); break; default: break; } } public class SampleAuthListener implements AuthListener { public void onAuthSucceed() { System.out.println("You have logged in! "); } public void onAuthFail(String error) { System.out.println("Login Failed: " + error); } } public class SampleRequestListener extends BaseRequestListener { public void onComplete(final String response, final Object state) { try { PlatformAccount account = new PlatformAccount(); Log.d("Facebook-Example", "Response: " + response.toString()); JSONObject json = Util.parseJson(response); account.setAccessToken(mFacebook.getAccessToken()); if (json.has("name")) { account.setNickName(json.getString("name")); } account.setOpenAvatar("https://graph.facebook.com/"+json.getString("id")+"/picture?type=large"); account.setOpenExpire(String.valueOf(mFacebook.getAccessExpires())); account.setOpenType(6); account.setOpenUid(json.getString("id")); PlatformAccountTable paTable = new PlatformAccountTable(); paTable.save(account); if (account.getOpenUid() != null && !account.getOpenUid().equals("")) { Message msg = Message.obtain(handler, oauth_facebook, account); handler.sendMessage(msg); } } catch (JSONException e) { e.printStackTrace(); Log.w("Facebook-Example", "JSON Error in response"); } catch (FacebookError e) { Log.w("Facebook-Example", "Facebook Error: " + e.getMessage()); } } } private final class LoginDialogListener implements DialogListener { public void onComplete(Bundle values) { SessionEvents.onLoginSuccess(); } public void onFacebookError(FacebookError error) { SessionEvents.onLoginError(error.getMessage()); } public void onError(DialogError error) { SessionEvents.onLoginError(error.getMessage()); } public void onCancel() { SessionEvents.onLoginError("Action Canceled"); } } private class SessionListener implements AuthListener { public void onAuthSucceed() { mAsyncRunner.request("me", new SampleRequestListener()); } public void onAuthFail(String error) { } } private void checkBind(PlatformAccount account) { String url = UrlConfig.check_bind; HashMap<String, String> paramsMap = new HashMap<String, String>(); paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid())); paramsMap.put("login_token", AppContext.getInstance().getLogin_token()); paramsMap.put("open_type", String.valueOf(account.getOpenType())); paramsMap.put("access_token", account.getAccessToken()); paramsMap.put("token_secret", account.getTokenSecret()); paramsMap.put("nickname", account.getNickName()); paramsMap.put("open_uid", account.getOpenUid()); paramsMap.put("open_sex", String.valueOf(account.getOpenSex())); paramsMap.put("open_expire", account.getOpenExpire()); paramsMap.put("open_avatar", account.getOpenAvatar()); paramsMap.put("device_token", AppContext.getInstance().getDeviceId()); try { String result = HttpUtils.doPost(this, url, paramsMap); JSONObject object = new JSONObject(result); if (object.has("results")) { final JSONObject resultObj = object.getJSONObject("results"); System.out.println(resultObj); int isbind = resultObj.getInt("isbind"); if (isbind == 0) { if (handler != null) { Message message = Message.obtain(handler, LoginPlatformActivity.NOT_BIND, account); handler.sendMessage(message); } } else { int login_uid = resultObj.getInt("login_uid"); String login_token = resultObj.getString("login_token"); SharedPreferences preferences = LoginPlatformActivity.this.getSharedPreferences("Preferences_userinfo", Activity.MODE_APPEND); Editor editor = preferences.edit(); editor.putInt("login_uid", login_uid); editor.putString("login_token", login_token); editor.commit(); AppContext.getInstance().setLogin_token(login_token); AppContext.getInstance().setLogin_uid(login_uid); if (handler != null) { handler.sendEmptyMessage(LoginPlatformActivity.HAS_BIND); } } } } catch (JSONException e) { e.printStackTrace(); } } @Override public boolean handleMessage(Message msg) { switch (msg.what) { case HAS_BIND: AppContext.getInstance().setOAUTH_TYPE(-1); Intent intent = new Intent(LoginPlatformActivity.this, HomeActivity.class); startActivity(intent); LoginPlatformActivity.this.finish(); break; case NOT_BIND: Intent register = new Intent(LoginPlatformActivity.this, BindRegisterActivity.class); register.putExtra("platform", platform); register.putExtra("openuid", msg.obj.toString()); startActivity(register); LoginPlatformActivity.this.finish(); break; case oauth_facebook: PlatformAccount account = (PlatformAccount) msg.obj; UICore.eventTask(LoginPlatformActivity.this, LoginPlatformActivity.this, oauth_facebook, "", account); break; case AppContext.oauth_bind: AppContext.getInstance().setOAUTH_TYPE(-1); Intent intent2 = new Intent(LoginPlatformActivity.this, HomeActivity.class); startActivity(intent2); LoginPlatformActivity.this.finish(); break; default: break; } destroyDialog(); return false; } }
Java
package com.outsourcing.bottle.ui; import java.util.HashMap; import java.util.List; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Handler.Callback; import android.os.Message; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.google.gson.Gson; import com.outsourcing.bottle.BasicActivity; import com.outsourcing.bottle.R; import com.outsourcing.bottle.domain.CityEntry; import com.outsourcing.bottle.domain.CityInfo; import com.outsourcing.bottle.domain.UrlConfig; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.BasicUIEvent; import com.outsourcing.bottle.util.HttpUtils; import com.outsourcing.bottle.util.UICore; /** * * @author 06peng * */ public class SearchCityActivity extends BasicActivity implements BasicUIEvent, Callback, OnClickListener { private final int search_city = 1; private final int error = 2; private Handler handler; private List<CityEntry> cityList; private ImageView backView; private TextView titleView; private EditText editView; private ImageView searchView; private ListView listView; private String title; private int resultCode; @Override protected void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); setContentView(R.layout.search_city); handler = new Handler(this); title = getIntent().getStringExtra("title"); resultCode = getIntent().getIntExtra("resultCode", 0); initWidget(); } private void initWidget() { backView = (ImageView) findViewById(R.id.topbar_back); backView.setOnClickListener(this); titleView = (TextView) findViewById(R.id.topbar_title); titleView.setText(title); editView = (EditText) findViewById(R.id.search_city_edit); editView.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) { UICore.eventTask(SearchCityActivity.this, SearchCityActivity.this, search_city, "search_city", null); } return false; } }); searchView = (ImageView) findViewById(R.id.search_city_go); searchView.setOnClickListener(this); listView = (ListView) findViewById(R.id.search_city_list); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { CityEntry entry = cityList.get(arg2); Intent intent = new Intent(SearchCityActivity.this, SettingBasicActivity.class); intent.putExtra("cityid", entry.getCityid()); intent.putExtra("city", entry.getCity()); intent.putExtra("province", entry.getProvince()); intent.putExtra("country", entry.getCountry()); setResult(resultCode, intent); finish(); } }); } @Override public void onClick(View v) { if (v == backView) { finish(); } else if (v == searchView) { UICore.eventTask(this, this, search_city, "search_city", null); } } @Override public void execute(int mes, Object obj) { switch (mes) { case search_city: searchCity(); break; default: break; } } @Override public boolean handleMessage(Message msg) { switch (msg.what) { case search_city: CityAdapter adapter = new CityAdapter(); listView.setAdapter(adapter); break; case error: onToast((String) msg.obj); break; default: break; } return false; } private void searchCity() { String url = UrlConfig.search_city; HashMap<String, String> paramsMap = new HashMap<String, String>(); paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid())); paramsMap.put("login_token", AppContext.getInstance().getLogin_token()); paramsMap.put("page", "1"); paramsMap.put("count", "20"); paramsMap.put("keyword", editView.getText().toString().trim()); try { String result = HttpUtils.doPost(this, url, paramsMap); if (result != null) { Gson gson = new Gson(); CityInfo info = gson.fromJson(result, CityInfo.class); if (info.getResults().getAuthok() == 0) { Message msg = Message.obtain(handler, error, info.getResults().getErrmsg()); handler.sendMessage(msg); } else { cityList = info.getCities_list(); handler.sendEmptyMessage(search_city); } } } catch (Exception e) { e.printStackTrace(); } } public class CityAdapter extends BaseAdapter { @Override public int getCount() { return cityList == null ? 0 : cityList.size(); } @Override public Object getItem(int arg0) { return cityList == null ? null : cityList.get(arg0); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.search_city_listitem, null); } TextView city = (TextView) convertView.findViewById(R.id.search_city_listitem_city); TextView province = (TextView) convertView.findViewById(R.id.search_city_listitem_province); TextView country = (TextView) convertView.findViewById(R.id.search_city_listitem_country); CityEntry entry = cityList.get(position); if (entry != null) { city.setText(entry.getCity()); province.setText(entry.getProvince()); country.setText(entry.getCountry()); } return convertView; } } }
Java
package com.outsourcing.bottle.ui; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; import android.content.Intent; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.os.Handler; import android.os.Handler.Callback; import android.os.Message; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.TextView; import com.outsourcing.bottle.BasicActivity; import com.outsourcing.bottle.R; import com.outsourcing.bottle.db.BottleNetTypeTable; import com.outsourcing.bottle.db.BottleTypeTable; import com.outsourcing.bottle.domain.BottleNetTypeEntry; import com.outsourcing.bottle.domain.BottleTypeEntry; import com.outsourcing.bottle.domain.UrlConfig; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.BasicUIEvent; import com.outsourcing.bottle.util.HttpUtils; import com.outsourcing.bottle.util.ImageLoader; import com.outsourcing.bottle.util.TextUtil; import com.outsourcing.bottle.util.UICore; /** * * @author 06peng * */ public class ChooseBottleActivity extends BasicActivity implements BasicUIEvent, Callback { private final int init_bottle_info = 1; private final int init_permission_error = 4; private final int net_choose_location = 2; private final int bttype_choose_location = 3; private final int init_location = 5; private final int gain_bottle_success = 6; private final int gain_bottle_error = 7; private final int gain_bottle = 8; private List<BottleTypeEntry> bottltTypes; private List<BottleNetTypeEntry> bottleNetTypes; private List<BottlePermission> permissions; private GridView gridView; private ImageView back; LinearLayout bottle_description; TextView bottle_desc; TextView bottle_provision; Button button; PopupWindow pop; private BottleTypeAdapter typeAdapter; private BottleNetTypeAdapter netAdapter; private String type; private int netLocationSelect; private int bttypeLocationSelect; private int bottleId; private Handler handler; private ImageLoader loader; @Override protected void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); handler = new Handler(this); setContentView(R.layout.choose_bottle); type = getIntent().getStringExtra("type"); loader = new ImageLoader(this, AppContext.BottleTimelineIcon); initWidget(); initPopuwindow(); //网络定位 networkLocat(); UICore.eventTask(this, this, init_bottle_info, getString(R.string.init_data), null); } private void initWidget() { if (type.equals("throw")) { ((TextView)findViewById(R.id.topbar_title)).setText(TextUtil.R("bottle_txt_title_throw")); } else { ((TextView)findViewById(R.id.topbar_title)).setText(TextUtil.R("bottle_txt_title_gain")); } gridView = (GridView) findViewById(R.id.choose_bottle_grid); back = (ImageView) findViewById(R.id.topbar_back); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ChooseBottleActivity.this.finish(); } }); gridView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> convertView, View view, int position, long id) { if (type.equals("throw")) { initBottleTypeDescription(position); } else { initBottleNetTypeDescription(position); } if (pop.isShowing()) { pop.dismiss(); } else { pop.showAtLocation(view, Gravity.CENTER, 0, 0); } } }); } private void initPopuwindow() { View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.choose_bottle_popuwindow, null); bottle_desc = (TextView) view.findViewById(R.id.choose_bottle_desc); bottle_provision = (TextView) view.findViewById(R.id.choose_bottle_provision); button = (Button) view.findViewById(R.id.choose_bottle_button); bottle_description = (LinearLayout) view.findViewById(R.id.choose_bottle_description); pop = new PopupWindow(view, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true); pop.setAnimationStyle(R.style.AnimationPreview); ColorDrawable dw = new ColorDrawable(-00000); pop.setBackgroundDrawable(dw); pop.update(); } private void initBottleNetTypeDescription(int position) { try { final BottleNetTypeEntry entry = bottleNetTypes.get(position); if (entry == null) { return; } bottleId = entry.getNettypeid(); netLocationSelect = entry.getNettype_location_select(); button.setText(ChooseBottleActivity.this.getString(R.string.choose_bchoose_try)); button.setBackgroundResource(R.drawable.btn_red_try); final BottlePermission permission = getPermission(entry.getNettypeid()); if (permission != null) { if (permission.enable == 0) { button.setBackgroundResource(R.drawable.btn_gray_try); } else { button.setBackgroundResource(R.drawable.btn_red_try); } } if (AppContext.language == 1) { bottle_desc.setText(entry.getNettype_desc_cn()); } else { bottle_desc.setText(entry.getNettype_desc_en()); } bottle_provision.setText(permission.useterm); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (permission != null) { if (permission.enable == 0) { onToast(permission.reason); return; } } pop.dismiss(); chooseLocationTab(net_choose_location, netLocationSelect); } }); } catch (Exception e) { e.printStackTrace(); } } private void initBottleTypeDescription(int position) { try { final BottleTypeEntry entry = bottltTypes.get(position); if (entry == null) { return; } bottleId = entry.getBttypeid(); bttypeLocationSelect = entry.getBttype_location_select(); button.setText(ChooseBottleActivity.this.getString(R.string.choose_bottle_throw)); button.setBackgroundResource(R.drawable.btn_blue_try); final BottlePermission permission = getPermission(entry.getBttypeid()); if (permission != null) { if (permission.enable == 0) { button.setBackgroundResource(R.drawable.btn_gray_try); } else { button.setBackgroundResource(R.drawable.btn_blue_try); } } if (AppContext.language == 1) { bottle_desc.setText(entry.getBttype_desc_cn()); } else { bottle_desc.setText(entry.getBttype_desc_en()); } bottle_provision.setText(permission.useterm); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (permission != null) { if (permission.enable == 0) { onToast(permission.reason); return; } } pop.dismiss(); chooseLocationTab(bttype_choose_location, bttypeLocationSelect); } }); } catch (Exception e) { e.printStackTrace(); } } private void chooseLocationTab(int locatoinType, int locationSelect) { try { if (locationSelect > 0) { String choices[] = new String[2]; if (locatoinType == net_choose_location) { choices[0] = getString(R.string.choose_location_here_try); choices[1] = getString(R.string.choose_location_search_try); } else { choices[0] = getString(R.string.choose_location_here_throw); choices[1] = getString(R.string.choose_location_search_throw); } chooseAction(choices, locatoinType); } else { String choices[] = new String[1]; if (locatoinType == net_choose_location) { choices[0] = getString(R.string.choose_location_here_try); } else { choices[0] = getString(R.string.choose_location_here_throw); } chooseAction(choices, locatoinType); } } catch (Exception e) { e.printStackTrace(); } } @Override public void doSelectChooseEvent(int which, int chooseType) { if (chooseType == net_choose_location) { if (which == 0) { UICore.eventTask(this, this, gain_bottle, "", null); } else { Intent intent = new Intent(ChooseBottleActivity.this, ChooseLocationTabsActivity.class); intent.putExtra("type", type); intent.putExtra("bottleId", bottleId); intent.putExtra("locationSelect", netLocationSelect); startActivity(intent); } } else { if (which == 0) { UICore.eventTask(this, this, init_location, "", null); } else { Intent intent = new Intent(ChooseBottleActivity.this, ChooseLocationTabsActivity.class); intent.putExtra("type", type); intent.putExtra("bottleId", bottleId); intent.putExtra("locationSelect", bttypeLocationSelect); startActivity(intent); } } } private void gainBottle() { String url = UrlConfig.gain_bt; HashMap<String, String> paramsMap = new HashMap<String, String>(); paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid())); paramsMap.put("login_token", AppContext.getInstance().getLogin_token()); paramsMap.put("nettypeid", String.valueOf(bottleId)); paramsMap.put("bt_geo_lng", String.valueOf(AppContext.getInstance().getLongitude() == 0.0 ? 0 : AppContext.getInstance().getLongitude())); paramsMap.put("bt_geo_lat", String.valueOf(AppContext.getInstance().getLatitude() == 0.0 ? 0 : AppContext.getInstance().getLatitude())); try { String result = HttpUtils.doPost(this, url, paramsMap); JSONObject obj = new JSONObject(result); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); if (success == 1) { String successmsg = resultObj.getString("successmsg"); int gainbt_type = resultObj.getInt("gainbt_type"); String gainbt_msg = resultObj.getString("gainbt_msg"); Object[] objs = new Object[3]; objs[0] = successmsg; objs[1] = gainbt_type; objs[2] = gainbt_msg; Message msg = Message.obtain(handler, gain_bottle_success, objs); handler.sendMessage(msg); } else { String errmsg = resultObj.getString("errmsg"); Message msg = Message.obtain(handler, gain_bottle_error, errmsg); handler.sendMessage(msg); } } catch (Exception e) { e.printStackTrace(); } } @Override public void execute(int mes, Object obj) { switch (mes) { case init_bottle_info: initBottleInfo(); handler.sendEmptyMessage(init_bottle_info); break; case init_permission_error: onToast((String) obj); break; case init_location: handler.sendEmptyMessage(init_location); break; case gain_bottle: gainBottle(); break; default: break; } } private void initBottleInfo() { if (type.equals("throw")) { BottleTypeTable btt = new BottleTypeTable(); bottltTypes = btt.getBottleTypes(); getThrowBottlePermission(); } else { BottleNetTypeTable bntt = new BottleNetTypeTable(); bottleNetTypes = bntt.getBottleNetTypes(); getTryBottlePermission(); } } private void getThrowBottlePermission() { String url = UrlConfig.get_sendbt_priv; HashMap<String, String> paramsMap = new HashMap<String, String>(); paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid())); paramsMap.put("login_token", AppContext.getInstance().getLogin_token()); try { String result = HttpUtils.doPost(this, url, paramsMap); if (result != null) { JSONObject obj = new JSONObject(result); JSONObject resultObj = obj.getJSONObject("results"); int authok = resultObj.getInt("authok"); if (authok == 0) { String errmsg = resultObj.getString("errmsg"); Message msg = Message.obtain(handler, init_permission_error, errmsg); handler.sendMessage(msg); } else { if (obj.has("sendbt_privs_list")) { JSONArray arrays = obj.getJSONArray("sendbt_privs_list"); permissions = new ArrayList<ChooseBottleActivity.BottlePermission>(); for (int i = 0;i < arrays.length();i++) { BottlePermission permission = new BottlePermission(); JSONObject priobj = arrays.getJSONObject(i); permission.bottleId = priobj.getInt("bttypeid"); permission.enable = priobj.getInt("enable"); permission.reason = priobj.getString("reason"); permission.useterm = priobj.getString("bttype_useterm"); permissions.add(permission); } } } } } catch (Exception e) { e.printStackTrace(); } } private BottlePermission getPermission(int bottleId) { if (permissions != null && !permissions.isEmpty()) { for (BottlePermission permission : permissions) { if (permission.bottleId == bottleId) { return permission; } } } return null; } private void getTryBottlePermission() { String url = UrlConfig.get_usenet_priv; HashMap<String, String> paramsMap = new HashMap<String, String>(); paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid())); paramsMap.put("login_token", AppContext.getInstance().getLogin_token()); try { String result = HttpUtils.doPost(this, url, paramsMap); if (result != null) { JSONObject obj = new JSONObject(result); JSONObject resultObj = obj.getJSONObject("results"); int authok = resultObj.getInt("authok"); if (authok == 0) { String errmsg = resultObj.getString("errmsg"); Message msg = Message.obtain(handler, init_permission_error, errmsg); handler.sendMessage(msg); } else { if (obj.has("usenet_privs_list")) { JSONArray arrays = obj.getJSONArray("usenet_privs_list"); permissions = new ArrayList<ChooseBottleActivity.BottlePermission>(); for (int i = 0;i < arrays.length();i++) { BottlePermission permission = new BottlePermission(); JSONObject priobj = arrays.getJSONObject(i); permission.bottleId = priobj.getInt("nettypeid"); permission.enable = priobj.getInt("enable"); permission.reason = priobj.getString("reason"); permission.useterm = priobj.getString("nettype_useterm"); permissions.add(permission); } } } } } catch (Exception e) { e.printStackTrace(); } } public class BottleTypeAdapter extends BaseAdapter { @Override public int getCount() { return bottltTypes == null ? 0 : bottltTypes.size(); } @Override public Object getItem(int position) { return bottltTypes == null ? null : bottltTypes.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view; ViewHolder holder; if (convertView != null) { view = convertView; holder = (ViewHolder) view.getTag(); } else { holder = new ViewHolder(); view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.choose_bottle_griditem, null); holder.bottle_icon = (ImageView) view.findViewById(R.id.choose_bottle_bottle_icon); holder.bottle_name = (TextView) view.findViewById(R.id.choose_bottle_bottle_name); view.setTag(holder); } BottleTypeEntry entry = bottltTypes.get(position); if (entry != null) { loader.DisplayImage(entry.getBttype_sjwicon(), holder.bottle_icon, R.drawable.bottle_type_1); if (AppContext.language == 1) { holder.bottle_name.setText(entry.getBttype_name_cn()); } else { holder.bottle_name.setText(entry.getBttype_name_en()); } } return view; } } public class BottleNetTypeAdapter extends BaseAdapter { @Override public int getCount() { return bottleNetTypes == null ? 0 : bottleNetTypes.size(); } @Override public Object getItem(int position) { return bottleNetTypes == null ? null : bottleNetTypes.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view; ViewHolder holder; if (convertView != null) { view = convertView; holder = (ViewHolder) view.getTag(); } else { holder = new ViewHolder(); view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.choose_bottle_griditem, null); holder.bottle_icon = (ImageView) view.findViewById(R.id.choose_bottle_bottle_icon); holder.bottle_name = (TextView) view.findViewById(R.id.choose_bottle_bottle_name); view.setTag(holder); } BottleNetTypeEntry entry = bottleNetTypes.get(position); if (entry != null) { loader.DisplayImage(entry.getNettype_sjwicon(), holder.bottle_icon, R.drawable.bottle_type_1); if (AppContext.language == 1) { holder.bottle_name.setText(entry.getNettype_name_cn()); } else { holder.bottle_name.setText(entry.getNettype_name_en()); } } return view; } } public static class ViewHolder { ImageView bottle_icon; TextView bottle_name; } public class BottlePermission { int bottleId; int enable; String reason; String useterm; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (pop.isShowing()) { pop.dismiss(); return true; } } return super.onKeyDown(keyCode, event); } @Override public boolean handleMessage(Message msg) { switch (msg.what) { case init_bottle_info: if (type.equals("throw")) { typeAdapter = new BottleTypeAdapter(); gridView.setAdapter(typeAdapter); } else { netAdapter = new BottleNetTypeAdapter(); gridView.setAdapter(netAdapter); } break; case init_location: if (type.equals("throw")) { Intent intent2 = new Intent(ChooseBottleActivity.this, ThrowBottleSettingActivity.class); intent2.putExtra("bttype_id", bottleId); intent2.putExtra("bt_geo_lng", AppContext.getInstance().getLongitude()); intent2.putExtra("bt_geo_lat", AppContext.getInstance().getLatitude()); startActivity(intent2); } break; case gain_bottle_error: onToast((String) msg.obj); break; case gain_bottle_success: try { Object[] objs = (Object[]) msg.obj; onToast((String) objs[0]); Intent intent = new Intent(ChooseBottleActivity.this, BottleTipsActivity.class); intent.putExtra("type", "try"); intent.putExtra("bottleId", Integer.parseInt(objs[1].toString())); intent.putExtra("gainbt_msg", objs[2].toString()); startActivity(intent); } catch (Exception e) { e.printStackTrace(); } break; default: break; } return false; } }
Java
package com.outsourcing.bottle.ui; import java.util.List; import org.json.JSONObject; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Handler; import android.os.Handler.Callback; import android.os.Message; import android.text.Html; import android.text.TextUtils; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.TextView; import com.google.gson.Gson; import com.outsourcing.bottle.BasicActivity; import com.outsourcing.bottle.R; import com.outsourcing.bottle.domain.MessageEntry; import com.outsourcing.bottle.domain.MyMessageInfo; import com.outsourcing.bottle.domain.OUserInfoEntry; import com.outsourcing.bottle.domain.UrlConfig; import com.outsourcing.bottle.remoteimage.RemoteImageView; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.HttpUtils; import com.outsourcing.bottle.util.ServiceUtils; import com.outsourcing.bottle.util.TextUtil; import com.outsourcing.bottle.util.UICore; import com.outsourcing.bottle.widget.CustomListView; /** * * @author 06peng * */ public class ConversationListActivity extends BasicActivity implements Callback, OnClickListener { private static final int EXEU_DELETE_LOCATION_SUCCESS = 101; private static final int EXEU_DELETE_LOCATION_FAILED = 102; private static final int EXEU_DELETE_LOCATION = 103; private ImageView backView; private ImageView moreView; // private ImageView noticeView; // private LinearLayout messageCountLayout; // private TextView countView; private CustomListView listView; private int visibleLastIndex = 0; // 最后的可视项索引 public int visibleItemCount; // 当前窗口可见项总数 private View loadMoreView; private ImageView commentView; private final int init_conversation_info = 1; private final int error = 2; private final int user_baseinfo_notfull = 3; private final int complete_info = 4; private final int more = 7; private int page = 1; // private int newNoticeCount; private Handler handler; private int ouid; private List<MessageEntry> messageList; private ConversationAdapter adapter; private OUserInfoEntry entry; private Bitmap bitmap; //用户头像 // private PushNoticeInfo pushInfo; /******* 用户资料 *********/ private RemoteImageView avatarView; private TextView nicknameView; private TextView memoView; private ImageView sexView; private TextView doingView; private TextView addressView; @Override protected void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); setContentView(R.layout.conversation_list); handler = new Handler(this); ouid = getIntent().getIntExtra("ouid", 0); initWidget(); UICore.eventTask(this, this, init_conversation_info, "init_conversation_info", null); } private void initWidget() { backView = (ImageView) findViewById(R.id.topbar_back); backView.setOnClickListener(this); moreView = (ImageView) findViewById(R.id.topbar_menu); moreView.setOnClickListener(this); // noticeView = (ImageView) findViewById(R.id.topbar_notice); // noticeView.setOnClickListener(this); commentView = (ImageView) findViewById(R.id.comment); commentView.setOnClickListener(this); // messageCountLayout = (LinearLayout) findViewById(R.id.notice_layout); // messageCountLayout.setVisibility(View.GONE); // countView = (TextView) findViewById(R.id.notice_count); listView = (CustomListView) findViewById(R.id.notice_list); loadMoreView = LayoutInflater.from(this).inflate(R.layout.refreshable_list_footer, null); loadMoreView.setVisibility(View.GONE); listView.addFooterView(loadMoreView); listView.setonRefreshListener(new CustomListView.OnRefreshListener() { @Override public void onRefresh() { page = 1; new Thread() { public void run() { initConversationInfo(); }; }.start(); } }); listView.setOnScrollListener(new OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { int itemsLastIndex = adapter.getCount() + 1; // 数据集最后一项的索引 int lastIndex = itemsLastIndex + 1; // 加上底部的loadMoreView项 和 head项 if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == lastIndex) { // 如果是自动加载,可以在这里放置异步加载数据的代码 loadMoreView.setVisibility(View.VISIBLE); page++; new Thread() { @Override public void run() { loadMoreConversationInfo(); } }.start(); } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { listView.setFirstVisiableItem(firstVisibleItem); ConversationListActivity.this.visibleItemCount = visibleItemCount; visibleLastIndex = firstVisibleItem + visibleItemCount; } }); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { if (arg2 == adapter.getCount() + 1) { return; } MessageEntry entry = messageList.get(arg2 - 1); if (entry.getMessage_location() != null && entry.getMessage_lat() != 0 && entry.getMessage_lng() != 0) { Intent intent = new Intent(ConversationListActivity.this, MapViewActivity.class); intent.putExtra("longitude", entry.getMessage_lng()); intent.putExtra("latidute", entry.getMessage_lat()); intent.putExtra("location", entry.getMessage_location()); startActivity(intent); } } }); avatarView = (RemoteImageView) findViewById(R.id.user_space_avatar); avatarView.setOnClickListener(this); nicknameView = (TextView) findViewById(R.id.user_space_nickname); memoView = (TextView) findViewById(R.id.user_space_memo); sexView = (ImageView) findViewById(R.id.user_space_sex); doingView = (TextView) findViewById(R.id.user_space_doing); addressView = (TextView) findViewById(R.id.user_space_address); } private void updateUI() { findViewById(R.id.conversation_layout).setVisibility(View.VISIBLE); commentView.setVisibility(View.VISIBLE); if (entry != null) { nicknameView.setText(entry.getOnickname()); if (entry.getOsex() == 1) { sexView.setBackgroundResource(R.drawable.male); } else if (entry.getOsex() == 2) { sexView.setBackgroundResource(R.drawable.female); } if (TextUtil.notEmpty(entry.getOmemo())) { ((TextView) findViewById(R.id.user_space_memo)).setVisibility(View.VISIBLE); memoView.setText("-" + entry.getOmemo()); } else { ((TextView) findViewById(R.id.user_space_memo)).setVisibility(View.GONE); memoView.setVisibility(View.GONE); } if (TextUtil.notEmpty(entry.getOcity()) && TextUtil.notEmpty(entry.getOcountry())) { addressView.setVisibility(View.VISIBLE); if (AppContext.language == 1) { addressView.setText(getString(R.string.user_from) + entry.getOcountry() + " " + entry.getOcity()); } else { addressView.setText(getString(R.string.user_from) + entry.getOcity() + " " + entry.getOcountry()); } } else { addressView.setVisibility(View.GONE); } String html = "<font color=black>"+getString(R.string.user_info_doing)+"</font>"; doingView.setText(Html.fromHtml(html + entry.getOdoing())); if (bitmap != null) { avatarView.setImageBitmap(bitmap); } } if (messageList != null && !messageList.isEmpty()) { adapter = new ConversationAdapter(); listView.setAdapter(adapter); } } @Override public void onClick(View v) { if (v == backView) { finish(); } else if (v == moreView) { // Intent intent = new Intent(this, MoreActivity.class); // startActivity(intent); Intent intent = new Intent(ConversationListActivity.this, HomeActivity.class); intent.putExtra("currentItem", 1); startActivity(intent); finish(); } // else if (v == noticeView) { // Intent intent = new Intent(this, NoticeListActivity.class); // startActivity(intent); // } else if (v == commentView) { Intent intent = new Intent(this, ExpandEditActivity.class); Bundle extras = new Bundle(); extras.putString("from_type", AppContext.SEND_MESSAGE); extras.putInt("ouid", ouid); intent.putExtras(extras); startActivity(intent); } else if (v == avatarView) { byte[] tempBytes = null; try { tempBytes = ServiceUtils.BitmapTobytes(bitmap); } catch (Exception e) { e.printStackTrace(); } Intent bigPicIntent = new Intent(ConversationListActivity.this, PhotoDetailActivity.class); bigPicIntent.putExtra("pic_big", entry.getOavatar()); bigPicIntent.putExtra("thumbnail", tempBytes); startActivity(bigPicIntent); } } @Override public void execute(int mes, Object obj) { switch (mes) { case init_conversation_info: initConversationInfo(); break; case EXEU_DELETE_LOCATION: MessageEntry messageEntry = (MessageEntry)obj; deleteLocation(String.valueOf(messageEntry.getLocation_objtype()),String.valueOf(messageEntry.getLocation_objid())); break; default: break; } } @Override public boolean handleMessage(Message msg) { switch (msg.what) { case init_conversation_info: updateUI(); listView.onRefreshComplete(); break; case user_baseinfo_notfull: showChoseMes(getString(R.string.exchange_complete_profile_tips), complete_info); break; case error: onToast((String) msg.obj); break; case more: adapter.notifyDataSetChanged(); loadMoreView.setVisibility(View.GONE); case EXEU_DELETE_LOCATION_SUCCESS: onToast((String) msg.obj); UICore.eventTask(ConversationListActivity.this, ConversationListActivity.this, init_conversation_info, "init_conversation_info", null); break; case EXEU_DELETE_LOCATION_FAILED: onToast((String) msg.obj); break; default: break; } return false; } /** * * @param objtype 要清除的位置的类型:选择项:(1)瓶子动态的位置信息、(2)交换动态留言的位置信息、(3)照片评论的位置信息、(4)私信的位置信息、(5)照片的位置信息 * @param objid objid */ private void deleteLocation(String objtype,String objid) { StringBuffer url = new StringBuffer(UrlConfig.delete_location); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&objtype=" + objtype); url.append("&objid=" + objid); ServiceUtils.dout("deleteLocation url:" + url.toString()); try { String result = HttpUtils.doGet(url.toString()); ServiceUtils.dout("deleteLocation result:" + result); JSONObject obj = new JSONObject(result); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); String errmsg = resultObj.getString("errmsg"); String successmsg = resultObj.getString("successmsg"); if (success == 1) { Message message = handler.obtainMessage( EXEU_DELETE_LOCATION_SUCCESS, successmsg); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_DELETE_LOCATION_FAILED, errmsg); handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } private void initConversationInfo() { StringBuffer url = new StringBuffer(UrlConfig.get_mymessageslist); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); url.append("&count=" + 20); url.append("&page=" + page); try { String result = HttpUtils.doGet(url.toString()); if (result == null) { return; } Gson gson = new Gson(); MyMessageInfo info = gson.fromJson(result, MyMessageInfo.class); if (info.getResults().getAuthok() == 0) { Message msg = Message.obtain(handler, error, info.getResults().getErrmsg()); handler.sendMessage(msg); } else { // PushNoticeInfoTable table = new PushNoticeInfoTable(); // pushInfo = table.getPushNoticeInfo(AppContext.getInstance().getLogin_uid()); // if (null!= pushInfo) { // newNoticeCount = pushInfo.getNew_notice_count(); // } entry = info.getOuser_info(); if (entry != null) { bitmap = HttpUtils.getBitmapFromUrl(ConversationListActivity.this, entry.getOavatar()); } messageList = info.getMessages_list(); handler.sendEmptyMessage(init_conversation_info); } } catch (Exception e) { e.printStackTrace(); } } private void loadMoreConversationInfo() { StringBuffer url = new StringBuffer(UrlConfig.get_mymessageslist); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); url.append("&count=" + 20); url.append("&page=" + page); try { String result = HttpUtils.doGet(url.toString()); if (result == null) { return; } Gson gson = new Gson(); MyMessageInfo info = gson.fromJson(result, MyMessageInfo.class); if (info.getResults().getAuthok() == 0) { Message msg = Message.obtain(handler, error, info.getResults().getErrmsg()); handler.sendMessage(msg); } else { List<MessageEntry> moreList = info.getMessages_list(); messageList.addAll(moreList); handler.sendEmptyMessage(more); } } catch (Exception e) { e.printStackTrace(); } } public class ConversationAdapter extends BaseAdapter { @Override public int getCount() { return messageList.size(); } @Override public Object getItem(int arg0) { return messageList.get(arg0); } @Override public long getItemId(int arg0) { return arg0; } @Override public View getView(int arg0, View arg1, ViewGroup arg2) { ViewHolder holder; if (arg1 != null && arg1.getId() == R.id.conversation_list_item_layout) { holder = (ViewHolder) arg1.getTag(); } else { arg1 = LayoutInflater.from(getApplicationContext()).inflate(R.layout.conversation_list_item, null); holder = new ViewHolder(); holder.avatarView = (RemoteImageView) arg1.findViewById(R.id.notice_item_avatar); holder.nameView = (TextView) arg1.findViewById(R.id.notice_item_nameandcontent); holder.timeView = (TextView) arg1.findViewById(R.id.notice_item_timeandlocation); holder.contentLayout = (LinearLayout) arg1.findViewById(R.id.notice_item_content_layout); arg1.setTag(holder); } final MessageEntry entry = messageList.get(arg0); if (entry != null) { holder.avatarView.setDefaultImage(R.drawable.avatar_default_big); holder.avatarView.setImageUrl(entry.getAvatar(), arg0, listView); String name = null; if (entry.getUid() == AppContext.getInstance().getLogin_uid()) { name = "<font color=#419AD9>" + entry.getNickname() + "</font>"; holder.contentLayout.setBackgroundResource(R.drawable.frame_yellow); } else { name = "<font color=red>" + entry.getNickname() + "</font>"; holder.contentLayout.setBackgroundResource(R.drawable.frame_gray); } holder.nameView.setText(Html.fromHtml(name + "&nbsp;" + TextUtil.htmlEncode(entry.getContent()))); String time = (!TextUtils.isEmpty(entry.getMessage_time()))?"#"+entry.getMessage_time():""; String location = (!TextUtils.isEmpty( entry.getMessage_location()))?"@"+ entry.getMessage_location():""; holder.timeView.setText(Html.fromHtml(time + " " +location)); if (!TextUtils.isEmpty(location)) { holder.timeView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(entry.getLocation_delete_enable() == 1){ final Context dialogContext = new ContextThemeWrapper( ConversationListActivity.this, android.R.style.Theme_Light); String[] choices = new String[2]; choices[0] = getString(R.string.bottle_txt_check_location); choices[1] = getString(R.string.bottle_txt_clean_location); final ListAdapter adapter = new ArrayAdapter<String>( dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems( adapter, -1, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { dialog.dismiss(); if (which == 0) { dialog.dismiss(); Intent intent = new Intent( ConversationListActivity.this, MapViewActivity.class); intent.putExtra("longitude",entry.getMessage_lng()); intent.putExtra("latidute",entry.getMessage_lat()); intent.putExtra("location",entry.getMessage_location()); startActivity(intent); } else { UICore.eventTask(ConversationListActivity.this, ConversationListActivity.this, EXEU_DELETE_LOCATION, "", entry); } } }); builder.create().show(); } else { final Context dialogContext = new ContextThemeWrapper( ConversationListActivity.this, android.R.style.Theme_Light); String[] choices = new String[1]; choices[0] = getString(R.string.bottle_txt_check_location); final ListAdapter adapter = new ArrayAdapter<String>( dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { dialog.dismiss(); Intent intent = new Intent( ConversationListActivity.this, MapViewActivity.class); intent.putExtra("longitude",entry.getMessage_lng()); intent.putExtra("latidute",entry.getMessage_lat()); intent.putExtra("location",entry.getMessage_location()); startActivity(intent); } }); builder.create().show(); } } }); } } return arg1; } } public static class ViewHolder { RemoteImageView avatarView; TextView nameView; TextView timeView; LinearLayout contentLayout; } @Override public void sysMesPositiveButtonEvent(int what) { if (what == complete_info) { Intent intent = new Intent(this, SettingActivity.class); startActivity(intent); } } }
Java
package com.outsourcing.bottle.ui; import java.util.HashMap; import java.util.List; import org.json.JSONObject; import android.os.Bundle; import android.os.Handler; import android.os.Handler.Callback; import android.os.Message; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.google.gson.Gson; import com.outsourcing.bottle.BasicActivity; import com.outsourcing.bottle.R; import com.outsourcing.bottle.db.LoginUserInfoTable; import com.outsourcing.bottle.domain.CompanyEntry; import com.outsourcing.bottle.domain.CompanyInfo; import com.outsourcing.bottle.domain.LoginUserInfo; import com.outsourcing.bottle.domain.UrlConfig; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.BasicUIEvent; import com.outsourcing.bottle.util.HttpUtils; import com.outsourcing.bottle.util.UICore; /** * * @author 06peng * */ public class SettingCompanyActivity extends BasicActivity implements BasicUIEvent, Callback, OnClickListener { private EditText editView; private ImageView addView; private ListView listView; private final int init_company_info = 1; private final int error = 2; private final int add_company = 3; private final int delete_company = 4; private Handler handler; private List<CompanyEntry> companyList; @Override protected void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); setContentView(R.layout.setting_company); handler = new Handler(this); initWidget(); UICore.eventTask(this, this, init_company_info, "init_company_info", null); } private void initWidget() { editView = (EditText) findViewById(R.id.setting_company_edit); editView.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) { if (editView.getText().toString().trim().equals("")) { onToast(getString(R.string.setting_company_error_tips)); return true; } UICore.eventTask(SettingCompanyActivity.this, SettingCompanyActivity.this, add_company, "add_company", null); } return false; } }); addView = (ImageView) findViewById(R.id.setting_company_add); addView.setOnClickListener(this); listView = (ListView) findViewById(R.id.setting_company_list); } @Override public void onClick(View v) { if (v == addView) { if (editView.getText().toString().trim().equals("")) { onToast(getString(R.string.setting_company_error_tips)); return; } UICore.eventTask(this, this, add_company, "add_company", null); } } @Override public boolean handleMessage(Message msg) { switch (msg.what) { case init_company_info: if (companyList != null && !companyList.isEmpty()) { CompanyAdapter adapter = new CompanyAdapter(); listView.setAdapter(adapter); } break; case error: onToast((String) msg.obj); break; case delete_company: onToast((String) msg.obj); UICore.eventTask(this, this, init_company_info, "init_company_info", null); break; case add_company: onToast((String) msg.obj); UICore.eventTask(this, this, init_company_info, "init_company_info", null); break; default: break; } return false; } public void back(View v) { finish(); } @Override public void execute(int mes, Object obj) { switch (mes) { case init_company_info: initCompanyInfo(); break; case delete_company: deleteCompany((String) obj); break; case add_company: addCompany(); break; default: break; } } private void initCompanyInfo() { StringBuffer url = new StringBuffer(UrlConfig.get_work_info); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); try { String result = HttpUtils.doGet(url.toString()); if (result != null) { Gson gson = new Gson(); CompanyInfo info = gson.fromJson(result, CompanyInfo.class); if (info.getResults().getAuthok() == 0) { Message msg = Message.obtain(handler, error, info.getResults().getErrmsg()); handler.sendMessage(msg); } else { companyList = info.getMycompanies_list(); handler.sendEmptyMessage(init_company_info); } } } catch (Exception e) { e.printStackTrace(); } } private void deleteCompany(String companyid) { String url = UrlConfig.delete_company_info; HashMap<String, String> paramsMap = new HashMap<String, String>(); paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid())); paramsMap.put("login_token", AppContext.getInstance().getLogin_token()); paramsMap.put("companyid", companyid); try { String result = HttpUtils.doPost(this, url, paramsMap); if (result != null) { JSONObject object = new JSONObject(result); JSONObject resultObj = object.getJSONObject("results"); int success = resultObj.getInt("success"); if (success == 0) { String errmsg = resultObj.getString("errmsg"); Message msg = Message.obtain(handler, error, errmsg); handler.sendMessage(msg); } else { getLoginUserInfo(); String successmsg = resultObj.getString("successmsg"); Message msg = Message.obtain(handler, delete_company, successmsg); handler.sendMessage(msg); } } } catch (Exception e) { e.printStackTrace(); } } private void addCompany() { String url = UrlConfig.add_company_info; HashMap<String, String> paramsMap = new HashMap<String, String>(); paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid())); paramsMap.put("login_token", AppContext.getInstance().getLogin_token()); paramsMap.put("company", editView.getText().toString().trim()); try { String result = HttpUtils.doPost(this, url, paramsMap); if (result != null) { JSONObject object = new JSONObject(result); JSONObject resultObj = object.getJSONObject("results"); int success = resultObj.getInt("success"); if (success == 0) { String errmsg = resultObj.getString("errmsg"); Message msg = Message.obtain(handler, error, errmsg); handler.sendMessage(msg); } else { getLoginUserInfo(); String successmsg = resultObj.getString("successmsg"); Message msg = Message.obtain(handler, add_company, successmsg); handler.sendMessage(msg); } } } catch (Exception e) { e.printStackTrace(); } } private void getLoginUserInfo() { StringBuffer url = new StringBuffer(UrlConfig.get_loginuser_info); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); try { String result = HttpUtils.doGet(url.toString()); if (result == null) { return; } Gson gson = new Gson(); LoginUserInfo loginUserInfo = gson.fromJson(result, LoginUserInfo.class); if (loginUserInfo.getResults().getAuthok() == 1) { LoginUserInfoTable loginUserInfoTable = new LoginUserInfoTable(); if (null != loginUserInfoTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid())) { loginUserInfoTable.deleteLoginUserInfoById(AppContext.getInstance().getLogin_uid()); loginUserInfoTable.saveLoginUserInfo(loginUserInfo .getLoginuser_info(), AppContext.getInstance().getLogin_uid()); } else { loginUserInfoTable.saveLoginUserInfo(loginUserInfo .getLoginuser_info(), AppContext.getInstance().getLogin_uid()); } } } catch (Exception e) { e.printStackTrace(); } } public class CompanyAdapter extends BaseAdapter { @Override public int getCount() { return companyList.size(); } @Override public Object getItem(int position) { return companyList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.setting_listitem, null); } TextView company = (TextView) convertView.findViewById(R.id.setting_listitem_name); ImageView add = (ImageView) convertView.findViewById(R.id.setting_listitem_image); final CompanyEntry entry = companyList.get(position); if (entry != null) { company.setText(entry.getCompany()); add.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int companyid = entry.getCompanyid(); UICore.eventTask(SettingCompanyActivity.this, SettingCompanyActivity.this, delete_company, "delete_company", String.valueOf(companyid)); } }); } return convertView; } } }
Java
package com.outsourcing.bottle.ui; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Handler.Callback; import android.os.Message; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ext.SatelliteMenu; import android.view.ext.SatelliteMenu.SateliteClickedListener; import android.view.ext.SatelliteMenuItem; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.google.gson.Gson; import com.outsourcing.bottle.BasicActivity; import com.outsourcing.bottle.R; import com.outsourcing.bottle.db.LoginUserInfoTable; import com.outsourcing.bottle.domain.LoginUserInfoEntry; import com.outsourcing.bottle.domain.MyFriendEntry; import com.outsourcing.bottle.domain.MyFriendInfo; import com.outsourcing.bottle.domain.UrlConfig; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.HttpUtils; import com.outsourcing.bottle.util.ImageLoader; import com.outsourcing.bottle.util.ServiceUtils; import com.outsourcing.bottle.util.TextUtil; import com.outsourcing.bottle.util.UICore; import com.outsourcing.bottle.widget.CustomListView; /** * * @author 06peng * */ public class FriendListActivity extends BasicActivity implements OnClickListener, Callback, OnScrollListener { private static final int INIT_FRIEND_FEED = 0; private static final int GET_MORE_DATA = 1; private static final int ERROR = 2; private static final String TAG = FriendListActivity.class.getSimpleName(); private static final int EXEU_GET_FRIEND_NOTHING = 3; private final int user_baseinfo_notfull = 4; private final int complete_info = 5; private ImageView backView; private ImageView addView; private TextView titleView; private ImageView spaceView; private CustomListView refreshView; private final int menu_uploadphoto = 15; private final int menu_exprofile = 14; private final int menu_exphoto = 13; private final int menu_gainbt = 12; private final int menu_sendbt = 11; private Handler handler; private int page = 1; private int visibleLastIndex = 0; // 最后的可视项索引 private View loadMoreView; private int ouid; private MyFriendInfo myfriendInfo; private List<MyFriendEntry> myFriendEntries; private FriendListAdapter myFriendAdapter; @Override protected void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); setContentView(R.layout.friend_feeds_layout); handler = new Handler(this); ouid = getIntent().getIntExtra("ouid", 0); // imageLoader = new ImageLoader(this, AppContext.UserAvatarIcon); // imageLoader2 = new ImageLoader(this, AppContext.BottleTimelineIcon); initWidget(); initSateMenu(); UICore.eventTask(this, this, INIT_FRIEND_FEED, "", null); } private void initWidget() { backView = (ImageView) findViewById(R.id.topbar_back); backView.setOnClickListener(this); addView = (ImageView) findViewById(R.id.topbar_menu); addView.setOnClickListener(this); titleView = (TextView) findViewById(R.id.topbar_title); titleView.setVisibility(View.VISIBLE); spaceView = (ImageView) findViewById(R.id.topbar_space); spaceView.setOnClickListener(this); refreshView = (CustomListView) findViewById(R.id.list_view); refreshView.setonRefreshListener(new CustomListView.OnRefreshListener() { @Override public void onRefresh() { page = 1; UICore.eventTask(FriendListActivity.this, FriendListActivity.this, INIT_FRIEND_FEED, null, null); } }); loadMoreView = LayoutInflater.from(this).inflate(R.layout.refreshable_list_footer, null); loadMoreView.setVisibility(View.GONE); refreshView.addFooterView(loadMoreView); refreshView.setOnScrollListener(this); } @Override public boolean handleMessage(Message msg) { switch (msg.what) { case INIT_FRIEND_FEED: myFriendAdapter = new FriendListAdapter(FriendListActivity.this, myFriendEntries); refreshView.setAdapter(myFriendAdapter); break; case ERROR: onToast((String) msg.obj); break; case GET_MORE_DATA: myFriendAdapter.notifyDataSetChanged(); // refreshView.onRefreshComplete(); break; case user_baseinfo_notfull: showChoseMes(getString(R.string.exchange_complete_profile_tips), complete_info); break; case EXEU_GET_FRIEND_NOTHING: loadMoreView.setVisibility(View.GONE); break; default: break; } return false; } @Override public void onClick(View v) { if (v == backView) { finish(); } else if (v == addView) { Intent intent = new Intent(this, MoreActivity.class); startActivity(intent); } else if (v == spaceView) { Intent intent = new Intent(this, UserSpaceActivity.class); intent.putExtra("ouid", AppContext.getInstance().getLogin_uid()); startActivity(intent); } } @Override public void execute(int mes, Object obj) { switch (mes) { case INIT_FRIEND_FEED: getFriendsList(page, -1, ouid); break; case GET_MORE_DATA: getMoreFriendsList(page, -1, ouid); break; default: break; } } /*** * 获取好友列表 * * @param page */ private void getFriendsList(int page, int groupid, int ouid) { StringBuffer url = new StringBuffer(UrlConfig.get_friends_list); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&groupid=" + groupid); url.append("&ouid=" + ouid); url.append("&count=20"); url.append("&page=" + page); ServiceUtils.dout("getFriendsList url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); if (results == null) { return; } ServiceUtils.dout("getFriendsList results:" + results.toString()); Gson gson = new Gson(); myfriendInfo = gson.fromJson(results, MyFriendInfo.class); if (myfriendInfo.getResults().getAuthok() == 1) { myFriendEntries = myfriendInfo.getFriends_list(); Message message = handler.obtainMessage(INIT_FRIEND_FEED); handler.sendMessage(message); } else { Message message = handler.obtainMessage(ERROR, myfriendInfo .getResults().getErrmsg()); handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } /*** * 获取更多好友列表 * * @param page */ private void getMoreFriendsList(int page, int groupid, int ouid) { StringBuffer url = new StringBuffer(UrlConfig.get_friends_list); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&groupid=" + groupid); url.append("&ouid=" + ouid); url.append("&count=20"); url.append("&page=" + page); ServiceUtils.dout("getMoreFriendsList url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); if (results == null) { return; } ServiceUtils.dout("getMoreFriendsList results:" + results.toString()); Gson gson = new Gson(); myfriendInfo = gson.fromJson(results, MyFriendInfo.class); if (myfriendInfo.getResults().getAuthok() == 1) { List<MyFriendEntry> moreEntries = myfriendInfo .getFriends_list(); if (null != moreEntries && moreEntries.size() > 0) { myFriendEntries.addAll(moreEntries); Message message = handler.obtainMessage(GET_MORE_DATA); handler.sendMessage(message); } else { Message message = handler .obtainMessage(EXEU_GET_FRIEND_NOTHING); handler.sendMessage(message); } } else { Message message = handler.obtainMessage(ERROR, myfriendInfo .getResults().getErrmsg()); handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } private void initSateMenu() { SatelliteMenu menu = (SatelliteMenu) findViewById(R.id.menu); menu.setVisibility(View.VISIBLE); List<SatelliteMenuItem> items = new ArrayList<SatelliteMenuItem>(); items.add(new SatelliteMenuItem(menu_exprofile, R.drawable.menu_exprofile)); items.add(new SatelliteMenuItem(menu_exphoto, R.drawable.menu_exphoto)); items.add(new SatelliteMenuItem(menu_gainbt, R.drawable.menu_gainbt)); items.add(new SatelliteMenuItem(menu_sendbt, R.drawable.menu_sendbt)); items.add(new SatelliteMenuItem(menu_uploadphoto, R.drawable.menu_uploadphoto)); menu.addItems(items); menu.setOnItemClickedListener(new SateliteClickedListener() { public void eventOccured(int id) { switch (id) { case menu_sendbt: // 扔瓶子 new Thread() { public void run() { try { Thread.sleep(500); Intent throwIntent = new Intent( FriendListActivity.this, ChooseBottleActivity.class); throwIntent.putExtra("type", "throw"); startActivity(throwIntent); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; case menu_gainbt: // 捞瓶子 new Thread() { public void run() { try { Thread.sleep(500); Intent tryIntent = new Intent( FriendListActivity.this, ChooseBottleActivity.class); tryIntent.putExtra("type", "try"); startActivity(tryIntent); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; case menu_exphoto: // 交换照片 new Thread() { public void run() { try { Thread.sleep(500); Intent exchangeInfoIntent = new Intent( FriendListActivity.this, ChooseFriendActivity.class); exchangeInfoIntent .putExtra( "choose_friend_type", AppContext.CHOOSE_FRIEND_EXCHANGE_PHOTO_TYPE); startActivity(exchangeInfoIntent); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; case menu_exprofile: // 交换资料 new Thread() { public void run() { try { Thread.sleep(500); LoginUserInfoTable userTable = new LoginUserInfoTable(); LoginUserInfoEntry userEntry = userTable .getLoginUserInfo(AppContext .getInstance().getLogin_uid()); if (userEntry.getBasicinfo_fullfill() == 0) { handler.sendEmptyMessage(user_baseinfo_notfull); } else { Intent exchangeFileIntent = new Intent( FriendListActivity.this, ChooseFriendActivity.class); exchangeFileIntent .putExtra( "choose_friend_type", AppContext.CHOOSE_FRIEND_EXCHANGE_INFO_TYPE); startActivity(exchangeFileIntent); } } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; case menu_uploadphoto: new Thread() { public void run() { try { Thread.sleep(500); Intent intent = new Intent(FriendListActivity.this, ExpandEditActivity.class); Bundle extras = new Bundle(); extras.putString("from_type", AppContext.UPLOAD_PHOTO); extras.putInt("albumid", 0); extras.putInt("ouid", AppContext.getInstance().getLogin_uid()); intent.putExtras(extras); startActivity(intent); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; default: break; } } }); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // this.visibleItemCount = visibleItemCount; visibleLastIndex = firstVisibleItem + visibleItemCount; } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { int itemsLastIndex = myFriendAdapter.getCount() + 1; // 数据集最后一项的索引 int lastIndex = itemsLastIndex + 1; // 加上底部的loadMoreView项 和 head项 ServiceUtils.dout(TAG + " visibleLastIndex:" + visibleLastIndex); ServiceUtils.dout(TAG + " lastIndex:" + lastIndex); if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == lastIndex) { // 如果是自动加载,可以在这里放置异步加载数据的代码 loadMoreView.setVisibility(View.VISIBLE); page++; UICore.eventTask(FriendListActivity.this, FriendListActivity.this, GET_MORE_DATA, null, null); } } public class FriendListAdapter extends BaseAdapter { private Context context = null; private List<MyFriendEntry> mbtfriendList = null; private ImageLoader imageLoader = null; public FriendListAdapter(Context context, List<MyFriendEntry> mbtfriendList) { this.context = context; this.mbtfriendList = mbtfriendList; imageLoader = new ImageLoader(context, AppContext.BottleTimelineIcon); } @Override public int getCount() { return mbtfriendList.size(); } @Override public Object getItem(int position) { return mbtfriendList.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { BTFriendViewHolder holder = null; if (convertView == null || ((BTFriendViewHolder) convertView.getTag()).flag != position) { holder = new BTFriendViewHolder(); System.out.println("position===== convertView=null ====" + position); convertView = LayoutInflater.from(context).inflate( R.layout.bottle_list_avatar_item, null); holder.flag = position; holder.mAuthorView = (ImageView) convertView .findViewById(R.id.iv_author_photo); holder.mExType = (ImageView) convertView .findViewById(R.id.iv_bottle_type); holder.mExType.setVisibility(View.GONE); // content layout LinearLayout contentLayout = (LinearLayout) convertView .findViewById(R.id.feed_post_body); View view = LayoutInflater.from(context).inflate( R.layout.mygroupfriend_list_item, null); holder.mNickName = (TextView) view .findViewById(R.id.tv_onickname); holder.mSex = (ImageView)view.findViewById(R.id.bt_sex); holder.mDoing = (TextView) view.findViewById(R.id.tv_odoing); holder.mLocation = (TextView) view .findViewById(R.id.tv_olocation); contentLayout.addView(view); final MyFriendEntry myFriendEntry = (MyFriendEntry) getItem(position); try { imageLoader.DisplayImage(myFriendEntry.getFavatar(), holder.mAuthorView, R.drawable.avatar_default_big); } catch (Exception e) { e.printStackTrace(); holder.mAuthorView .setImageResource(R.drawable.avatar_default_big); } holder.mAuthorView .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent spaceIntent = new Intent(context, UserSpaceActivity.class); spaceIntent.putExtra("ouid", myFriendEntry.getFuid()); context.startActivity(spaceIntent); } }); String nickName = "<font color='#0099FF'>" + myFriendEntry.getFnickname() + "</font>"; // String sex = (((myFriendEntry.getFsex()) == 1) ? ("(" // + TextUtil.R("login_txt_register_male") + ")") : ("(" // + TextUtil.R("login_txt_register_female") + ")")); holder.mNickName.setText(Html.fromHtml(nickName)); int sex_res = myFriendEntry.getFsex() == 1 ? R.drawable.male:R.drawable.female; holder.mSex.setBackgroundResource(sex_res); if (null != myFriendEntry.getFdoing() && myFriendEntry.getFdoing().length() > 0) { holder.mDoing.setVisibility(View.VISIBLE); String doingTips = "<font color='#000000'>" + TextUtil.R("friend_doing_tips") + "</font>"; holder.mDoing.setText(Html.fromHtml(doingTips + myFriendEntry.getFdoing())); } else { holder.mDoing.setVisibility(View.GONE); } if ((null != myFriendEntry.getFcountry() && myFriendEntry .getFcountry().length() > 0) || (null != myFriendEntry.getFcity() && myFriendEntry .getFcity().length() > 0)) { holder.mLocation.setVisibility(View.VISIBLE); String fromTips = "<font color='#000000'>" + TextUtil.R("friend_comfrom_tips") + "</font>"; holder.mLocation.setText(Html.fromHtml(fromTips + myFriendEntry.getFcity() + " " + myFriendEntry.getFcity())); } else { holder.mLocation.setVisibility(View.GONE); } convertView.setTag(holder); } else { holder = (BTFriendViewHolder) convertView.getTag(); } return convertView; } class BTFriendViewHolder { public ImageView mSex; ImageView mAuthorView; ImageView mExType; TextView mNickName; TextView mDoing; TextView mLocation; int flag; } } }
Java
package com.outsourcing.bottle.ui; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.json.JSONObject; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Handler.Callback; import android.os.Message; import android.text.Html; import android.text.TextUtils; import android.util.DisplayMetrics; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.view.ext.SatelliteMenu; import android.view.ext.SatelliteMenu.SateliteClickedListener; import android.view.ext.SatelliteMenuItem; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import com.aviary.android.feather.Constants; import com.aviary.android.feather.FeatherActivity; import com.google.gson.Gson; import com.outsourcing.bottle.BasicActivity; import com.outsourcing.bottle.R; import com.outsourcing.bottle.db.LoginUserInfoTable; import com.outsourcing.bottle.db.PushNoticeInfoTable; import com.outsourcing.bottle.domain.ExFeedInfoEntry; import com.outsourcing.bottle.domain.ExchangePicFeedInfo; import com.outsourcing.bottle.domain.ExchangePicInfoEntry; import com.outsourcing.bottle.domain.LoginUserInfoEntry; import com.outsourcing.bottle.domain.PushNoticeInfo; import com.outsourcing.bottle.domain.UrlConfig; import com.outsourcing.bottle.remoteimage.RemoteImageView; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.BasicUIEvent; import com.outsourcing.bottle.util.HttpUtils; import com.outsourcing.bottle.util.ImageLoader; import com.outsourcing.bottle.util.ImageThumbnail; import com.outsourcing.bottle.util.ServiceUtils; import com.outsourcing.bottle.util.TextUtil; import com.outsourcing.bottle.util.UICore; import com.outsourcing.bottle.util.Utility; import com.outsourcing.bottle.widget.CustomPopupWindow; import com.outsourcing.bottle.widget.TryRefreshableView; public class ExchangePicFeedDetailActivity extends BasicActivity implements BasicUIEvent, Callback, OnClickListener { private final int menu_uploadphoto = 105; private final int menu_exprofile = 104; private final int menu_exphoto = 103; private final int menu_gainbt = 102; private final int menu_sendbt = 101; private final int user_baseinfo_notfull = 100; private final int complete_info = 1; private static final int EXEU_EXCHANGE_PIC_INFO = 0; private static final int EXEU_EXCHANGE_PIC_INFO_FAILED = 1; private static final int EXEU_REFRESH_PIC_INFO = 2; private static final int EXEU_LIKE_OPERATION = 3; private static final int EXEU_UNLIKE_OPERATION = 4; private static final int EXEU_LIKE_OP_PICEX_SUCCESS = 5; private static final int EXEU_LIKE_OP_PICEX_FAILED = 6; protected static final int REQUESTCODE_FOR_DRAW = 7; protected static final int EXEU_ALLOW_PAINT_SUCCESS = 8; private static final int EXEU_DELETE_LOCATION = 9; private static final int EXEU_DELETE_LOCATION_SUCCESS = 10; private static final int EXEU_DELETE_LOCATION_FAILED = 11; private static final int EXEU_DELETE_LOCATION_ROOT = 12; private static final int download_image = 13; private static final String TAG = ExchangePicFeedDetailActivity.class.getSimpleName(); Handler handler; ImageView topbar_back; ImageView topbar_menu; float longitude, latidute; String location; Bitmap bitmap = null; private int ouid; private int page = 1; private int picid; private ImageLoader imageLoader; private ExchangePicFeedInfo mExPicInfo; private TryRefreshableView rv; private LinearLayout ll_content; private ScrollView sv; // private ImageView messageView; private LinearLayout bottomLayout; private ImageView avatarView; private TextView contentView; private TextView btnCount; private int newNoticeCount; private int newMessageCount; private int newBottleFeedCount; private int newExchangeFeedCount; private int newMaybeKownCount; private String message_content; private String message_avatar; private ImageLoader userImageLoader; private PushBroadcastReceiver receiver; private PushNoticeInfo pushInfo; @Override protected void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); setContentView(R.layout.exchange_pic_root); handler = new Handler(this); ouid = getIntent().getIntExtra("ouid", 0); picid = getIntent().getIntExtra("picid", 0); topbar_back = (ImageView) findViewById(R.id.topbar_back); topbar_menu = (ImageView) findViewById(R.id.topbar_menu); topbar_menu.setVisibility(View.VISIBLE); topbar_menu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ExchangePicFeedDetailActivity.this, HomeActivity.class); intent.putExtra("currentItem", 0); startActivity(intent); finish(); } }); topbar_back.setOnClickListener(this); // messageView = (ImageView) findViewById(R.id.notice_message_count); // messageView.setOnClickListener(this); bottomLayout = (LinearLayout) findViewById(R.id.notice_bottom_layout); bottomLayout.setOnClickListener(this); avatarView = (ImageView) findViewById(R.id.notice_avatar); contentView = (TextView) findViewById(R.id.notice_text); btnCount = (TextView) findViewById(R.id.notice_number); // messageView.setVisibility(View.VISIBLE); // refresh_view = (ElasticScrollView) findViewById(R.id.refresh_view); // refresh_view.setonRefreshListener(new // ElasticScrollView.OnRefreshListener() { // // // @Override // public void onRefresh() { // page =1; // UICore.eventTask(ExchangePicFeedDetailActivity.this, // ExchangePicFeedDetailActivity.this, EXEU_REFRESH_PIC_INFO, null, // null); // } // }); imageLoader = new ImageLoader(this, AppContext.BottleTimelineIcon); userImageLoader = new ImageLoader(this, AppContext.UserAvatarIcon); sv = (ScrollView) findViewById(R.id.trymySv); rv = (TryRefreshableView) findViewById(R.id.trymyRV); rv.mfooterView = (View) findViewById(R.id.tryrefresh_footer); rv.sv = sv; ll_content = (LinearLayout) findViewById(R.id.ll_content); // 隐藏mfooterView rv.mfooterViewText = (TextView) findViewById(R.id.tryrefresh_footer_text); rv.mfooterViewText.setVisibility(View.INVISIBLE); // 监听是否加载刷新 rv.setRefreshListener(new TryRefreshableView.RefreshListener() { @Override public void onRefresh() { if (rv.mRefreshState == 4) { page = 1; UICore.eventTask(ExchangePicFeedDetailActivity.this, ExchangePicFeedDetailActivity.this, EXEU_REFRESH_PIC_INFO, null, null); } else if (rv.mfooterRefreshState == 4) { page = 1; UICore.eventTask(ExchangePicFeedDetailActivity.this, ExchangePicFeedDetailActivity.this, EXEU_REFRESH_PIC_INFO, null, null); } } }); initLikePopupWindow(); initSateMenu(); UICore.eventTask(this, this, EXEU_EXCHANGE_PIC_INFO, "", null); } private void initSateMenu() { SatelliteMenu menu = (SatelliteMenu) findViewById(R.id.menu); menu.setVisibility(View.VISIBLE); if (CanvasWidth >= 480) { menu.setSatelliteDistance(200); } else { menu.setSatelliteDistance(100); } List<SatelliteMenuItem> items = new ArrayList<SatelliteMenuItem>(); items.add(new SatelliteMenuItem(menu_exprofile, R.drawable.menu_exprofile)); items.add(new SatelliteMenuItem(menu_exphoto, R.drawable.menu_exphoto)); items.add(new SatelliteMenuItem(menu_gainbt, R.drawable.menu_gainbt)); items.add(new SatelliteMenuItem(menu_sendbt, R.drawable.menu_sendbt)); items.add(new SatelliteMenuItem(menu_uploadphoto, R.drawable.menu_uploadphoto)); menu.addItems(items); menu.setOnItemClickedListener(new SateliteClickedListener() { public void eventOccured(int id) { switch (id) { case menu_sendbt: // 扔瓶子 new Thread() { public void run() { try { Thread.sleep(500); Intent throwIntent = new Intent( ExchangePicFeedDetailActivity.this, ChooseBottleActivity.class); throwIntent.putExtra("type", "throw"); startActivity(throwIntent); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; case menu_gainbt: // 捞瓶子 new Thread() { public void run() { try { Thread.sleep(500); Intent tryIntent = new Intent( ExchangePicFeedDetailActivity.this, ChooseBottleActivity.class); tryIntent.putExtra("type", "try"); startActivity(tryIntent); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; case menu_exphoto: // 交换照片 new Thread() { public void run() { try { Thread.sleep(500); Intent exchangeInfoIntent = new Intent( ExchangePicFeedDetailActivity.this, ChooseFriendActivity.class); exchangeInfoIntent .putExtra( "choose_friend_type", AppContext.CHOOSE_FRIEND_EXCHANGE_PHOTO_TYPE); startActivity(exchangeInfoIntent); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; case menu_exprofile: // 交换资料 new Thread() { public void run() { try { Thread.sleep(500); LoginUserInfoTable userTable = new LoginUserInfoTable(); LoginUserInfoEntry userEntry = userTable .getLoginUserInfo(AppContext .getInstance().getLogin_uid()); if (userEntry.getBasicinfo_fullfill() == 0) { handler.sendEmptyMessage(user_baseinfo_notfull); } else { Intent exchangeFileIntent = new Intent( ExchangePicFeedDetailActivity.this, ChooseFriendActivity.class); exchangeFileIntent .putExtra( "choose_friend_type", AppContext.CHOOSE_FRIEND_EXCHANGE_INFO_TYPE); startActivity(exchangeFileIntent); } } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; case menu_uploadphoto: new Thread() { public void run() { try { Thread.sleep(500); Intent intent = new Intent(ExchangePicFeedDetailActivity.this, ExpandEditActivity.class); Bundle extras = new Bundle(); extras.putString("from_type", AppContext.UPLOAD_PHOTO); extras.putInt("albumid", 0); extras.putInt("ouid", AppContext.getInstance().getLogin_uid()); intent.putExtras(extras); startActivity(intent); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; default: break; } } }); } @Override protected void onResume() { super.onResume(); if(AppContext.getInstance().isFromExchangePicDetail()){ AppContext.getInstance().setFromExchangePicDetail(false); page = 1; UICore.eventTask(this, this, EXEU_REFRESH_PIC_INFO, "", null); } } @Override public void execute(int mes, Object obj) { switch (mes) { case EXEU_EXCHANGE_PIC_INFO: getExchangePicFeed(ouid, page, picid); break; case EXEU_REFRESH_PIC_INFO: refreshExchangePicFeed(ouid, page, picid); break; case EXEU_LIKE_OPERATION: likeIOperationPicex(ouid, picid, 0); break; case EXEU_UNLIKE_OPERATION: likeIOperationPicex(ouid, picid, 1); break; case EXEU_ALLOW_PAINT_SUCCESS: int optype = (Integer)obj; setExpicPaint(ouid,picid,optype); break; case EXEU_DELETE_LOCATION: ExFeedInfoEntry mExFeedPicEntry = (ExFeedInfoEntry)obj; deleteLocation(String.valueOf(mExFeedPicEntry.getLocation_objtype_2()),String.valueOf(mExFeedPicEntry.getLocation_objid_2())); break; case EXEU_DELETE_LOCATION_ROOT: ExchangePicInfoEntry mExEntry = (ExchangePicInfoEntry)obj; deleteLocation(String.valueOf(mExEntry.getLocation_objtype()),String.valueOf(mExEntry.getLocation_objid())); break; default: break; } } private void setExpicPaint(int ouid, int picid,int optype) { StringBuffer url = new StringBuffer(UrlConfig.set_expic_paint); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); url.append("&picid=" + picid); url.append("&optype=" + optype); try { String result = HttpUtils.doGet(url.toString()); if (result != null) { JSONObject object = new JSONObject(result); JSONObject resultObj = object.getJSONObject("results"); int authok = resultObj.getInt("success"); if (authok == 0) { String errmsg = resultObj.getString("errmsg"); Message msg = Message.obtain(handler, EXEU_EXCHANGE_PIC_INFO_FAILED, errmsg); handler.sendMessage(msg); } else { String successmsg = resultObj.getString("successmsg"); Message msg = Message.obtain(handler, EXEU_ALLOW_PAINT_SUCCESS, successmsg); handler.sendMessage(msg); } } } catch (Exception e) { e.printStackTrace(); } } private void likeIOperationPicex(int ouid, int picid, int liketype) { StringBuffer url = new StringBuffer(UrlConfig.likeop_picex); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); url.append("&picid=" + picid); url.append("&liketype=" + liketype); ServiceUtils.dout("likeIOperationPicex url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); ServiceUtils.dout("likeIOperationPicex result:" + results); if (null != results) { JSONObject obj = new JSONObject(results); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); String errmsg = resultObj.getString("errmsg"); String successmsg = resultObj.getString("successmsg"); if (success == 1) { Message message = handler.obtainMessage( EXEU_LIKE_OP_PICEX_SUCCESS, successmsg); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_LIKE_OP_PICEX_FAILED, errmsg); handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); } } View view = null; private View mLikeView; private CustomPopupWindow mLikePopview; private ImageView bigImageView ; ExchangePicInfoEntry exPicOuidEntry; private Bitmap imageBitmap; private void setViewValue() { view = LayoutInflater.from(this).inflate( R.layout.exchange_pic_feed_detail, null); RemoteImageView iv_ovatar_2 = (RemoteImageView) view .findViewById(R.id.iv_ex_pic_ovatar_2); TextView tv_ex_feed = (TextView) view.findViewById(R.id.tv_ex_feed); TextView tv_feed_time = (TextView) view.findViewById(R.id.tv_feed_time); TextView tv_comment = (TextView) view .findViewById(R.id.comments_ellipsis_text); RemoteImageView iv_ovatar_right = (RemoteImageView) view .findViewById(R.id.iv_ex_pic_ovatar_3); RelativeLayout content_photo = (RelativeLayout) view .findViewById(R.id.rl_bottle_content_photo); bigImageView = (ImageView) view.findViewById(R.id.photo); Button bt_ex_comment = (Button) view.findViewById(R.id.bt_pic_comment); Button bt_ex_forward = (Button) view.findViewById(R.id.bt_pic_forward); LinearLayout feed_comment = (LinearLayout) view .findViewById(R.id.ll_feed_comment_content); exPicOuidEntry = mExPicInfo.getPic_info(); iv_ovatar_2.setDefaultImage(R.drawable.avatar_default_small); iv_ovatar_2.setImageUrl(exPicOuidEntry.getSavatar()); iv_ovatar_right.setDefaultImage(R.drawable.avatar_default_small); iv_ovatar_right.setImageUrl(exPicOuidEntry.getRavatar()); iv_ovatar_2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent spaceIntent = new Intent(ExchangePicFeedDetailActivity.this, UserSpaceActivity.class); spaceIntent.putExtra("ouid", exPicOuidEntry.getSuid()); startActivity(spaceIntent); } }); iv_ovatar_right.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent spaceIntent = new Intent(ExchangePicFeedDetailActivity.this, UserSpaceActivity.class); spaceIntent.putExtra("ouid", exPicOuidEntry.getRuid()); startActivity(spaceIntent); } }); String nickName = null; if (ouid!= AppContext.getInstance() .getLogin_uid()) { nickName ="<font color='#DA4A37'>" + exPicOuidEntry.getSnickname() + "</font>"; } else { nickName = "<font color='#3F99D8'>" + exPicOuidEntry.getSnickname() + "</font>"; } tv_ex_feed.setText(Html.fromHtml(nickName + exPicOuidEntry.getExfeed_send_content())); if ((null != exPicOuidEntry.getExfeed_send_time() && exPicOuidEntry .getExfeed_send_time().length() > 0) || (null != exPicOuidEntry.getExfeed_send_location() && exPicOuidEntry .getExfeed_send_location().length() > 0)) { tv_feed_time.setVisibility(View.VISIBLE); String time = (null != exPicOuidEntry.getExfeed_send_time() && exPicOuidEntry .getExfeed_send_time().length() > 0) ? (" #" + exPicOuidEntry.getExfeed_send_time()): ""; String location = (null != exPicOuidEntry.getExfeed_send_location() && exPicOuidEntry .getExfeed_send_location().length() > 0) ? (" @"+exPicOuidEntry .getExfeed_send_location()) : ""; tv_feed_time.setText(time + location); if (!TextUtils.isEmpty(location)) { tv_feed_time.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(exPicOuidEntry.getLocation_delete_enable() == 1){ final Context dialogContext = new ContextThemeWrapper( ExchangePicFeedDetailActivity.this, android.R.style.Theme_Light); String[] choices = new String[2]; choices[0] = getString(R.string.bottle_txt_check_location); choices[1] = getString(R.string.bottle_txt_clean_location); final ListAdapter adapter = new ArrayAdapter<String>( dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems( adapter, -1, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { dialog.dismiss(); if (which == 0) { dialog.dismiss(); Intent intent = new Intent( ExchangePicFeedDetailActivity.this, MapViewActivity.class); intent.putExtra("longitude", exPicOuidEntry.getExfeed_send_lng()); intent.putExtra("latidute", exPicOuidEntry.getExfeed_send_lat()); intent.putExtra("location", exPicOuidEntry.getExfeed_send_location()); startActivity(intent); } else { UICore.eventTask(ExchangePicFeedDetailActivity.this, ExchangePicFeedDetailActivity.this, EXEU_DELETE_LOCATION_ROOT, "", exPicOuidEntry); } } }); builder.create().show(); } else { final Context dialogContext = new ContextThemeWrapper( ExchangePicFeedDetailActivity.this, android.R.style.Theme_Light); String[] choices = new String[1]; choices[0] = getString(R.string.bottle_txt_check_location); final ListAdapter adapter = new ArrayAdapter<String>( dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { dialog.dismiss(); Intent intent = new Intent( ExchangePicFeedDetailActivity.this, MapViewActivity.class); intent.putExtra("longitude", exPicOuidEntry.getExfeed_send_lng()); intent.putExtra("latidute", exPicOuidEntry.getExfeed_send_lat()); intent.putExtra("location", exPicOuidEntry.getExfeed_send_location()); startActivity(intent); } }); builder.create().show();} } }); } } else { tv_feed_time.setVisibility(View.GONE); } if (null != exPicOuidEntry.getExfeed_send_comment() && exPicOuidEntry.getExfeed_send_comment().length() > 0) { String commentTips = "<font color='#000000'>" + TextUtil.R("exchange_feed_comment_title") + "</font>"; tv_comment.setText(Html.fromHtml(commentTips + TextUtil.htmlEncode(exPicOuidEntry.getExfeed_send_comment()))); } else { } LinearLayout comment_button_like = (LinearLayout) view .findViewById(R.id.comment_button_like); if (!TextUtils.isEmpty(exPicOuidEntry.getExfeed_pic())) { content_photo.setVisibility(View.VISIBLE); Button bt_drawing = (Button)view.findViewById(R.id.bt_drawing); Button bt_allow_draw = (Button)view.findViewById(R.id.bt_allow_draw); ServiceUtils.dout(TAG+" Exfeed_pic_big:"+exPicOuidEntry.getExfeed_pic_big()); // imageLoader.DisplayImage(exPicOuidEntry.getExfeed_pic_big(), photo, // R.drawable.photo_wrapper); new Thread() { public void run() { downloadImage(); }; }.start(); bigImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!TextUtils.isEmpty(exPicOuidEntry.getExfeed_pic_tuya())) { showCommentPicFeedDialog(exPicOuidEntry); }else { byte[] tempBytes = null; try { String filename = ServiceUtils.convertUrlToFileName(exPicOuidEntry.getExfeed_pic()); tempBytes = ServiceUtils.readStream(new FileInputStream(new File( android.os.Environment.getExternalStorageDirectory() + "/" + AppContext.BottleTimelineIcon + "/" + filename))); } catch (Exception e) { e.printStackTrace(); } Intent bigPicIntent = new Intent(ExchangePicFeedDetailActivity.this, PhotoDetailActivity.class); bigPicIntent.putExtra("pic_big", exPicOuidEntry.getExfeed_pic_big()); bigPicIntent.putExtra("thumbnail", tempBytes); ExchangePicFeedDetailActivity.this.startActivity(bigPicIntent); } } }); if (exPicOuidEntry.getExfeed_pic_allowtuya() == 1) { (view.findViewById(R.id.ll_layout_drawing)).setVisibility(View.VISIBLE); bt_drawing.setVisibility(View.VISIBLE); bt_drawing.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); byte[] tempBytes = baos.toByteArray(); File file = Utility.getNextFileName(); FileOutputStream fs = null; try { fs = new FileOutputStream(file); fs.write(tempBytes); } catch (IOException e) { e.printStackTrace(); } finally { try { if (null != fs) { fs.close(); } } catch (IOException e) { e.printStackTrace(); } } File resultfile = Utility.getNextFileName(); Uri fileUri = Uri.fromFile(resultfile); Intent newIntent = new Intent( ExchangePicFeedDetailActivity.this, FeatherActivity.class ); newIntent.putExtra( "From_Type", Constants.ACTIVITY_DRAW ); newIntent.setData( fileUri ); newIntent.putExtra( "API_KEY", Utility.API_KEY ); newIntent.putExtra( "output", Uri.parse( "file://" + resultfile.getAbsolutePath() ) ); newIntent.putExtra( Constants.EXTRA_OUTPUT_FORMAT, Bitmap.CompressFormat.JPEG.name() ); newIntent.putExtra( Constants.EXTRA_OUTPUT_QUALITY, 100 ); newIntent.putExtra( Constants.EXTRA_TOOLS_DISABLE_VIBRATION, true ); final DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics( metrics ); int max_size = Math.min( metrics.widthPixels, metrics.heightPixels ); max_size = (int) ( (double) max_size / 0.8 ); newIntent.putExtra( "max-image-size", max_size ); newIntent.putExtra( "effect-enable-borders", true ); // mSessionId = StringUtils.getSha256( System.currentTimeMillis() + Utility.API_KEY ); // newIntent.putExtra( "output-hires-session-id", mSessionId ); // startActivity(newIntent); startActivityForResult(newIntent, REQUESTCODE_FOR_DRAW); overridePendingTransition(R.anim.translate_right_in, R.anim.translate_left_in); } }); }else { bt_drawing.setVisibility(View.GONE); } if (exPicOuidEntry.getExfeed_pic_enabletuya()== 0) { bt_allow_draw.setVisibility(View.GONE); }else { (view.findViewById(R.id.ll_layout_drawing)).setVisibility(View.VISIBLE); bt_allow_draw.setVisibility(View.VISIBLE); if (exPicOuidEntry.getExfeed_pic_enabletuya()== 1) { bt_allow_draw.setText(TextUtil.R("bottle_txt_allow_draw")); bt_allow_draw.setBackgroundResource(R.drawable.btn_red_try); bt_allow_draw.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //TODO 允许涂鸦 UICore.eventTask(ExchangePicFeedDetailActivity.this, ExchangePicFeedDetailActivity.this, EXEU_ALLOW_PAINT_SUCCESS, "", 1); } }); }else { bt_allow_draw.setText(TextUtil.R("bottle_txt_not_allow_draw")); bt_allow_draw.setBackgroundResource(R.drawable.btn_gray_try); bt_allow_draw.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { UICore.eventTask(ExchangePicFeedDetailActivity.this, ExchangePicFeedDetailActivity.this, EXEU_ALLOW_PAINT_SUCCESS, "", 0); } }); } } } else { content_photo.setVisibility(View.GONE); } if (exPicOuidEntry.getExfeed_like_enable() == 1) { comment_button_like.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.photo_pill)); comment_button_like .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showInfoPopupWindow(v,picid,ouid); } }); } else { comment_button_like .setBackgroundDrawable(this.getResources().getDrawable(R.drawable.photo_pill_dark)); } ImageView mLikeIcon = (ImageView) view .findViewById(R.id.comment_button_like_icon); switch (exPicOuidEntry.getExfeed_pic_liked()) { case 0: mLikeIcon .setImageResource(R.drawable.like_gray2); break; case 1: mLikeIcon .setImageResource(R.drawable.like_red2); break; case 2: mLikeIcon .setImageResource(R.drawable.like_black2); break; default: break; } bt_ex_comment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent commentIntent = new Intent( ExchangePicFeedDetailActivity.this, ExpandEditActivity.class); Bundle commentBundle = new Bundle(); commentBundle.putString("from_type", AppContext.REPLYPIC_PICEX); commentBundle.putInt("ouid", ouid); commentBundle.putInt("picid", picid); commentIntent.putExtras(commentBundle); startActivityForResult(commentIntent, 0); } }); if (exPicOuidEntry.getExfeed_forward_enable() == 1) { bt_ex_forward.setVisibility(View.VISIBLE); bt_ex_forward.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent friendIntent = new Intent( ExchangePicFeedDetailActivity.this, ChooseFriendActivity.class); friendIntent.putExtra("choose_friend_type", AppContext.CHOOSE_FRIEND_FORWARD_PHOTO_TYPE); friendIntent.putExtra("picid", picid); friendIntent.putExtra("pic_uid", ouid); startActivity(friendIntent); AppContext.getInstance().setFromExchangePicDetail(true); } }); } else { bt_ex_forward.setVisibility(View.GONE); } /******************************* 留言分割线 ***********************************/ List<ExFeedInfoEntry> mExFeedPicEntries = mExPicInfo.getExfeeds_list(); if (null != mExFeedPicEntries && mExFeedPicEntries.size() > 0) { for (int j = 0; j < mExFeedPicEntries.size(); j++) { final ExFeedInfoEntry mExFeedPicEntry = mExFeedPicEntries .get(j); View feed_child = LayoutInflater.from(this).inflate( R.layout.exchange_pic_feed_item, null); RemoteImageView mFeedCommentAvatar = (RemoteImageView) feed_child .findViewById(R.id.comment_profile_photo); ImageView link = (ImageView) feed_child .findViewById(R.id.iv_feed_comment_white); TextView tv_nickName = (TextView) feed_child .findViewById(R.id.tv_feed_comment_nickname); TextView tv_location = (TextView) feed_child .findViewById(R.id.tv_feed_comment_time); try { mFeedCommentAvatar.setDefaultImage(R.drawable.avatar_default_small); mFeedCommentAvatar.setImageUrl(mExFeedPicEntry.getExfeed_avatar()); } catch (Exception e) { e.printStackTrace(); mFeedCommentAvatar .setImageResource(R.drawable.avatar_default_small); } mFeedCommentAvatar .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent spaceIntent = new Intent(ExchangePicFeedDetailActivity.this, UserSpaceActivity.class); spaceIntent.putExtra("ouid", mExFeedPicEntry.getExfeed_uid()); startActivity(spaceIntent); } }); String feed_name = null; String comment = null; if (mExFeedPicEntry.getExfeed_uid()!= AppContext.getInstance() .getLogin_uid()) { feed_name = (!TextUtils.isEmpty(mExFeedPicEntry.getExfeed_nickname())) ? ("<font color='#DA4A37'>" + mExFeedPicEntry.getExfeed_nickname()+ "</font>") : ""; } else { feed_name = (!TextUtils.isEmpty(mExFeedPicEntry.getExfeed_nickname())) ? ("<font color='#3F99D8'>" + mExFeedPicEntry.getExfeed_nickname() + "</font>") : ""; } // 动态(0)、评论(1)、是喜欢动态(2)、是不喜欢动态(3) switch (mExFeedPicEntry.getExfeed_type()) { case 0: link.setImageResource(R.drawable.feed_gray); comment = mExFeedPicEntry.getExfeed_isnew() == 1 ? ("<font color='#DA4A37'>" + TextUtil.htmlEncode(mExFeedPicEntry.getExfeed_content()) + "</font>") : TextUtil.htmlEncode(mExFeedPicEntry.getExfeed_content()); tv_nickName.setText(Html.fromHtml(feed_name +comment)); break; case 1: link.setVisibility(View.GONE); comment = mExFeedPicEntry.getExfeed_isnew() == 1 ? ("<font color='#DA4A37'>" + TextUtil.htmlEncode(mExFeedPicEntry.getExfeed_comment()) + "</font>") : TextUtil.htmlEncode(mExFeedPicEntry.getExfeed_comment()); tv_nickName.setText(Html.fromHtml(feed_name + comment)); break; case 2: link.setImageResource(R.drawable.like_red3); comment = mExFeedPicEntry.getExfeed_isnew() == 1 ? ("<font color='#DA4A37'>" + TextUtil.htmlEncode(mExFeedPicEntry.getExfeed_content()) + "</font>") : TextUtil.htmlEncode(mExFeedPicEntry.getExfeed_content()); tv_nickName.setText(Html.fromHtml(feed_name + comment)); break; case 3: link.setImageResource(R.drawable.like_black3); comment = mExFeedPicEntry.getExfeed_isnew() == 1 ? ("<font color='#DA4A37'>" + TextUtil.htmlEncode(mExFeedPicEntry.getExfeed_content()) + "</font>") : TextUtil.htmlEncode(mExFeedPicEntry.getExfeed_content()); tv_nickName.setText(Html.fromHtml(feed_name + comment)); break; default: break; } String timeComent = (mExFeedPicEntry.getExfeed_time() != null && mExFeedPicEntry .getExfeed_time().length() > 0) ? ("<font color='#666666'>" + "#" + mExFeedPicEntry.getExfeed_time() + "</font>") : ""; final String location = (mExFeedPicEntry.getExfeed_location() != null && mExFeedPicEntry .getExfeed_location().length() > 0) ? ("<font color='#666666'>" + "@" + mExFeedPicEntry.getExfeed_location() + "</font>") : ""; tv_location.setText(Html.fromHtml(timeComent + location)); if (!TextUtils.isEmpty(location)) { tv_location.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(location.length()>0){ if(mExFeedPicEntry.getLocation_delete_enable_2() == 1){ final Context dialogContext = new ContextThemeWrapper( ExchangePicFeedDetailActivity.this, android.R.style.Theme_Light); String[] choices = new String[2]; choices[0] = getString(R.string.bottle_txt_check_location); choices[1] = getString(R.string.bottle_txt_clean_location); final ListAdapter adapter = new ArrayAdapter<String>( dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems( adapter, -1, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { dialog.dismiss(); if (which == 0) { dialog.dismiss(); Intent intent = new Intent( ExchangePicFeedDetailActivity.this, MapViewActivity.class); intent.putExtra("longitude", mExFeedPicEntry .getExfeed_lng()); intent.putExtra("latidute", mExFeedPicEntry .getExfeed_lat()); intent.putExtra( "location", mExFeedPicEntry .getExfeed_location()); startActivity(intent); } else { UICore.eventTask(ExchangePicFeedDetailActivity.this, ExchangePicFeedDetailActivity.this, EXEU_DELETE_LOCATION, "", mExFeedPicEntry); } } }); builder.create().show(); } else { final Context dialogContext = new ContextThemeWrapper( ExchangePicFeedDetailActivity.this, android.R.style.Theme_Light); String[] choices = new String[1]; choices[0] = getString(R.string.bottle_txt_check_location); final ListAdapter adapter = new ArrayAdapter<String>( dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { dialog.dismiss(); Intent intent = new Intent( ExchangePicFeedDetailActivity.this, MapViewActivity.class); intent.putExtra("longitude", mExFeedPicEntry .getExfeed_lng()); intent.putExtra("latidute", mExFeedPicEntry .getExfeed_lat()); intent.putExtra( "location", mExFeedPicEntry .getExfeed_location()); startActivity(intent); } }); builder.create().show(); } } } }); } feed_comment.addView(feed_child); } } ll_content.addView(view); rv.mfooterViewText.setVisibility(View.VISIBLE); } public void showInfoPopupWindow(View achorView, int picid, int ouid) { this.ouid = ouid; this.picid = picid; if (mLikePopview.isShowing()) { mLikePopview.dismiss(); } else { // mLikePopview.showAtLocation(achorView, Gravity.RIGHT, 0, 0); mLikePopview.showAsDropDown(achorView, 60, -60); } } /** 喜欢pop */ private void initLikePopupWindow() { LayoutInflater mLayoutInflater = LayoutInflater.from(this); mLikeView = mLayoutInflater.inflate(R.layout.pop_bottle_like_left, null); ImageView iv_unlike = (ImageView) mLikeView .findViewById(R.id.iv_unlike); ImageView iv_like = (ImageView) mLikeView.findViewById(R.id.iv_like); iv_unlike.setOnClickListener(this); iv_like.setOnClickListener(this); mLikePopview = new CustomPopupWindow(mLikeView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); mLikePopview.setBackgroundDrawable(getResources().getDrawable( R.drawable.like_frame_left)); mLikePopview.setOutsideTouchable(true); mLikePopview.update(); mLikePopview.setTouchable(true); mLikePopview.setFocusable(true); } private void getExchangePicFeed(int ouid, int page, int picid) { StringBuffer url = new StringBuffer(UrlConfig.get_picex_picfeeds); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); url.append("&picid=" + picid); url.append("&count=20"); url.append("&page=" + page); ServiceUtils.dout("getExchangePicFeed url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); if (results == null) { return; } ServiceUtils.dout("getExchangePicFeed results:" + results); Gson gson = new Gson(); mExPicInfo = gson.fromJson(results, ExchangePicFeedInfo.class); if (mExPicInfo.getResults().getAuthok() == 1) { PushNoticeInfoTable table = new PushNoticeInfoTable(); pushInfo = table.getPushNoticeInfo(AppContext.getInstance().getLogin_uid()); if (null!=pushInfo) { newBottleFeedCount = pushInfo.getNew_btfeed_count(); newExchangeFeedCount = pushInfo.getNew_exfeed_count(); newMessageCount = pushInfo.getNew_message_count(); newNoticeCount = pushInfo.getNew_notice_count(); message_content = pushInfo.getMessage_content(); message_avatar = pushInfo.getMessage_avatar(); newMaybeKownCount = pushInfo.getNew_maybeknow_count(); } Message message = handler.obtainMessage(EXEU_EXCHANGE_PIC_INFO, mExPicInfo.getResults().getErrmsg()); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_EXCHANGE_PIC_INFO_FAILED, mExPicInfo.getResults() .getErrmsg()); handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } private void refreshExchangePicFeed(int ouid, int page, int picid) { StringBuffer url = new StringBuffer(UrlConfig.get_picex_picfeeds); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); url.append("&picid=" + picid); url.append("&count=20"); url.append("&page=" + page); ServiceUtils.dout("getExchangePicFeed url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); if (results == null) { return; } ServiceUtils.dout("getExchangePicFeed results:" + results); Gson gson = new Gson(); mExPicInfo = gson.fromJson(results, ExchangePicFeedInfo.class); if (mExPicInfo.getResults().getAuthok() == 1) { Message message = handler.obtainMessage(EXEU_REFRESH_PIC_INFO, mExPicInfo.getResults().getErrmsg()); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_EXCHANGE_PIC_INFO_FAILED, mExPicInfo.getResults() .getErrmsg()); handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } @Override protected void onDestroy() { super.onDestroy(); } @Override public boolean handleMessage(Message msg) { switch (msg.what) { case EXEU_EXCHANGE_PIC_INFO: setViewValue(); pushNoticeUpdateUI(); receiver = new PushBroadcastReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction("push"); registerReceiver(receiver, filter); break; case EXEU_REFRESH_PIC_INFO: // refresh_view.removeChild(view); ll_content.removeAllViews(); setViewValue(); // refresh_view.onRefreshComplete(); rv.finishRefresh(); break; case EXEU_EXCHANGE_PIC_INFO_FAILED: onToast((String) msg.obj); break; case EXEU_LIKE_OP_PICEX_SUCCESS: onToast((String) msg.obj); UICore.eventTask(this, this, EXEU_REFRESH_PIC_INFO, "", null); break; case EXEU_LIKE_OP_PICEX_FAILED: onToast((String) msg.obj); UICore.eventTask(this, this, EXEU_REFRESH_PIC_INFO, "", null); break; case user_baseinfo_notfull: LoginUserInfoTable userTable = new LoginUserInfoTable(); LoginUserInfoEntry userEntry = userTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid()); showChoseMes(userEntry.getBasicinfo_tip(), complete_info); break; case EXEU_ALLOW_PAINT_SUCCESS: UICore.eventTask(this, this, EXEU_REFRESH_PIC_INFO, "", null); break; case EXEU_DELETE_LOCATION_SUCCESS: if (!TextUtils.isEmpty((String) msg.obj)) { onToast((String) msg.obj); } UICore.eventTask(this, this, EXEU_REFRESH_PIC_INFO, "", null); break; case EXEU_DELETE_LOCATION_FAILED: onToast((String) msg.obj); break; case download_image: Bitmap tempBP = (Bitmap) msg.obj; view.findViewById(R.id.rl_bottle_content_photo).setVisibility(View.VISIBLE); view.findViewById(R.id.pull_to_refresh_progress).setVisibility(View.GONE); bigImageView.setVisibility(View.VISIBLE); if (imageBitmap != null) { bigImageView.setImageBitmap(tempBP); } break; default: break; } return false; } private void downloadImage() { Bitmap tempBitmap = null; if (imageBitmap == null) { imageBitmap = HttpUtils.getBitmapFromUrl(ExchangePicFeedDetailActivity.this, exPicOuidEntry.getExfeed_pic_big()); } if (null != imageBitmap && imageBitmap.getWidth() > CanvasWidth) { float scale = ImageThumbnail.reckonThumbnail( imageBitmap.getWidth(), imageBitmap.getHeight(), CanvasWidth - 20, 0); tempBitmap = ImageThumbnail.PicZoom(imageBitmap, (int) (imageBitmap.getWidth() / scale), (int) (imageBitmap.getHeight() / scale)); } else { tempBitmap = imageBitmap; } Message message = handler.obtainMessage(download_image, tempBitmap); handler.sendMessage(message); } @Override public void sysMesPositiveButtonEvent(int what) { if (what == complete_info) { Intent intent = new Intent(this, SettingActivity.class); startActivity(intent); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.topbar_back: finish(); break; case R.id.iv_unlike:// 不喜欢 mLikePopview.dismiss(); UICore.eventTask(this, this, EXEU_UNLIKE_OPERATION, "", null); break; case R.id.iv_like:// 喜欢 mLikePopview.dismiss(); UICore.eventTask(this, this, EXEU_LIKE_OPERATION, "", null); break; // case R.id.notice_message_count: // doMessageAction(); // break; case R.id.notice_bottom_layout: doFeedsAction(); break; default: break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // refresh_view.removeChild(view); if (null != data) { if (data.getBooleanExtra("need_refresh", false)) { page = 1; UICore.eventTask(this, this, EXEU_REFRESH_PIC_INFO, "", null); } } if (resultCode == RESULT_OK) { if(REQUESTCODE_FOR_DRAW == requestCode){ Intent commentIntent = new Intent(this, ExpandEditActivity.class); Bundle commentBundle = new Bundle(); commentBundle.putString("from_type", AppContext.PAINT_PICEX); commentBundle.putInt("ouid", ouid); commentBundle.putInt("picid", picid); commentBundle.putString("return_type", ExchangePicFeedDetailActivity.class.getSimpleName()); commentIntent.putExtras(commentBundle); startActivity(commentIntent); } } } public void doMessageAction() { final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light); String[] choices = new String[2]; if (newNoticeCount > 0) { choices[0] = newNoticeCount + getString(R.string.bottle_txt_notice_list); } else { choices[0] = getString(R.string.bottle_txt_notice_list); } if (newMessageCount > 0) { choices[1] = newMessageCount + getString(R.string.bottle_txt_message_list); } else { choices[1] = getString(R.string.bottle_txt_message_list); } final ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (which == 0) { Intent intent = new Intent(ExchangePicFeedDetailActivity.this, NoticeListActivity.class); startActivity(intent); } else { Intent intent = new Intent(ExchangePicFeedDetailActivity.this, MessageListActivity.class); startActivity(intent); } } }); builder.create().show(); } public void doFeedsAction() { final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light); final List<String> choices = new ArrayList<String>(); if (newBottleFeedCount > 0) { choices.add(newBottleFeedCount + getString(R.string.bottle_txt_new_bottle_feed)); } if (newExchangeFeedCount > 0) { choices.add(newExchangeFeedCount + getString(R.string.bottle_txt_new_exchange_feed)); } if (newNoticeCount > 0) { choices.add(newNoticeCount + getString(R.string.bottle_txt_notice_list)); } if (newMessageCount > 0) { choices.add(newMessageCount + getString(R.string.bottle_txt_message_list)); } if (newMaybeKownCount > 0) { choices.add(newMaybeKownCount + getString(R.string.bottle_txt_new_maybe_kown)); } final ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (choices.get(which).indexOf(getString(R.string.bottle_txt_new_bottle_feed)) != -1) { Intent intent = new Intent(ExchangePicFeedDetailActivity.this, HomeActivity.class); AppContext.getInstance().setCurrentItem(1); startActivity(intent); } else if (choices.get(which).indexOf(getString(R.string.bottle_txt_new_exchange_feed)) != -1) { Intent intent = new Intent(ExchangePicFeedDetailActivity.this, HomeActivity.class); AppContext.getInstance().setCurrentItem(0); startActivity(intent); } else if (choices.get(which).indexOf(getString(R.string.bottle_txt_notice_list)) != -1) { Intent intent = new Intent(ExchangePicFeedDetailActivity.this, NoticeListActivity.class); startActivity(intent); } else if (choices.get(which).indexOf(getString(R.string.bottle_txt_message_list)) != -1) { Intent intent = new Intent(ExchangePicFeedDetailActivity.this, MessageListActivity.class); startActivity(intent); } else if (choices.get(which).indexOf(getString(R.string.bottle_txt_new_maybe_kown)) != -1) { Intent intent = new Intent(ExchangePicFeedDetailActivity.this, HomeActivity.class); AppContext.getInstance().setCurrentItem(2); AppContext.getInstance().setGotoMaybeKown(true); startActivity(intent); } } }); builder.create().show(); } public void pushNoticeUpdateUI() { if (newBottleFeedCount + newExchangeFeedCount + newMessageCount + newNoticeCount + newMaybeKownCount > 0) { bottomLayout.setVisibility(View.VISIBLE); contentView.setText(message_content); btnCount.setText(newBottleFeedCount + newExchangeFeedCount + newMessageCount + newNoticeCount + newMaybeKownCount + ""); userImageLoader.DisplayImage(message_avatar, avatarView, R.drawable.avatar_default_big); } else { bottomLayout.setVisibility(View.GONE); } } public class PushBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); if (bundle != null) { newBottleFeedCount = bundle.getInt("bottle_feed_count"); newExchangeFeedCount = bundle.getInt("exchange_feed_count"); newMessageCount = bundle.getInt("message_count"); newNoticeCount = bundle.getInt("notice_count"); message_content = bundle.getString("message_content"); message_avatar = bundle.getString("message_avatar"); newMaybeKownCount = bundle.getInt("maybe_kown_count"); pushNoticeUpdateUI(); } } } private void showCommentPicFeedDialog(final ExchangePicInfoEntry message) { String[] choices = new String[]{TextUtil.R("bottle_txt_feed_comment_pic"),TextUtil.R("bottle_txt_feed_comment_tuya")}; final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light); final ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (which == 0) { byte[] tempBytes = null; try { String filename = ServiceUtils.convertUrlToFileName(message.getExfeed_pic()); tempBytes = ServiceUtils.readStream(new FileInputStream(new File( android.os.Environment.getExternalStorageDirectory() + "/" + AppContext.BottleTimelineIcon + "/" + filename))); } catch (Exception e) { e.printStackTrace(); } Intent bigPicIntent = new Intent(ExchangePicFeedDetailActivity.this, PhotoDetailActivity.class); bigPicIntent.putExtra("pic_big", message.getExfeed_pic_big()); bigPicIntent.putExtra("thumbnail", tempBytes); ExchangePicFeedDetailActivity.this.startActivity(bigPicIntent); } else { Intent bigPicIntent = new Intent(ExchangePicFeedDetailActivity.this, PhotoDetailActivity.class); bigPicIntent.putExtra("pic_big", message.getExfeed_pic_tuya()); startActivity(bigPicIntent); } } }); builder.create().show(); } /** * * @param objtype 要清除的位置的类型:选择项:(1)瓶子动态的位置信息、(2)交换动态留言的位置信息、(3)照片评论的位置信息、(4)私信的位置信息、(5)照片的位置信息 * @param objid objid */ private void deleteLocation(String objtype,String objid) { StringBuffer url = new StringBuffer(UrlConfig.delete_location); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&objtype=" + objtype); url.append("&objid=" + objid); ServiceUtils.dout("deleteLocation url:" + url.toString()); try { String result = HttpUtils.doGet(url.toString()); ServiceUtils.dout("deleteLocation result:" + result); JSONObject obj = new JSONObject(result); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); String errmsg = resultObj.getString("errmsg"); String successmsg = resultObj.getString("successmsg"); if (success == 1) { Message message = handler.obtainMessage( EXEU_DELETE_LOCATION_SUCCESS, successmsg); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_DELETE_LOCATION_FAILED, errmsg); handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } }
Java
package com.outsourcing.bottle.ui.fragment; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Handler.Callback; import android.os.Message; import android.support.v4.app.Fragment; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import com.outsourcing.bottle.R; import com.outsourcing.bottle.domain.LocationEntry; import com.outsourcing.bottle.domain.PlatformBindConfig; import com.outsourcing.bottle.domain.UrlConfig; import com.outsourcing.bottle.ui.BottleTipsActivity; import com.outsourcing.bottle.ui.ChooseLocationTabsActivity; import com.outsourcing.bottle.ui.ThrowBottleSettingActivity; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.BasicUIEvent; import com.outsourcing.bottle.util.HttpUtils; import com.outsourcing.bottle.util.UICore; /** * * @author 06peng * */ public class CityFragment extends Fragment implements BasicUIEvent, Callback { private final int search_location = 2; private final int gain_bottle = 3; private final int gain_bottle_success = 4; private final int gain_bottle_error = 5; private final int throw_bottle = 6; private ListView listView; private ChooseLocationTabsActivity activity; private int currentItem; private List<LocationEntry> locations; private LocationAdapter adapter; private LocationEntry myLocation; private ImageView refresh; private EditText keywordView; private Handler handler; public CityFragment() { super(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); handler = new Handler(this); this.activity = (ChooseLocationTabsActivity) getActivity(); Bundle bundle = getArguments(); if (bundle != null) { currentItem = bundle.getInt("currentItem"); } UICore.eventTask(this, activity, search_location, "search_location", null); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.choose_location, null); listView = (ListView) view.findViewById(R.id.choose_location_list); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { LocationEntry entry = locations.get(arg2); if (activity.type.equals("try")) { UICore.eventTask(CityFragment.this, activity, gain_bottle, getString(R.string.init_data), entry); } else { UICore.eventTask(CityFragment.this, activity, throw_bottle, getString(R.string.init_data), entry); } } }); refresh = (ImageView) view.findViewById(R.id.choose_location_refresh); refresh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { search(); } }); keywordView = (EditText) view.findViewById(R.id.choose_location_search_edit); keywordView.setHint(R.string.choose_location_city); keywordView.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { search(); return false; } }); return view; } @Override public void onResume() { super.onResume(); adapter = new LocationAdapter(); listView.setAdapter(adapter); } @Override public void execute(int mes, Object obj) { switch (mes) { case search_location: locate(); getSearchLocation(obj == null ? "" : (String)obj); handler.sendEmptyMessage(search_location); break; case gain_bottle: LocationEntry entry = (LocationEntry) obj; gainBottle(entry); break; case throw_bottle: LocationEntry entry_throw = (LocationEntry) obj; Message msg = Message.obtain(handler, throw_bottle, entry_throw); handler.sendMessage(msg); break; default: break; } } public void search() { String keyword = keywordView.getText().toString().trim(); UICore.eventTask(CityFragment.this, activity, search_location, getString(R.string.init_data), keyword); } private void locate() { myLocation = new LocationEntry(); myLocation.setLatitude(AppContext.getInstance().getLatitude()); myLocation.setLongitude(AppContext.getInstance().getLongitude()); String params = String.valueOf(AppContext.getInstance().getLatitude()) + "," + String.valueOf(AppContext.getInstance().getLongitude()); String language = AppContext.language == 1 ? "zh" : "en"; String url = "http://www.mobibottle.com/openapi/geocode_offset.json?" + "latlng="+params+"&sensor=true&language=" + language + "&login_uid=" + AppContext.getInstance().getLogin_uid(); try { String result = HttpUtils.doGet(url); JSONObject object = new JSONObject(result); JSONArray arrays = object.getJSONArray("results"); for (int i = 0;i < arrays.length();i++) { JSONObject jsonObject = arrays.getJSONObject(i); if (jsonObject != null) { JSONArray addressArrays = jsonObject.getJSONArray("address_components"); for (int j = 0;j < addressArrays.length();j++) { JSONObject obj = addressArrays.getJSONObject(j); JSONArray typeArray = obj.getJSONArray("types"); for (int k = 0;k < typeArray.length();k++) { String typename = typeArray.getString(k); if (typename.equals("locality")) { myLocation.setCity(obj.getString("long_name")); } else if (typename.equals("administrative_area_level_1")) { myLocation.setProvince(obj.getString("long_name")); } else if (typename.equals("country")) { myLocation.setCountry(obj.getString("long_name")); } } } break; } } } catch (Exception e) { e.printStackTrace(); } } private void getSearchLocation(String keyword) { String url = "http://www.mobibottle.com/openapi/google_get_autocomplete.json?"; String language = AppContext.language == 1 ? "zh" : "en" + "&login_uid=" + AppContext.getInstance().getLogin_uid(); if (currentItem == 1) { String input = keyword + "+" + myLocation.getCountry() + "+" + myLocation.getProvince() + "+" + myLocation.getCity(); url += "input=" + input + "&sensor=false&language=" + language + "&key=" + PlatformBindConfig.Goolge_Places_AppKey; } else if (currentItem == 2) { String input = keyword + "+" + myLocation.getCountry(); url += "input=" + input + "&sensor=false&language=" + language + "&key=" + PlatformBindConfig.Goolge_Places_AppKey; } else if (currentItem == 3) { url += "input=" + keyword + "&sensor=false&language=" + language + "&key=" + PlatformBindConfig.Goolge_Places_AppKey; } System.out.println(url); try { String result = HttpUtils.doGet(url); JSONObject obj = new JSONObject(result); JSONArray arrays = obj.getJSONArray("predictions"); locations = new ArrayList<LocationEntry>(); for (int i = 0;i < arrays.length();i++) { LocationEntry entry = new LocationEntry(); JSONObject object = arrays.getJSONObject(i); entry.setAddress(object.getString("description")); entry.setReference(object.getString("reference")); JSONArray typeArrays = object.getJSONArray("types"); String type = typeArrays.getString(0); entry.setType(type); JSONArray termsArrays = object.getJSONArray("terms"); JSONObject tearmObj = termsArrays.getJSONObject(0); entry.setLocationName(tearmObj.getString("value")); locations.add(entry); } } catch (Exception e) { e.printStackTrace(); } } private void gainBottle(LocationEntry entry) { String url = UrlConfig.gain_bt; HashMap<String, String> paramsMap = new HashMap<String, String>(); paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid())); paramsMap.put("login_token", AppContext.getInstance().getLogin_token()); paramsMap.put("nettypeid", String.valueOf(activity.bottleId)); paramsMap.put("bt_geo_lng", String.valueOf(entry.getLongitude())); paramsMap.put("bt_geo_lat", String.valueOf(entry.getLatitude())); paramsMap.put("bt_geo_reference", entry.getReference()); try { String result = HttpUtils.doPost(activity, url, paramsMap); JSONObject obj = new JSONObject(result); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); if (success == 1) { String successmsg = resultObj.getString("successmsg"); int gainbt_type = resultObj.getInt("gainbt_type"); String gainbt_msg = resultObj.getString("gainbt_msg"); Object[] objs = new Object[3]; objs[0] = successmsg; objs[1] = gainbt_type; objs[2] = gainbt_msg; Message msg = Message.obtain(handler, gain_bottle_success, objs); handler.sendMessage(msg); } else { String errmsg = resultObj.getString("errmsg"); Message msg = Message.obtain(handler, gain_bottle_error, errmsg); handler.sendMessage(msg); } } catch (Exception e) { e.printStackTrace(); } } public class LocationAdapter extends BaseAdapter { @Override public int getCount() { return locations == null ? 0 : locations.size(); } @Override public Object getItem(int arg0) { return locations == null ? null : locations.get(arg0); } @Override public long getItemId(int arg0) { return arg0; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view; ViewHolder holder = new ViewHolder(); if (convertView != null) { view = convertView; holder = (ViewHolder) view.getTag(); } else { view = LayoutInflater.from(activity).inflate(R.layout.choose_location_listitem, null); holder.nameView = (TextView) view.findViewById(R.id.choose_location_listitem_name); holder.vicinityView = (TextView) view.findViewById(R.id.choose_location_listitem_vicinity); holder.typeView = (TextView) view.findViewById(R.id.choose_location_listitem_type); view.setTag(holder); } LocationEntry entry = locations.get(position); if (entry != null) { holder.nameView.setText(entry.getLocationName()); holder.vicinityView.setText(entry.getAddress()); holder.typeView.setText(entry.getType()); } return view; } } public static class ViewHolder { TextView nameView; TextView vicinityView; TextView typeView; } @Override public boolean handleMessage(Message msg) { switch (msg.what) { case search_location: adapter = new LocationAdapter(); listView.setAdapter(adapter); break; case gain_bottle_error: activity.onToast((String) msg.obj); break; case gain_bottle_success: Object[] objs = (Object[]) msg.obj; activity.onToast((String) objs[0]); Intent intent = new Intent(activity, BottleTipsActivity.class); intent.putExtra("type", "try"); intent.putExtra("bottleId", Integer.parseInt(objs[1].toString())); intent.putExtra("gainbt_msg", objs[2].toString()); startActivity(intent); break; case throw_bottle: LocationEntry entry = (LocationEntry) msg.obj; Intent intent2 = new Intent(activity, ThrowBottleSettingActivity.class); intent2.putExtra("bttype_id", activity.bottleId); intent2.putExtra("bt_geo_lng", entry.getLongitude()); intent2.putExtra("bt_geo_lat", entry.getLatitude()); intent2.putExtra("reference", entry.getReference()); startActivity(intent2); break; default: break; } return false; } }
Java
package com.outsourcing.bottle.ui.fragment; import java.util.List; import org.json.JSONObject; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.Handler.Callback; import android.os.Message; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.util.Log; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.RelativeLayout; import android.widget.TextView; import com.google.gson.Gson; import com.outsourcing.bottle.BasicActivity; import com.outsourcing.bottle.R; import com.outsourcing.bottle.adapter.BTFriendListAdapter; import com.outsourcing.bottle.adapter.GroupFriendAdapter; import com.outsourcing.bottle.adapter.MaybeKnowFriendListAdapter; import com.outsourcing.bottle.adapter.MyFriendListAdapter; import com.outsourcing.bottle.db.BottleTypeTable; import com.outsourcing.bottle.db.LanguageConfigTable; import com.outsourcing.bottle.db.LoginUserInfoTable; import com.outsourcing.bottle.db.PushNoticeInfoTable; import com.outsourcing.bottle.domain.BottleFriendEntry; import com.outsourcing.bottle.domain.BottleFriendInfo; import com.outsourcing.bottle.domain.BottleTypeEntry; import com.outsourcing.bottle.domain.GroupFriendEntry; import com.outsourcing.bottle.domain.LanguageConfig; import com.outsourcing.bottle.domain.LoginUserInfoEntry; import com.outsourcing.bottle.domain.MaybeFriendEntry; import com.outsourcing.bottle.domain.MaybeKnowFriendInfo; import com.outsourcing.bottle.domain.MyFriendEntry; import com.outsourcing.bottle.domain.MyFriendInfo; import com.outsourcing.bottle.domain.PushNoticeInfo; import com.outsourcing.bottle.domain.UrlConfig; import com.outsourcing.bottle.remoteimage.RemoteImageView; import com.outsourcing.bottle.ui.AlbumsActivity; import com.outsourcing.bottle.ui.BindInviteActivity; import com.outsourcing.bottle.ui.ChooseBottleActivity; import com.outsourcing.bottle.ui.ChooseLocationTabsActivity; import com.outsourcing.bottle.ui.ExchangeInfoDetailActivity; import com.outsourcing.bottle.ui.ExchangePicDetailActivity; import com.outsourcing.bottle.ui.ExpandEditActivity; import com.outsourcing.bottle.ui.HomeActivity; import com.outsourcing.bottle.ui.ManagerGroupActivity; import com.outsourcing.bottle.ui.SettingActivity; import com.outsourcing.bottle.ui.ThrowBottleSettingActivity; import com.outsourcing.bottle.ui.UserSpaceActivity; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.BasicUIEvent; import com.outsourcing.bottle.util.HttpUtils; import com.outsourcing.bottle.util.ServiceUtils; import com.outsourcing.bottle.util.TextUtil; import com.outsourcing.bottle.util.UICore; import com.outsourcing.bottle.widget.CustomListView; /** * * @author 06peng * */ public class FriendFragment extends Fragment implements BasicUIEvent, Callback, OnClickListener, OnScrollListener { private final int user_baseinfo_notfull = 100; private final int complete_info = 1; private static final String TAG = FriendFragment.class.getSimpleName(); private static final int EXEU_GET_BTFRIEND_LIST = 0; private static final int EXEU_GET_BTFRIEND_LIST_FAILED = 1; public static final int EXEU_GET_MAYBEKONW_LIST = 2; private static final int EXEU_GET_MAYBEKONW_LIST_FAILED = 3; public static final int EXEU_GET_MYFRIEND_LIST = 4; private static final int EXEU_GET_MYFRIEND_LIST_FAILED = 5; private static final int EXEU_GET_BOTTLE_PRIV_OPERATION = 6; private static final int EXEU_SEND_BOTTLE_PRIV_SUCCESS = 7; private static final int EXEU_SEND_BOTTLE_PRIV_SUCCESS_NOT_ENABLE = 8; private static final int EXEU_SEND_BOTTLE_PRIV_FAILED = 9; private static final int EXEU_GET_BTFRIEND_TIMELINE_MORE = 10; private static final int EXEU_GOTO_TA_ALBUM = 11; private static final int EXEU_GOTO_EXCHANGE = 12; private static final int INIT_HAS_EXS_ERROR = 13; private static final int INIT_HAS_EXS_PROFILE = 14; private static final int INIT_HAS_EXS_PHOTO = 15; private static final int EXEU_GOTO_PROFILE = 16; private static final int EXEU_GOTO_PHOTO = 17; private static final int EXEU_GET_BTFRIEND_TIMELINE_NOTHING = 18; public static final int EXEU_GET_MAYBEKONW_LIST_MORE = 19; public static final int EXEU_GET_MYFRIEND_LIST_MORE = 20; private static final int EXEU_CHECK_FRIEND_FAILED = 21; private static final int EXEU_CAN_NOT_ADD_FRIEND = 22; private static final int EXEU_CHECK_FRIEND_SUCCESS = 23; private static final int EXEU_CHECK_FRIEND = 24; private static final int EXEU_ALLOW_ADD_FRIEND = 25; private final int throw_bottle_init_location = 26; private static final int EXEU_PUSH_NOTICE = 35; private static final int EXEU_GET_MAYBEKONW_LIST_NODATA = 36; private static final int EXEU_GET_BTFRIEND_LIST_NO_DATA = 37; private static final int EXEU_GET_MYFRIEND_LIST_NO_DATA = 38; private Handler handler = null; private BottleFriendInfo bottleFriendInfo = null; private MyFriendInfo myfriendInfo = null; private FrameLayout mContentView = null; private CustomListView listView = null; private View loadMoreView = null; private View mheaderView; private int page = 1; private HomeActivity activity; private BTFriendListAdapter mBtfriendAdapter = null; private MaybeKnowFriendListAdapter maybeFriendAdapter; private GroupFriendAdapter groupAdapter = null; private List<BottleFriendEntry> mBtFriendList = null; private List<MaybeFriendEntry> maybeFriendEntries = null; private List<MyFriendEntry> myFriendEntries = null; private List<GroupFriendEntry> groups_list = null; public String[] groupNames; public int groupItem; private int visibleLastIndex = 0; // 最后的可视项索引 private int visibleItemCount; // 当前窗口可见项总数 /** 记录当前页面是在哪个分类 */ private int state; private int adapter_type; //listadapter 的类型 public int getState() { return state; } public void setState(int state) { this.state = state; } public boolean init = false; private int btId; private int btTypeId; private int ouid; private int groupid = -1; /** * AppContext.CHOOSE_FRIEND_EXCHANGE_PHOTO_TYPE/AppContext. * CHOOSE_FRIEND_EXCHANGE_PHOTO_TYPE */ private int exsType; private MyFriendListAdapter myFriendAdapter; private PopupWindow popupWindow; private ListView list_Contact; private RelativeLayout mNoDataTipsLayout; private TextView mNoDataTipsText1; private TextView mNoDataTipsText2; private TextView mNoDataTipsButton; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ServiceUtils.dout(TAG + " onCreate"); setRetainInstance(true); activity = (HomeActivity) getActivity(); handler = new Handler(this); // doGetBTfriendList(); // new Thread() { // public void run() { // getBottleFriendList(page); // init = true; // }; // }.start(); if (AppContext.getInstance().isGotoMaybeKown()) { doMenuItemSelect(1); AppContext.getInstance().setGotoMaybeKown(false); } else if (AppContext.getInstance().isGotoMyfriend()) { doMenuItemSelect(0); AppContext.getInstance().setGoToMyfriend(false); } else { if (!init) { UICore.eventTask(this, activity, EXEU_GET_BTFRIEND_LIST, "EXEU_GET_BTFRIEND_LIST", null); } } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ServiceUtils.dout(TAG + " onCreateView"); View view = inflater.inflate(R.layout.root_layout, null); mContentView = (FrameLayout) view.findViewById(R.id.mainView); if (!init) { listView = (CustomListView) LayoutInflater.from(activity).inflate(R.layout.main_refresh_list, null); loadMoreView = inflater.inflate(R.layout.refreshable_list_footer, null); loadMoreView.setVisibility(View.GONE); listView.addFooterView(loadMoreView); listView.setOnScrollListener(this); mheaderView = LayoutInflater.from(activity).inflate( R.layout.friend_list_header, null); mNoDataTipsLayout = (RelativeLayout)mheaderView.findViewById(R.id.rl_nodata_tip); mNoDataTipsText1 = (TextView)mheaderView.findViewById(R.id.tv_nodata_tips); mNoDataTipsText2 = (TextView)mheaderView.findViewById(R.id.tv_nodata_tips_2); mNoDataTipsButton = (TextView)mheaderView.findViewById(R.id.bt_nodata_try); listView.addHeaderView(mheaderView); } listView.setonRefreshListener(new CustomListView.OnRefreshListener() { @Override public void onRefresh() { page = 1; if (state == EXEU_GET_BTFRIEND_LIST || state == EXEU_GET_BTFRIEND_TIMELINE_MORE) { UICore.eventTask(FriendFragment.this, activity, EXEU_GET_BTFRIEND_LIST, null, null); } if (state == EXEU_GET_MAYBEKONW_LIST || state == EXEU_GET_MAYBEKONW_LIST_MORE) { UICore.eventTask(FriendFragment.this, activity, EXEU_GET_MAYBEKONW_LIST, null, null); } if(state == EXEU_GET_MYFRIEND_LIST || state == EXEU_GET_MYFRIEND_LIST_MORE){ UICore.eventTask(FriendFragment.this, activity, EXEU_GET_MYFRIEND_LIST, null, null); } } }); initPopupWindow(); return view; } @Override public void onClick(View v) { } @Override public void onPause() { super.onPause(); ServiceUtils.dout(TAG + " onPause"); // if (null != mContentView) { // mContentView.removeAllViews(); // } } @Override public void onResume() { super.onResume(); ServiceUtils.dout(TAG + " onResume"); // if (init) { // if (state==EXEU_GET_BTFRIEND_LIST||state == EXEU_GET_BTFRIEND_TIMELINE_MORE) { // Message message = handler.obtainMessage(EXEU_GET_BTFRIEND_LIST); // handler.sendMessage(message); // } // if (state == EXEU_GET_MAYBEKONW_LIST||state == EXEU_GET_MAYBEKONW_LIST_MORE) { // Message message = handler.obtainMessage(EXEU_GET_MAYBEKONW_LIST); // handler.sendMessage(message); // } // if (state == EXEU_GET_MYFRIEND_LIST||state == EXEU_GET_MYFRIEND_LIST_MORE) { // Message message = handler.obtainMessage(EXEU_GET_MYFRIEND_LIST); // handler.sendMessage(message); // } // } } @Override public void onDestroy() { super.onDestroy(); ServiceUtils.dout(TAG + " onDestory"); } @Override public boolean handleMessage(Message msg) { LanguageConfigTable languageConfigTable = null; LanguageConfig languageCon = null; try { setHeaderVisible(); switch (msg.what) { case EXEU_GET_BTFRIEND_LIST: adapter_type = EXEU_GET_BTFRIEND_LIST; mNoDataTipsLayout.setVisibility(View.GONE); state = EXEU_GET_BTFRIEND_LIST; mContentView.removeAllViews(); if (null!=mBtFriendList&&mBtFriendList.size()<10) { loadMoreView.setVisibility(View.GONE); } mBtfriendAdapter = new BTFriendListAdapter(activity, this, mBtFriendList); listView.setAdapter(mBtfriendAdapter); mContentView.addView(listView); listView.onRefreshComplete(); init = true; new Thread() { public void run() { getPushNotice(); }; }.start(); break; case EXEU_GET_BTFRIEND_TIMELINE_MORE: state = EXEU_GET_BTFRIEND_TIMELINE_MORE; mBtfriendAdapter.notifyDataSetChanged(); listView.setSelection(visibleLastIndex - visibleItemCount + 1); // 设置选中项 break; case EXEU_GET_BTFRIEND_TIMELINE_NOTHING: loadMoreView.setVisibility(View.GONE); listView.setSelection(visibleLastIndex - visibleItemCount); break; case EXEU_SEND_BOTTLE_PRIV_SUCCESS: final Bundle bundle = msg.getData(); try { BottleTypeTable table = new BottleTypeTable(); BottleTypeEntry bottleEntry = table.getBottleType(bundle.getInt("type")); int locationSelect = bottleEntry.getBttype_location_select(); String[] choices = new String[2]; if (locationSelect > 1) { choices[0] = getString(R.string.choose_location_here_throw); choices[1] = getString(R.string.choose_location_search_throw); } else { choices = new String[1]; choices[0] = getString(R.string.choose_location_here_throw); } chooseAction(choices, locationSelect , bundle.getInt("type")); } catch (Exception e) { e.printStackTrace(); } break; case EXEU_PUSH_NOTICE: ((HomeActivity) getActivity()).pushNoticeUpdateUI(); break; case EXEU_SEND_BOTTLE_PRIV_SUCCESS_NOT_ENABLE: activity.onToast((String) msg.obj); break; case EXEU_SEND_BOTTLE_PRIV_FAILED: activity.onToast((String) msg.obj); break; case EXEU_GET_MAYBEKONW_LIST: adapter_type = EXEU_GET_MAYBEKONW_LIST; mNoDataTipsLayout.setVisibility(View.GONE); state = EXEU_GET_MAYBEKONW_LIST; maybeFriendAdapter = new MaybeKnowFriendListAdapter(activity, this, maybeFriendEntries); mContentView.removeAllViews(); mContentView.addView(listView); listView.setAdapter(maybeFriendAdapter); if (maybeFriendEntries.size()<10) { listView.onRefreshComplete(); loadMoreView.setVisibility(View.GONE); } listView.onRefreshComplete(); new Thread() { public void run() { getPushNotice(); }; }.start(); break; case EXEU_GET_MAYBEKONW_LIST_NODATA: state = EXEU_GET_MAYBEKONW_LIST; listView.setAdapter(null); mContentView.removeAllViews(); mContentView.addView(listView); languageConfigTable = new LanguageConfigTable(); languageCon = languageConfigTable.getBottleLanguageConfig(); RelativeLayout mProfileInfo = (RelativeLayout) mheaderView .findViewById(R.id.rl_friend_profile); View line_profile_bottle = (View) mheaderView .findViewById(R.id.line_profile_bottle); LoginUserInfoTable loginUserInfoTable = new LoginUserInfoTable(); LoginUserInfoEntry loginUserInfoEntry = loginUserInfoTable .getLoginUserInfo(AppContext.getInstance().getLogin_uid()); if (null != loginUserInfoEntry && loginUserInfoEntry.getBasicinfo_fullfill() == 0) { mProfileInfo.setVisibility(View.VISIBLE); line_profile_bottle.setVisibility(View.VISIBLE); RemoteImageView img_head = (RemoteImageView) mheaderView .findViewById(R.id.iv_author_photo); LoginUserInfoTable userInfoTable = new LoginUserInfoTable(); if (null != userInfoTable.getLoginUserInfo(AppContext .getInstance().getLogin_uid())) { String avatar = userInfoTable.getLoginUserInfo( AppContext.getInstance().getLogin_uid()) .getAvatar(); if (!TextUtils.isEmpty(avatar)) { img_head.setDefaultImage(R.drawable.avatar_default_small); img_head.setImageUrl(avatar); } } ImageView img_Profile = (ImageView) mheaderView .findViewById(R.id.iv_profile_info); img_Profile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View paramView) { Intent settingIntent = new Intent(activity, SettingActivity.class); startActivity(settingIntent); } }); String setUpTips1 = null; String setUpTips2 = null; if (AppContext.language == 1) { setUpTips1 = languageCon.getWithout_maybeknow_tip_cn(); setUpTips2 = languageCon.getWithout_maybeknow_tip_setup_cn(); }else { setUpTips1 = languageCon.getWithout_maybeknow_tip_en(); setUpTips2 = languageCon.getWithout_maybeknow_tip_setup_en(); } TextView tvProfileTipTitle = (TextView) mheaderView .findViewById(R.id.tv_friend_profile_tips); tvProfileTipTitle.setText(setUpTips1); TextView tvProfileTips = (TextView) mheaderView .findViewById(R.id.tv_friend_profile_tips_2); tvProfileTips.setText(setUpTips2); Button bt_profile = (Button) mheaderView .findViewById(R.id.bt_friend_profile_try); bt_profile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View paramView) { Intent settingIntent2 = new Intent(activity, SettingActivity.class); startActivity(settingIntent2); } }); } else { mProfileInfo.setVisibility(View.GONE); line_profile_bottle.setVisibility(View.GONE); } mNoDataTipsLayout.setVisibility(View.VISIBLE); String maybeKnowTips1 = null; String maybeknowTips2 = null; if (AppContext.language == 1) { maybeKnowTips1 = languageCon.getWithout_maybeknow_tip_cn(); maybeknowTips2 = languageCon.getWithout_maybeknow_tip_invite_cn(); }else { maybeKnowTips1 = languageCon.getWithout_maybeknow_tip_en(); maybeknowTips2 = languageCon.getWithout_maybeknow_tip_invite_en(); } mNoDataTipsText1.setText(maybeKnowTips1); mNoDataTipsText2.setText(maybeknowTips2); mNoDataTipsButton.setText(TextUtil.R("friend_nodata_tip_bt_maybeknow")); mNoDataTipsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View paramView) { Intent intent = new Intent(activity, BindInviteActivity.class); startActivity(intent); } }); break; case EXEU_GET_BTFRIEND_LIST_NO_DATA: state = EXEU_GET_BTFRIEND_LIST; listView.setAdapter(null); mContentView.removeAllViews(); mContentView.addView(listView); languageConfigTable = new LanguageConfigTable(); languageCon = languageConfigTable.getBottleLanguageConfig(); mNoDataTipsLayout.setVisibility(View.VISIBLE); String bottlefriendTips1 = null; String bottlefriendTips2 = null; if (AppContext.language == 1) { bottlefriendTips1 = languageCon.getWithout_btfriend_tip_cn(); bottlefriendTips2 = languageCon.getWithout_btfriend_tip_2_cn(); }else { bottlefriendTips1 = languageCon.getWithout_btfriend_tip_en(); bottlefriendTips2 = languageCon.getWithout_btfriend_tip_2_en(); } mNoDataTipsText1.setText(bottlefriendTips1); mNoDataTipsText2.setText(bottlefriendTips2); mNoDataTipsButton.setText(TextUtil.R("bottle_txt_title_gain")); mNoDataTipsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View paramView) { Intent tryIntent2 = new Intent(activity, ChooseBottleActivity.class); tryIntent2.putExtra("type", "try"); startActivity(tryIntent2); } }); break; case EXEU_GET_MYFRIEND_LIST_NO_DATA: state = EXEU_GET_MYFRIEND_LIST; listView.setAdapter(null); mContentView.removeAllViews(); mContentView.addView(listView); languageConfigTable = new LanguageConfigTable(); languageCon = languageConfigTable.getBottleLanguageConfig(); mNoDataTipsLayout.setVisibility(View.VISIBLE); String myfriendTips1 = null; String myfriendTips2 = null; if (AppContext.language == 1) { myfriendTips1 = languageCon.getWithout_friend_tip_cn(); myfriendTips2 = languageCon.getWithout_friend_tip_2_cn(); }else { myfriendTips1 = languageCon.getWithout_friend_tip_en(); myfriendTips2 = languageCon.getWithout_friend_tip_2_en(); } mNoDataTipsText1.setText(myfriendTips1); mNoDataTipsText2.setText(myfriendTips2); mNoDataTipsButton.setText(TextUtil.R("friend_nodata_tip_bt_maybeknow")); mNoDataTipsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View paramView) { Intent intent = new Intent(activity, BindInviteActivity.class); startActivity(intent); } }); break; case EXEU_GET_MAYBEKONW_LIST_MORE: state = EXEU_GET_MAYBEKONW_LIST_MORE; loadMoreView.setVisibility(View.GONE); maybeFriendAdapter.notifyDataSetChanged(); listView.setSelection(visibleLastIndex - visibleItemCount + 1); // 设置选中项 break; case EXEU_GET_MYFRIEND_LIST: adapter_type = EXEU_GET_MYFRIEND_LIST; mNoDataTipsLayout.setVisibility(View.GONE); state = EXEU_GET_MYFRIEND_LIST; myFriendAdapter = new MyFriendListAdapter(activity, this, myFriendEntries); mContentView.removeAllViews(); if (myFriendEntries.size()<10) { listView.onRefreshComplete(); loadMoreView.setVisibility(View.GONE); } listView.setAdapter(myFriendAdapter); listView.onRefreshComplete(); mContentView.addView(listView); break; case EXEU_GET_MYFRIEND_LIST_MORE: state = EXEU_GET_MYFRIEND_LIST_MORE; loadMoreView.setVisibility(View.GONE); myFriendAdapter.notifyDataSetChanged(); listView.setSelection(visibleLastIndex - visibleItemCount + 1); // 设置选中项 break; case EXEU_GET_MAYBEKONW_LIST_FAILED: activity.onToast((String) msg.obj); break; case EXEU_GET_MYFRIEND_LIST_FAILED: activity.onToast((String) msg.obj); break; case INIT_HAS_EXS_ERROR: activity.onToast((String) msg.obj); break; case INIT_HAS_EXS_PHOTO: Intent intentPhoto = new Intent(activity, ExpandEditActivity.class); Bundle bundlePhoto = new Bundle(); bundlePhoto.putString("from_type", AppContext.APPLY_PICEX); bundlePhoto.putInt("ouid", ouid); intentPhoto.putExtras(bundlePhoto); startActivity(intentPhoto); break; case INIT_HAS_EXS_PROFILE: Intent intentProfile = new Intent(activity, ExpandEditActivity.class); Bundle bundleProfile = new Bundle(); bundleProfile.putString("from_type", AppContext.REPLY_INFOEX); bundleProfile.putInt("ouid", ouid); bundleProfile.putString("reply_infoex_type", "apply"); intentProfile.putExtras(bundleProfile); startActivity(intentProfile); break; case EXEU_GOTO_PROFILE: Intent intentExchangePro = new Intent(activity, ExchangeInfoDetailActivity.class); intentExchangePro.putExtra("ouid", ouid); intentExchangePro.putExtra("page", 1); activity.startActivity(intentExchangePro); break; case EXEU_GOTO_PHOTO: Intent intentExchangePic = new Intent(activity, ExchangePicDetailActivity.class); intentExchangePic.putExtra("ouid", ouid); intentExchangePic.putExtra("page", 1); activity.startActivity(intentExchangePic); break; case EXEU_CHECK_FRIEND_FAILED: activity.onToast((String) msg.obj); break; case EXEU_CAN_NOT_ADD_FRIEND: activity.onToast((String) msg.obj); break; case EXEU_CHECK_FRIEND_SUCCESS: activity.onToast((String) msg.obj); Intent userIntent = new Intent(activity, UserSpaceActivity.class); userIntent.putExtra("ouid", ouid); startActivity(userIntent); break; case EXEU_ALLOW_ADD_FRIEND: Intent applyIntent = new Intent(activity, ExpandEditActivity.class); Bundle bundleFriend = new Bundle(); bundleFriend.putString("from_type", AppContext.APPLY_FRIEND); bundleFriend.putInt("ouid", ouid); applyIntent.putExtras(bundleFriend); startActivity(applyIntent); break; case user_baseinfo_notfull: LoginUserInfoTable userTable = new LoginUserInfoTable(); LoginUserInfoEntry userEntry = userTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid()); activity.showChoseMes(userEntry.getBasicinfo_tip(), complete_info); break; case throw_bottle_init_location: // try { // int bottleid = Integer.parseInt(msg.obj.toString()); // Intent intent2 = new Intent(activity, ThrowBottleSettingActivity.class); // intent2.putExtra("bttype_id", bottleid); // intent2.putExtra("bt_geo_lng", longitude); // intent2.putExtra("bt_geo_lat", latitude); // startActivity(intent2); // } catch (Exception e) { // e.printStackTrace(); // } break; default: break; } } catch (Exception e) { e.printStackTrace(); } return false; } private void setHeaderVisible(){ RelativeLayout mProfileInfo = (RelativeLayout) mheaderView .findViewById(R.id.rl_friend_profile); View line_profile_bottle = (View)mheaderView.findViewById(R.id.line_profile_bottle); LoginUserInfoTable loginUserInfoTable = new LoginUserInfoTable(); LoginUserInfoEntry loginUserInfoEntry = loginUserInfoTable .getLoginUserInfo(AppContext.getInstance().getLogin_uid()); if (null != loginUserInfoEntry && loginUserInfoEntry.getBasicinfo_fullfill() == 0) { mProfileInfo.setVisibility(View.VISIBLE); line_profile_bottle.setVisibility(View.VISIBLE); RemoteImageView img_head = (RemoteImageView) mheaderView .findViewById(R.id.iv_author_photo); LoginUserInfoTable userInfoTable = new LoginUserInfoTable(); if (null != userInfoTable.getLoginUserInfo(AppContext .getInstance().getLogin_uid())) { String avatar = userInfoTable.getLoginUserInfo( AppContext.getInstance().getLogin_uid()) .getAvatar(); if (!TextUtils.isEmpty(avatar)) { img_head.setDefaultImage(R.drawable.avatar_default_small); img_head.setImageUrl(avatar); } } ImageView img_Profile = (ImageView) mheaderView .findViewById(R.id.iv_profile_info); img_Profile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View paramView) { Intent settingIntent = new Intent(activity, SettingActivity.class); startActivity(settingIntent); } }); TextView tvProfileTips = (TextView) mheaderView .findViewById(R.id.tv_friend_profile_tips_2); tvProfileTips.setText(loginUserInfoEntry.getBasicinfo_tip()); Button bt_profile = (Button) mheaderView .findViewById(R.id.bt_friend_profile_try); bt_profile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View paramView) { Intent settingIntent2 = new Intent(activity, SettingActivity.class); startActivity(settingIntent2); } }); } else { mProfileInfo.setVisibility(View.GONE); line_profile_bottle.setVisibility(View.GONE); } } @Override public void execute(int mes, Object obj) { adapter_type = mes; switch (mes) { case EXEU_GET_BTFRIEND_LIST: getBottleFriendList(page); init = true; break; case EXEU_GET_BTFRIEND_TIMELINE_MORE: getMoreBottleFriendList(page); break; case EXEU_GET_BOTTLE_PRIV_OPERATION: getSendSingleBtPriv(btTypeId, btId); break; case EXEU_GET_MAYBEKONW_LIST: getMaybeknowFriendsList(page); break; case EXEU_GET_MAYBEKONW_LIST_MORE: getMoreMaybeknowFriendsList(page); break; case EXEU_GET_MYFRIEND_LIST: getFriendsList(page, groupid, AppContext.getInstance().getLogin_uid()); break; case EXEU_GET_MYFRIEND_LIST_MORE: getMoreFriendsList(page, groupid, AppContext.getInstance().getLogin_uid()); break; case EXEU_GOTO_TA_ALBUM: checkVisible(ouid); break; case EXEU_GOTO_EXCHANGE: getHasExs(exsType, ouid); break; case EXEU_CHECK_FRIEND: CheckFriendApply(ouid); break; case throw_bottle_init_location: Object idObj = obj; ((BasicActivity) getActivity()).networkLocat(); Message msg = Message.obtain(handler, throw_bottle_init_location, idObj); handler.sendMessage(msg); break; default: break; } } private void getMoreBottleFriendList(int page2) { StringBuffer url = new StringBuffer(UrlConfig.get_btfs_list); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&count=20"); url.append("&page=" + page); ServiceUtils.dout("getMoreBottleFriendList url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); if (results == null) { return; } ServiceUtils.dout("getMoreBottleFriendList results:" + results.toString()); Gson gson = new Gson(); BottleFriendInfo bottleFriendInfo = gson.fromJson(results, BottleFriendInfo.class); if (bottleFriendInfo.getResults().getAuthok() == 1) { List<BottleFriendEntry> mMoreBtFriendList = bottleFriendInfo.getBtfs_list(); if (null != mMoreBtFriendList && mMoreBtFriendList.size() > 0) { mBtFriendList.addAll(mMoreBtFriendList); Message message = handler.obtainMessage(EXEU_GET_BTFRIEND_TIMELINE_MORE); handler.sendMessage(message); } else { Message message = handler.obtainMessage(EXEU_GET_BTFRIEND_TIMELINE_NOTHING); handler.sendMessage(message); } } else { Message message = handler.obtainMessage( EXEU_GET_BTFRIEND_LIST_FAILED, bottleFriendInfo.getResults().getErrmsg()); handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } public void doVisitAlbum(int ouid) { this.ouid = ouid; UICore.eventTask(this, activity, EXEU_GOTO_TA_ALBUM, "", null); } public void doExchange(int exsType, int ouid) { if (exsType == AppContext.CHOOSE_FRIEND_EXCHANGE_INFO_TYPE) { LoginUserInfoTable userTable = new LoginUserInfoTable(); LoginUserInfoEntry userEntry = userTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid()); if (userEntry.getBasicinfo_fullfill() == 0) { handler.sendEmptyMessage(user_baseinfo_notfull); } else { this.ouid = ouid; this.exsType = exsType; UICore.eventTask(this, activity, EXEU_GOTO_EXCHANGE, "has_exs", null); } }else { this.ouid = ouid; this.exsType = exsType; UICore.eventTask(this, activity, EXEU_GOTO_EXCHANGE, "has_exs", null); } } private void getHasExs(int exsType, int ouid) { StringBuffer url = new StringBuffer(UrlConfig.get_has_exs); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); ServiceUtils.dout(TAG + " getHasExs url:" + url.toString()); try { String result = HttpUtils.doGet(url.toString()); ServiceUtils.dout(TAG + " getHasExs result:" + result.toString()); if (result != null) { JSONObject object = new JSONObject(result); JSONObject resultObj = object.getJSONObject("results"); int authok = resultObj.getInt("authok"); if (authok == 0) { String errmsg = resultObj.getString("errmsg"); Message msg = Message.obtain(handler, INIT_HAS_EXS_ERROR, errmsg); handler.sendMessage(msg); } else { JSONObject hasExsObj = object.getJSONObject("has_exs"); if (exsType == AppContext.CHOOSE_FRIEND_EXCHANGE_INFO_TYPE) { int has_infoexs = hasExsObj.getInt("has_infoexs"); if (has_infoexs == 1) { handler.sendEmptyMessage(EXEU_GOTO_PROFILE); } else { handler.sendEmptyMessage(INIT_HAS_EXS_PROFILE); } } else if (exsType == AppContext.CHOOSE_FRIEND_EXCHANGE_PHOTO_TYPE) { int has_picexs = hasExsObj.getInt("has_picexs"); if (has_picexs == 1) { handler.sendEmptyMessage(EXEU_GOTO_PHOTO); } else { handler.sendEmptyMessage(INIT_HAS_EXS_PHOTO); } } } } } catch (Exception e) { e.printStackTrace(); } } /** 相册是否可见 */ private void checkVisible(int ouid) { StringBuffer url = new StringBuffer(UrlConfig.check_ouser_visible); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); try { String result = HttpUtils.doGet(url.toString()); if (result != null) { JSONObject object = new JSONObject(result); JSONObject resultObj = object.getJSONObject("results"); if (resultObj.getInt("authok") == 1) { JSONObject visibleObj = object.getJSONObject("visible_info"); int album_visible = visibleObj.getInt("album_visible"); if (album_visible == 1) { Intent intent = new Intent(activity, AlbumsActivity.class); intent.putExtra("ouid", ouid); startActivity(intent); } else { activity.onToast(getString(R.string.exchange_feed_invisible_tips)); } } else { activity.onToast(getString(R.string.exchange_feed_invisible_tips)); } } } catch (Exception e) { e.printStackTrace(); } } /** 获取扔瓶子的权限 */ public void getSendSingleBtPriv(int btTypeId, int btId) { StringBuffer url = new StringBuffer(UrlConfig.get_sendsinglebt_priv); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&bttypeid=" + btTypeId); ServiceUtils.dout("sendsingleBT private url:" + url.toString()); try { String results = HttpUtils.doGet(url.toString()); ServiceUtils.dout("getsendsinglebt_priv result:" + results); if (null != results) { JSONObject obj = new JSONObject(results); JSONObject resultObj = obj.getJSONObject("results"); int authok = resultObj.getInt("authok"); String errmsg = resultObj.getString("errmsg"); if (authok == 1) { JSONObject privObj = obj.getJSONObject("sendsinglebt_priv"); int enable = privObj.getInt("enable"); String reason = privObj.getString("reason"); if (enable == 1) { Bundle bundle = new Bundle(); bundle.putInt("type", btTypeId); bundle.putInt("btid", btId); bundle.putString("reason", reason); Message message = handler.obtainMessage(EXEU_SEND_BOTTLE_PRIV_SUCCESS); message.setData(bundle); handler.sendMessage(message); } else { Message message = handler.obtainMessage(EXEU_SEND_BOTTLE_PRIV_SUCCESS_NOT_ENABLE, reason); handler.sendMessage(message); } } else { Message message = handler.obtainMessage(EXEU_SEND_BOTTLE_PRIV_FAILED, errmsg); handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); } } public void doSendSingleBtPri(int btTypeId, int btId) { this.btId = btId; this.btTypeId = btTypeId; UICore.eventTask(this, activity, EXEU_GET_BOTTLE_PRIV_OPERATION, "", null); } public void doGetBTfriendList_Refresh() { UICore.eventTask(this, activity, EXEU_GET_BTFRIEND_LIST, "EXEU_GET_BTFRIEND_LIST", null); } public void doMenuItemSelect(int which) { page = 1; switch (which) { case 0:// 好友 if (myFriendEntries != null && myFriendEntries.size() > 0) { Message message = handler.obtainMessage(EXEU_GET_MYFRIEND_LIST); handler.sendMessage(message); } else { UICore.eventTask(this, activity, EXEU_GET_MYFRIEND_LIST, "", null); } break; case 1:// 可能认识 if (maybeFriendEntries != null && maybeFriendEntries.size() > 0) { Message message = handler.obtainMessage(EXEU_GET_MAYBEKONW_LIST); handler.sendMessage(message); } else { UICore.eventTask(this, activity, EXEU_GET_MAYBEKONW_LIST, "", null); } break; default: break; } } public void doMenuItemSelect2(int which) { page = 1; switch (which) { case 0:// 好友 if (myFriendEntries != null && myFriendEntries.size() > 0) { Message message = handler.obtainMessage(EXEU_GET_MYFRIEND_LIST); handler.sendMessage(message); } else { UICore.eventTask(this, activity, EXEU_GET_MYFRIEND_LIST, "", null); } break; case 1:// 瓶友 if (mBtFriendList != null && mBtFriendList.size() > 0) { Message message = handler.obtainMessage(EXEU_GET_BTFRIEND_LIST); handler.sendMessage(message); } else { UICore.eventTask(this, activity, EXEU_GET_BTFRIEND_LIST, "", null); } break; default: break; } } private void getBottleFriendList(int page) { if (AppContext.getInstance().getLogin_uid() == 0 || AppContext.getInstance().getLogin_token() == null) { initConfig(); } StringBuffer url = new StringBuffer(UrlConfig.get_btfs_list); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&count=20"); url.append("&page=" + page); ServiceUtils.dout("getBottleFriendList url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); if (results == null) { return; } ServiceUtils.dout("getFeedLocationList results:" + results.toString()); Gson gson = new Gson(); bottleFriendInfo = gson.fromJson(results, BottleFriendInfo.class); if (bottleFriendInfo.getResults().getAuthok() == 1) { mBtFriendList = bottleFriendInfo.getBtfs_list(); if (null != mBtFriendList && mBtFriendList.size()>0) { Message message = handler.obtainMessage(EXEU_GET_BTFRIEND_LIST); handler.sendMessage(message); }else { Message message = handler.obtainMessage(EXEU_GET_BTFRIEND_LIST_NO_DATA); handler.sendMessage(message); } } else { Message message = handler.obtainMessage( EXEU_GET_BTFRIEND_LIST_FAILED, bottleFriendInfo.getResults().getErrmsg()); handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } private void getPushNotice() { StringBuffer url = new StringBuffer(UrlConfig.push_notice); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); try { String result = HttpUtils.doGet(url.toString()); if (result != null) { JSONObject obj = new JSONObject(result); JSONObject resultObj = obj.getJSONObject("results"); if (resultObj.getInt("authok") == 1) { JSONObject pushObj = obj.getJSONObject("push_notice"); PushNoticeInfoTable table = new PushNoticeInfoTable(); PushNoticeInfo pushInfo = new PushNoticeInfo(); table.clearTable(); pushInfo.setMessage_avatar(pushObj.getString("message_avatar")); pushInfo.setMessage_content(pushObj.getString("message_content")); pushInfo.setNew_btfeed_count(pushObj.getInt("new_btfeed_count")); pushInfo.setNew_exfeed_count(pushObj.getInt("new_exfeed_count")); pushInfo.setNew_message_count(pushObj.getInt("new_message_count")); pushInfo.setNew_notice_count(pushObj.getInt("new_notice_count")); pushInfo.setNew_maybeknow_count(pushObj.getInt("new_maybeknow_count")); table.savePushNoticeInfo(pushInfo, AppContext.getInstance().getLogin_uid()); Message message = Message.obtain(handler); message.what = EXEU_PUSH_NOTICE; handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); } } /*** * 获取好友列表 * * @param page */ private void getFriendsList(int page, int groupid, int ouid) { StringBuffer url = new StringBuffer(UrlConfig.get_friends_list); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&groupid=" + groupid); url.append("&ouid=" + ouid); url.append("&count=20"); url.append("&page=" + page); ServiceUtils.dout("getFriendsList url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); if (results == null) { return; } ServiceUtils.dout("getFriendsList results:" + results.toString()); Gson gson = new Gson(); myfriendInfo = gson.fromJson(results, MyFriendInfo.class); if (myfriendInfo.getResults().getAuthok() == 1) { groups_list = myfriendInfo.getGroups_list(); if (groups_list != null && !groups_list.isEmpty()) { groupNames = new String[groups_list.size() + 3]; groupNames[0] = getString(R.string.friend_btfriend); groupNames[1] = getString(R.string.friend_maybe_kown); groupNames[2] = getString(R.string.friend_all_friend); for (int i = 3;i < groups_list.size() + 3;i++) { groupNames[i] = groups_list.get(i - 3).getGroupname(); } groupNames[2+groups_list.size()] = getString(R.string.friend_mangager_group); } myFriendEntries = myfriendInfo.getFriends_list(); if (myFriendEntries.isEmpty()) { Message message = handler.obtainMessage(EXEU_GET_MYFRIEND_LIST_NO_DATA); handler.sendMessage(message); }else { Message message = handler.obtainMessage(EXEU_GET_MYFRIEND_LIST); handler.sendMessage(message); } } else { Message message = handler.obtainMessage( EXEU_GET_MYFRIEND_LIST_FAILED, myfriendInfo.getResults().getErrmsg()); handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } /*** * 获取更多好友列表 * * @param page */ private void getMoreFriendsList(int page, int groupid, int ouid) { StringBuffer url = new StringBuffer(UrlConfig.get_friends_list); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&groupid=" + groupid); url.append("&ouid=" + ouid); url.append("&count=20"); url.append("&page=" + page); ServiceUtils.dout("getMoreFriendsList url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); if (results == null) { return; } ServiceUtils.dout("getMoreFriendsList results:" + results.toString()); Gson gson = new Gson(); myfriendInfo = gson.fromJson(results, MyFriendInfo.class); if (myfriendInfo.getResults().getAuthok() == 1) { List<MyFriendEntry> moreEntries = myfriendInfo.getFriends_list(); if (null != moreEntries && moreEntries.size() > 0) { myFriendEntries.addAll(moreEntries); Message message = handler.obtainMessage(EXEU_GET_MYFRIEND_LIST_MORE); handler.sendMessage(message); } else { Message message = handler.obtainMessage(EXEU_GET_BTFRIEND_TIMELINE_NOTHING); handler.sendMessage(message); } } else { Message message = handler.obtainMessage( EXEU_GET_MYFRIEND_LIST_FAILED, myfriendInfo.getResults().getErrmsg()); handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } /*** * 获取可能认识好友列表 * * @param page */ private void getMaybeknowFriendsList(int page) { StringBuffer url = new StringBuffer(UrlConfig.get_maybeknows_list); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&count=20"); url.append("&page=" + page); ServiceUtils.dout("getMaybeknowFriendsList url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); if (results == null) { return; } ServiceUtils.dout("getMaybeknowFriendsList results:" + results.toString()); Gson gson = new Gson(); MaybeKnowFriendInfo maybefriendInfo = gson.fromJson(results, MaybeKnowFriendInfo.class); if (maybefriendInfo.getResults().getAuthok() == 1) { maybeFriendEntries = maybefriendInfo.getMaybeknows_list(); if (null != maybeFriendEntries && maybeFriendEntries.size()>0) { Message message = handler.obtainMessage(EXEU_GET_MAYBEKONW_LIST); handler.sendMessage(message); }else { Message message = handler.obtainMessage(EXEU_GET_MAYBEKONW_LIST_NODATA); handler.sendMessage(message); } } else { Message message = handler.obtainMessage( EXEU_GET_MAYBEKONW_LIST_FAILED, bottleFriendInfo.getResults().getErrmsg()); handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } /*** * 获取可能认识好友列表 * * @param page */ private void getMoreMaybeknowFriendsList(int page) { StringBuffer url = new StringBuffer(UrlConfig.get_maybeknows_list); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&count=20"); url.append("&page=" + page); ServiceUtils.dout("getMoreMaybeknowFriendsList url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); if (results == null) { return; } ServiceUtils.dout("getMoreMaybeknowFriendsList results:" + results.toString()); Gson gson = new Gson(); MaybeKnowFriendInfo maybefriendInfo = gson.fromJson(results, MaybeKnowFriendInfo.class); if (maybefriendInfo.getResults().getAuthok() == 1) { List<MaybeFriendEntry> moreMaybeFriendEntries = maybefriendInfo.getMaybeknows_list(); if (null != moreMaybeFriendEntries && moreMaybeFriendEntries.size() > 0) { maybeFriendEntries.addAll(moreMaybeFriendEntries); Message message = handler.obtainMessage(EXEU_GET_MAYBEKONW_LIST_MORE); handler.sendMessage(message); } else { Message message = handler.obtainMessage(EXEU_GET_BTFRIEND_TIMELINE_NOTHING); handler.sendMessage(message); } } else { Message message = handler.obtainMessage( EXEU_GET_MAYBEKONW_LIST_FAILED, bottleFriendInfo.getResults().getErrmsg()); handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } private void initPopupWindow() { View popview = LayoutInflater.from(activity).inflate( R.layout.contact_popmeun, null); popupWindow = new PopupWindow(popview, 200, LayoutParams.WRAP_CONTENT); // mPopupWindow.setBackgroundDrawable(new BitmapDrawable()); popupWindow.setBackgroundDrawable(getResources().getDrawable( R.drawable.bubble_frame_pop)); popupWindow.setOutsideTouchable(true); // 自定义动画 // popupWindow.setAnimationStyle(R.style.map_menu_animation); // 使用系统动画 // mPopupWindow.setAnimationStyle(android.R.style.Animation_Translucent); popupWindow.update(); popupWindow.setTouchable(true); popupWindow.setFocusable(true); list_Contact = (ListView) popview.findViewById(R.id.list_contact); } public void showPopupWindow(View view) { groupAdapter = new GroupFriendAdapter(this, activity, groups_list); list_Contact.setAdapter(groupAdapter); if (!popupWindow.isShowing()) { popupWindow.showAsDropDown(view, 0, 0); } else { popupWindow.dismiss(); } } public void doSelectGroupAction() { final Context dialogContext = new ContextThemeWrapper(activity, android.R.style.Theme_Light); String cancel = getString(R.string.bt_title_back); final ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, groupNames); final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext); builder.setTitle(getString(R.string.choose_friend_select_group)); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); groupItem = which; activity.titleView.setText(groupNames[groupItem]); if (groupItem == 0) { if (mBtFriendList != null && mBtFriendList.size() > 0) { Message message = handler.obtainMessage(EXEU_GET_BTFRIEND_LIST); handler.sendMessage(message); } else { UICore.eventTask(FriendFragment.this, activity, EXEU_GET_BTFRIEND_LIST, "", null); } } else if (groupItem == 1){ if (maybeFriendEntries != null && maybeFriendEntries.size() > 0) { Message message = handler.obtainMessage(EXEU_GET_MAYBEKONW_LIST); handler.sendMessage(message); } else { UICore.eventTask(FriendFragment.this, activity, EXEU_GET_MAYBEKONW_LIST, "", null); } } else if (groupItem == 2) { groupid = -1; UICore.eventTask(FriendFragment.this, activity, EXEU_GET_MYFRIEND_LIST, "", null); } else if (groupItem == groupNames.length-1) { activity.titleView.setText(""); Intent intent = new Intent(activity, ManagerGroupActivity.class); activity.startActivity(intent); } else { groupid = groups_list.get(which - 3).getGroupid(); UICore.eventTask(FriendFragment.this, activity, EXEU_GET_MYFRIEND_LIST, "", null); } } }); builder.setNegativeButton(cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } public void doCheckApplyFriend(int ouid){ this.ouid = ouid; UICore.eventTask(this, activity, EXEU_CHECK_FRIEND, "", null); } /*** * 好友申请前检测接口 */ private void CheckFriendApply(int ouid) { StringBuffer url = new StringBuffer(UrlConfig.check_friendapply); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); ServiceUtils.dout("CheckFriendApply url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); ServiceUtils.dout("CheckFriendApply results:" + results.toString()); if (null != results) { JSONObject obj = new JSONObject(results); JSONObject resultObj = obj.getJSONObject("results"); int authok = resultObj.getInt("authok"); String errmsg = resultObj.getString("errmsg"); int check_result = resultObj.getInt("check_result"); String msg = resultObj.getString("msg"); if (authok == 1) { Message message = null; switch (check_result) { case 0: message = handler.obtainMessage(EXEU_CAN_NOT_ADD_FRIEND,msg); handler.sendMessage(message); break; case 1: message = handler.obtainMessage(EXEU_CHECK_FRIEND_SUCCESS,msg); handler.sendMessage(message); break; case 2: message = handler.obtainMessage(EXEU_ALLOW_ADD_FRIEND); handler.sendMessage(message); break; default: break; } } else { Message message = handler.obtainMessage(EXEU_CHECK_FRIEND_FAILED, errmsg); handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { listView.setFirstVisiableItem(firstVisibleItem); this.visibleItemCount = visibleItemCount; visibleLastIndex = firstVisibleItem + visibleItemCount; } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { try { BaseAdapter adapter = null; if (adapter_type == EXEU_GET_BTFRIEND_LIST) { adapter = mBtfriendAdapter; } else if (adapter_type == EXEU_GET_MAYBEKONW_LIST) { adapter = maybeFriendAdapter; } else if (adapter_type == EXEU_GET_MYFRIEND_LIST) { adapter = myFriendAdapter; } if (adapter != null) { int itemsLastIndex = adapter.getCount() + 2; // 数据集最后一项的索引 int lastIndex = itemsLastIndex + 1; // 加上底部的loadMoreView项 和 head项 ServiceUtils.dout(TAG+" lastIndex: "+lastIndex); ServiceUtils.dout(TAG+" visibleLastIndex:"+visibleLastIndex); if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == lastIndex) { // 如果是自动加载,可以在这里放置异步加载数据的代码 page++; loadMoreView.setVisibility(View.VISIBLE); switch (state) { case EXEU_GET_BTFRIEND_LIST: UICore.eventTask(this, activity, EXEU_GET_BTFRIEND_TIMELINE_MORE, null, null); break; case EXEU_GET_MAYBEKONW_LIST: UICore.eventTask(this, activity, EXEU_GET_MAYBEKONW_LIST_MORE, null, null); break; case EXEU_GET_MYFRIEND_LIST: UICore.eventTask(this, activity, EXEU_GET_MYFRIEND_LIST_MORE, null, null); break; default: break; } Log.i("LOADMORE", "loading..."); } } } catch (Exception e) { e.printStackTrace(); } } public void initConfig() { String country = getResources().getConfiguration().locale.getCountry(); if (country.equals("CN")) { AppContext.setLanguage(1); } else { AppContext.setLanguage(0); } SharedPreferences preferences = getActivity().getSharedPreferences("Preferences_userinfo", Activity.MODE_APPEND); int login_uid = preferences.getInt("login_uid", 0); String login_token = preferences.getString("login_token", null); AppContext.getInstance().setLogin_uid(login_uid); AppContext.getInstance().setLogin_token(login_token); } private void chooseAction(String[] choices, final int locationSelected, final int bottleId) { final Context dialogContext = new ContextThemeWrapper(activity, android.R.style.Theme_Light); final ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (which == 0) { Intent intent2 = new Intent(activity, ThrowBottleSettingActivity.class); intent2.putExtra("bttype_id", bottleId); intent2.putExtra("bt_geo_lng", AppContext.getInstance().getLongitude()); intent2.putExtra("bt_geo_lat", AppContext.getInstance().getLatitude()); startActivity(intent2); } else { Intent intent = new Intent(activity, ChooseLocationTabsActivity.class); intent.putExtra("type", "throw"); intent.putExtra("bottleId", bottleId); intent.putExtra("locationSelect", locationSelected); startActivity(intent); } } }); builder.create().show(); } }
Java
package com.outsourcing.bottle.ui.fragment; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Handler.Callback; import android.os.Message; import android.support.v4.app.Fragment; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import com.outsourcing.bottle.R; import com.outsourcing.bottle.domain.LocationEntry; import com.outsourcing.bottle.domain.PlatformBindConfig; import com.outsourcing.bottle.domain.UrlConfig; import com.outsourcing.bottle.ui.BottleTipsActivity; import com.outsourcing.bottle.ui.ChooseLocationTabsActivity; import com.outsourcing.bottle.ui.ThrowBottleSettingActivity; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.BasicUIEvent; import com.outsourcing.bottle.util.HttpUtils; import com.outsourcing.bottle.util.UICore; /** * * @author 06peng * */ public class GlobalFragment extends Fragment implements BasicUIEvent, Callback { private final int search_location = 2; private final int gain_bottle = 3; private final int gain_bottle_success = 4; private final int gain_bottle_error = 5; private final int throw_bottle = 6; private ListView listView; private ChooseLocationTabsActivity activity; private int currentItem; private List<LocationEntry> locations; private LocationAdapter adapter; private LocationEntry myLocation; private Handler handler; private ImageView refresh; private EditText keywordView; public GlobalFragment() { super(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); handler = new Handler(this); this.activity = (ChooseLocationTabsActivity) getActivity(); Bundle bundle = getArguments(); if (bundle != null) { currentItem = bundle.getInt("currentItem"); } UICore.eventTask(this, activity, search_location, "search_location", null); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.choose_location, null); listView = (ListView) view.findViewById(R.id.choose_location_list); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { LocationEntry entry = locations.get(arg2); if (activity.type.equals("try")) { UICore.eventTask(GlobalFragment.this, activity, gain_bottle, getString(R.string.init_data), entry); } else { UICore.eventTask(GlobalFragment.this, activity, throw_bottle, getString(R.string.init_data), entry); } } }); refresh = (ImageView) view.findViewById(R.id.choose_location_refresh); refresh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { search(); } }); keywordView = (EditText) view.findViewById(R.id.choose_location_search_edit); keywordView.setHint(R.string.choose_location_global); keywordView.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { search(); return false; } }); return view; } @Override public void execute(int mes, Object obj) { switch (mes) { case search_location: locate(); getSearchLocation(obj == null ? "" : (String)obj); handler.sendEmptyMessage(search_location); break; case gain_bottle: LocationEntry entry = (LocationEntry) obj; gainBottle(entry); break; case throw_bottle: LocationEntry entry_throw = (LocationEntry) obj; Message msg = Message.obtain(handler, throw_bottle, entry_throw); handler.sendMessage(msg); break; default: break; } } public void search() { String keyword = keywordView.getText().toString().trim(); UICore.eventTask(GlobalFragment.this, activity, search_location, getString(R.string.init_data), keyword); } private void locate() { myLocation = new LocationEntry(); myLocation.setLatitude(AppContext.getInstance().getLatitude()); myLocation.setLongitude(AppContext.getInstance().getLongitude()); String params = String.valueOf(AppContext.getInstance().getLatitude()) + "," + String.valueOf(AppContext.getInstance().getLongitude()); String language = AppContext.language == 1 ? "zh" : "en"; String url = "http://www.mobibottle.com/openapi/geocode_offset.json?" + "latlng="+params+"&sensor=true&language=" + language + "&login_uid=" + AppContext.getInstance().getLogin_uid(); try { String result = HttpUtils.doGet(url); JSONObject object = new JSONObject(result); JSONArray arrays = object.getJSONArray("results"); for (int i = 0;i < arrays.length();i++) { JSONObject jsonObject = arrays.getJSONObject(i); if (jsonObject != null) { JSONArray addressArrays = jsonObject.getJSONArray("address_components"); for (int j = 0;j < addressArrays.length();j++) { JSONObject obj = addressArrays.getJSONObject(j); JSONArray typeArray = obj.getJSONArray("types"); for (int k = 0;k < typeArray.length();k++) { String typename = typeArray.getString(k); if (typename.equals("locality")) { myLocation.setCity(obj.getString("long_name")); } else if (typename.equals("administrative_area_level_1")) { myLocation.setProvince(obj.getString("long_name")); } else if (typename.equals("country")) { myLocation.setCountry(obj.getString("long_name")); } } } break; } } } catch (Exception e) { e.printStackTrace(); } } private void getSearchLocation(String keyword) { String url = "http://www.mobibottle.com/openapi/google_get_autocomplete.json?"; String language = AppContext.language == 1 ? "zh" : "en" + "&login_uid=" + AppContext.getInstance().getLogin_uid(); if (currentItem == 1) { String input = keyword + "+" + myLocation.getCountry() + "+" + myLocation.getProvince() + "+" + myLocation.getCity(); url += "input=" + input + "&sensor=false&language=" + language + "&key=" + PlatformBindConfig.Goolge_Places_AppKey; } else if (currentItem == 2) { String input = keyword + "+" + myLocation.getCountry(); url += "input=" + input + "&sensor=false&language=" + language + "&key=" + PlatformBindConfig.Goolge_Places_AppKey; } else if (currentItem == 3) { url += "input=" + keyword + "&sensor=false&language=" + language + "&key=" + PlatformBindConfig.Goolge_Places_AppKey; } System.out.println(url); try { String result = HttpUtils.doGet(url); JSONObject obj = new JSONObject(result); JSONArray arrays = obj.getJSONArray("predictions"); locations = new ArrayList<LocationEntry>(); for (int i = 0;i < arrays.length();i++) { LocationEntry entry = new LocationEntry(); JSONObject object = arrays.getJSONObject(i); entry.setAddress(object.getString("description")); entry.setReference(object.getString("reference")); JSONArray typeArrays = object.getJSONArray("types"); String type = typeArrays.getString(0); entry.setType(type); JSONArray termsArrays = object.getJSONArray("terms"); JSONObject tearmObj = termsArrays.getJSONObject(0); entry.setLocationName(tearmObj.getString("value")); locations.add(entry); } } catch (Exception e) { e.printStackTrace(); } } private void gainBottle(LocationEntry entry) { String url = UrlConfig.gain_bt; HashMap<String, String> paramsMap = new HashMap<String, String>(); paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid())); paramsMap.put("login_token", AppContext.getInstance().getLogin_token()); paramsMap.put("nettypeid", String.valueOf(activity.bottleId)); paramsMap.put("bt_geo_lng", String.valueOf(entry.getLongitude())); paramsMap.put("bt_geo_lat", String.valueOf(entry.getLatitude())); paramsMap.put("bt_geo_reference", entry.getReference()); try { String result = HttpUtils.doPost(activity, url, paramsMap); JSONObject obj = new JSONObject(result); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); if (success == 1) { String successmsg = resultObj.getString("successmsg"); int gainbt_type = resultObj.getInt("gainbt_type"); String gainbt_msg = resultObj.getString("gainbt_msg"); Object[] objs = new Object[3]; objs[0] = successmsg; objs[1] = gainbt_type; objs[2] = gainbt_msg; Message msg = Message.obtain(handler, gain_bottle_success, objs); handler.sendMessage(msg); } else { String errmsg = resultObj.getString("errmsg"); Message msg = Message.obtain(handler, gain_bottle_error, errmsg); handler.sendMessage(msg); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onResume() { super.onResume(); adapter = new LocationAdapter(); listView.setAdapter(adapter); } public class LocationAdapter extends BaseAdapter { @Override public int getCount() { return locations == null ? 0 : locations.size(); } @Override public Object getItem(int arg0) { return locations == null ? null : locations.get(arg0); } @Override public long getItemId(int arg0) { return arg0; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view; ViewHolder holder = new ViewHolder(); if (convertView != null) { view = convertView; holder = (ViewHolder) view.getTag(); } else { view = LayoutInflater.from(activity).inflate(R.layout.choose_location_listitem, null); holder.nameView = (TextView) view.findViewById(R.id.choose_location_listitem_name); holder.vicinityView = (TextView) view.findViewById(R.id.choose_location_listitem_vicinity); holder.typeView = (TextView) view.findViewById(R.id.choose_location_listitem_type); view.setTag(holder); } LocationEntry entry = locations.get(position); if (entry != null) { holder.nameView.setText(entry.getLocationName()); holder.vicinityView.setText(entry.getAddress()); holder.typeView.setText(entry.getType()); } return view; } } public static class ViewHolder { TextView nameView; TextView vicinityView; TextView typeView; } @Override public boolean handleMessage(Message msg) { switch (msg.what) { case search_location: adapter = new LocationAdapter(); listView.setAdapter(adapter); break; case gain_bottle_error: activity.onToast((String) msg.obj); break; case gain_bottle_success: Object[] objs = (Object[]) msg.obj; activity.onToast((String) objs[0]); Intent intent = new Intent(activity, BottleTipsActivity.class); intent.putExtra("type", "try"); intent.putExtra("bottleId", Integer.parseInt(objs[1].toString())); intent.putExtra("gainbt_msg", objs[2].toString()); startActivity(intent); break; case throw_bottle: LocationEntry entry = (LocationEntry) msg.obj; Intent intent2 = new Intent(activity, ThrowBottleSettingActivity.class); intent2.putExtra("bttype_id", activity.bottleId); intent2.putExtra("bt_geo_lng", entry.getLongitude()); intent2.putExtra("bt_geo_lat", entry.getLatitude()); intent2.putExtra("reference", entry.getReference()); startActivity(intent2); break; default: break; } return false; } }
Java
package com.outsourcing.bottle.ui.fragment; import java.util.List; import org.json.JSONObject; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.Handler.Callback; import android.os.Message; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.util.Log; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.RelativeLayout; import android.widget.TextView; import com.google.gson.Gson; import com.outsourcing.bottle.BasicActivity; import com.outsourcing.bottle.R; import com.outsourcing.bottle.SplashActivity; import com.outsourcing.bottle.adapter.PublicActivityAdapter; import com.outsourcing.bottle.adapter.PublicActivityAdapter.ViewHolder; import com.outsourcing.bottle.db.BottleTypeTable; import com.outsourcing.bottle.db.LanguageConfigTable; import com.outsourcing.bottle.db.LoginUserInfoTable; import com.outsourcing.bottle.db.PushNoticeInfoTable; import com.outsourcing.bottle.db.StickersPackTable; import com.outsourcing.bottle.domain.BottleEntry; import com.outsourcing.bottle.domain.BottleTimelineInfo; import com.outsourcing.bottle.domain.BottleTypeEntry; import com.outsourcing.bottle.domain.LanguageConfig; import com.outsourcing.bottle.domain.LoginUserInfo; import com.outsourcing.bottle.domain.LoginUserInfoEntry; import com.outsourcing.bottle.domain.PasterDirConfigEntry; import com.outsourcing.bottle.domain.PushNoticeInfo; import com.outsourcing.bottle.domain.UrlConfig; import com.outsourcing.bottle.remoteimage.RemoteImageView; import com.outsourcing.bottle.ui.ChooseBottleActivity; import com.outsourcing.bottle.ui.ChooseLocationTabsActivity; import com.outsourcing.bottle.ui.HomeActivity; import com.outsourcing.bottle.ui.SettingActivity; import com.outsourcing.bottle.ui.ThrowBottleSettingActivity; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.BasicUIEvent; import com.outsourcing.bottle.util.HttpUtils; import com.outsourcing.bottle.util.ServiceUtils; import com.outsourcing.bottle.util.TextUtil; import com.outsourcing.bottle.util.UICore; import com.outsourcing.bottle.widget.CustomListView; import com.outsourcing.bottle.widget.CustomPopupWindow; /** * * @author 06peng * */ public class BottleFragment extends Fragment implements BasicUIEvent, Callback, OnClickListener, OnScrollListener { private static final String TAG = BottleFragment.class.getSimpleName(); public HomeActivity activity; private View mLikeView = null; private CustomPopupWindow mLikePopview = null; public static final int EXEU_GET_TIMELINE = 0; private static final int EXEU_LIKE_OPERATION = 1; private static final int EXEU_UNLIKE_OPERATION = 2; private static final int EXEU_OPEN_BOTTLE_OPERATION = 3; private static final int EXEU_OPEN_BOTTLE_SUCCESS = 4; private static final int EXEU_OPEN_BOTTLE_FAILED = 5; private static final int EXEU_DROP_BOTTLE_OPERATION = 6; private static final int EXEU_DROP_BOTTLE_SUCCESS = 7; private static final int EXEU_DROP_BOTTLE_FAILED = 8; private static final int EXEU_SEND_BOTTLE_PRIV_SUCCESS = 9; private static final int EXEU_SEND_BOTTLE_PRIV_SUCCESS_NOT_ENABLE = 10; private static final int EXEU_SEND_BOTTLE_PRIV_FAILED = 11; private static final int EXEU_GET_BOTTLE_PRIV_OPERATION = 12; private static final int EXEU_LIKE_OPERATION_FAILED = 13; private static final int EXEU_GET_MORE_TIMELINE = 15; private static final int EXEU_GET_BOTTLE_INFO = 16; private static final int EXEU_GET_TIMELINE_FAILED = 17; private static final int EXEU_REFRESH_TIMELINE = 18; private static final int EXEU_GET_MORE_TIMELINE_NOTHING = 19; private static final int EXEU_GET_MENU_TIMELINE = 20; private static final int EXEU_GET_SINGLE_BOTTLE_SUCCESS = 21; private final int refresh_bottle_fragment = 22; private final int throw_bottle_init_location = 23; private static final int EXEU_SET_BTPIC_PAINT = 24; private static final int EXEU_PASTERDIR_PAY = 25; private static final int EXEU_PUSH_NOTICE = 26; private CustomListView listView; private View mheaderView = null; private View loadMoreView = null; private Handler handler = null; private PublicActivityAdapter mTimeLineAdapter; private BottleTimelineInfo bottlelist = null; private List<BottleEntry> mBottleList = null; public int btId = -1; private int btTypeId; private int page = 1; private int mode = 0; public boolean init = false; private int visibleLastIndex = 0; // 最后的可视项索引 private int visibleItemCount; // 当前窗口可见项总数 LinearLayout contentView = null; private StickersPackTable stickPackTable; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ServiceUtils.dout(TAG + "onCreate"); setRetainInstance(true); activity = (HomeActivity) getActivity(); handler = new Handler(this); // if (AppContext.getInstance().getCurrentItem() == 1) { // doGetBottleTimeline(); // } doGetBottleTimeline(); AppContext.setContext(activity); stickPackTable = new StickersPackTable(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ServiceUtils.dout(TAG + "onCreateView"); View view = inflater.inflate(R.layout.bottle_fragment, null); listView = (CustomListView) view.findViewById(R.id.list_view); listView.setonRefreshListener(new CustomListView.OnRefreshListener() { @Override public void onRefresh() { refresh(); } }); loadMoreView = inflater.inflate(R.layout.refreshable_list_footer, null); loadMoreView.setVisibility(View.GONE); mheaderView = LayoutInflater.from(activity).inflate( R.layout.bottle_list_header, null); listView.addHeaderView(mheaderView); listView.addFooterView(loadMoreView); listView.setOnScrollListener(this); // 添加滑动监听 initLikePopupWindow(); return view; } public void doGetBottleTimeline() { if (!init) { UICore.eventTask(this, activity, EXEU_GET_TIMELINE, "EXEU_GET_TIMELINE", null); } } public void doGetBottleTimeline_Refresh() { UICore.eventTask(this, activity, refresh_bottle_fragment, "refresh_bottle_fragment", null); } @Override public void onResume() { super.onResume(); ServiceUtils.dout(TAG + "onResume"); handler = new Handler(this); if (AppContext.getInstance().isFromBottleTime()) { AppContext.getInstance().setFromBottleTime(false); UICore.eventTask(this, activity, EXEU_REFRESH_TIMELINE, "EXEU_GET_TIMELINE", null); } } @Override public void execute(int mes, Object obj) { switch (mes) { case EXEU_GET_TIMELINE: if (!init) { getLoginUserInfo(); getTimeLineForRefresh(mode); init = true; } break; case EXEU_REFRESH_TIMELINE: getSingleBottle(btId); break; case refresh_bottle_fragment: getLoginUserInfo(); getTimeLineForRefresh(mode); break; case EXEU_GET_MORE_TIMELINE: getMoreTimeLine(page, mode); break; case EXEU_LIKE_OPERATION: likeOperation(btId, 1); break; case EXEU_UNLIKE_OPERATION: likeOperation(btId, 2); break; case EXEU_OPEN_BOTTLE_OPERATION: openBottle(btId); break; case EXEU_DROP_BOTTLE_OPERATION: dropBottle(btId); break; case EXEU_GET_BOTTLE_PRIV_OPERATION: getSendSingleBtPriv(btTypeId, btId); break; case EXEU_GET_MENU_TIMELINE: getTimeLine(mode); break; case EXEU_GET_SINGLE_BOTTLE_SUCCESS: getSingleBottle(btId); break; case throw_bottle_init_location: Object idObj = obj; ((BasicActivity) getActivity()).networkLocat(); Message msg = Message.obtain(handler, throw_bottle_init_location, idObj); handler.sendMessage(msg); break; case EXEU_SET_BTPIC_PAINT: int optype = (Integer)obj; setBtpicPaint(btId, optype); break; default: break; } } private void getPushNotice() { StringBuffer url = new StringBuffer(UrlConfig.push_notice); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); try { String result = HttpUtils.doGet(url.toString()); if (result != null) { JSONObject obj = new JSONObject(result); JSONObject resultObj = obj.getJSONObject("results"); if (resultObj.getInt("authok") == 1) { JSONObject pushObj = obj.getJSONObject("push_notice"); PushNoticeInfoTable table = new PushNoticeInfoTable(); PushNoticeInfo pushInfo = new PushNoticeInfo(); table.clearTable(); pushInfo.setMessage_avatar(pushObj.getString("message_avatar")); pushInfo.setMessage_content(pushObj.getString("message_content")); pushInfo.setNew_btfeed_count(pushObj.getInt("new_btfeed_count")); pushInfo.setNew_exfeed_count(pushObj.getInt("new_exfeed_count")); pushInfo.setNew_message_count(pushObj.getInt("new_message_count")); pushInfo.setNew_notice_count(pushObj.getInt("new_notice_count")); table.savePushNoticeInfo(pushInfo, AppContext.getInstance().getLogin_uid()); Message message = Message.obtain(handler); message.what = EXEU_PUSH_NOTICE; handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); } } private void refresh() { page = 1; new Thread() { public void run() { getLoginUserInfo(); getTimeLineForRefresh(mode); handler.sendEmptyMessage(EXEU_GET_TIMELINE); }; }.start(); } /** * 获取用户基本资料 */ private void getLoginUserInfo() { StringBuffer url = new StringBuffer(UrlConfig.get_loginuser_info); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); ServiceUtils.dout("login url:" + url.toString()); try { String result = HttpUtils.doGet(url.toString()); Gson gson = new Gson(); LoginUserInfo loginUserInfo = gson.fromJson(result, LoginUserInfo.class); LoginUserInfoTable loginUserInfoTable = new LoginUserInfoTable(); if (null != loginUserInfoTable.getLoginUserInfo(AppContext .getInstance().getLogin_uid())) { String net_avatar = loginUserInfo.getLoginuser_info() .getAvatar(); String old_avatar = loginUserInfoTable.getLoginUserInfo( AppContext.getInstance().getLogin_uid()).getAvatar(); // if (!TextUtils.isEmpty(net_avatar)) { // ServiceUtils.downLoadImage(net_avatar, AppContext.UserAvatarIcon); // } loginUserInfoTable.deleteLoginUserInfoById(AppContext .getInstance().getLogin_uid()); loginUserInfoTable.saveLoginUserInfo(loginUserInfo .getLoginuser_info(), AppContext.getInstance() .getLogin_uid()); /***********保存贴纸目录路径*********/ List<PasterDirConfigEntry> pasterdir_config = loginUserInfo.getPasterdir_privs_list(); stickPackTable.clearTalbe(); for (PasterDirConfigEntry mPasterDirEntry : pasterdir_config) { // ServiceUtils.downLoadImage(mPasterDirEntry.getPasterdir_coverurl(),mPasterDirEntry.getPasterdir_id()+"", // AppContext.PasterDir); stickPackTable.saveStickDir(mPasterDirEntry); } } else { loginUserInfoTable.saveLoginUserInfo(loginUserInfo .getLoginuser_info(), AppContext.getInstance() .getLogin_uid()); /***********保存贴纸目录路径*********/ List<PasterDirConfigEntry> pasterdir_config = loginUserInfo.getPasterdir_privs_list(); stickPackTable.clearTalbe(); for (PasterDirConfigEntry mPasterDirEntry : pasterdir_config) { // ServiceUtils.downLoadImage(mPasterDirEntry.getPasterdir_coverurl(),mPasterDirEntry.getPasterdir_id()+"", // AppContext.PasterDir); stickPackTable.saveStickDir(mPasterDirEntry); } } } catch (Exception e) { e.printStackTrace(); } } public void doSendSingleBtPri(int btTypeId, int btId) { this.btId = btId; this.btTypeId = btTypeId; UICore.eventTask(this, activity, EXEU_GET_BOTTLE_PRIV_OPERATION, "", null); } /** 获取扔瓶子的权限 */ public void getSendSingleBtPriv(int btTypeId, int btId) { StringBuffer url = new StringBuffer(UrlConfig.get_sendsinglebt_priv); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&bttypeid=" + btTypeId); ServiceUtils.dout("sendsingleBT private url:" + url.toString()); try { String results = HttpUtils.doGet(url.toString()); ServiceUtils.dout("getsendsinglebt_priv result:" + results); if (null != results) { JSONObject obj = new JSONObject(results); JSONObject resultObj = obj.getJSONObject("results"); int authok = resultObj.getInt("authok"); String errmsg = resultObj.getString("errmsg"); if (authok == 1) { JSONObject privObj = obj.getJSONObject("sendsinglebt_priv"); int enable = privObj.getInt("enable"); String reason = privObj.getString("reason"); if (enable == 1) { Bundle bundle = new Bundle(); bundle.putInt("type", btTypeId); bundle.putInt("btid", btId); bundle.putString("reason", reason); Message message = handler.obtainMessage(EXEU_SEND_BOTTLE_PRIV_SUCCESS); message.setData(bundle); handler.sendMessage(message); } else { Message message = handler.obtainMessage(EXEU_SEND_BOTTLE_PRIV_SUCCESS_NOT_ENABLE, reason); handler.sendMessage(message); } } else { Message message = handler.obtainMessage( EXEU_SEND_BOTTLE_PRIV_FAILED, errmsg); handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); } } /** * * @param objtype 要清除的位置的类型:选择项:(1)瓶子动态的位置信息、(2)交换动态留言的位置信息、(3)照片评论的位置信息、(4)私信的位置信息、(5)照片的位置信息 * @param objid objid */ private void deleteLocation(int objtype,int objid) { StringBuffer url = new StringBuffer(UrlConfig.delete_location); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&objtype=" + objtype); url.append("&objid=" + objid); ServiceUtils.dout("deleteLocation url:" + url.toString()); try { String result = HttpUtils.doGet(url.toString()); ServiceUtils.dout("deleteLocation result:" + result); Gson gson = new Gson(); } catch (Exception e) { e.printStackTrace(); } } public void doPicPaint(int btid,int optype){ this.btId = btid; UICore.eventTask(this, activity, EXEU_SET_BTPIC_PAINT, "", optype); } /** * 设置瓶子照片涂鸦权限接口 * @param btid 瓶子ID * @param optype 设置是否允许涂鸦。选择项:不允许(0)、允许(1) */ private void setBtpicPaint(int btid,int optype) { this.btId = btid; StringBuffer url = new StringBuffer(UrlConfig.set_btpic_paint); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&btid=" + btid); url.append("&optype=" + optype); ServiceUtils.dout("setBtpicPaint url:" + url.toString()); try { String result = HttpUtils.doGet(url.toString()); ServiceUtils.dout("setBtpicPaint result:" + result); if (result != null) { JSONObject object = new JSONObject(result); JSONObject resultObj = object.getJSONObject("results"); int authok = resultObj.getInt("success"); if (authok == 0) { String errmsg = resultObj.getString("errmsg"); Message msg = Message.obtain(handler, EXEU_GET_TIMELINE_FAILED, errmsg); handler.sendMessage(msg); } else { String successmsg = resultObj.getString("successmsg"); Message msg = Message.obtain(handler, EXEU_SET_BTPIC_PAINT, successmsg); handler.sendMessage(msg); } } } catch (Exception e) { e.printStackTrace(); } } private void getTimeLine(int mode) { if (AppContext.getInstance().getLogin_uid() == 0 || AppContext.getInstance().getLogin_token() == null) { initConfig(); } StringBuffer url = new StringBuffer(UrlConfig.get_bt_timeline); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&mode=" + mode); url.append("&count=10"); url.append("&page=1"); url.append("&likescount=5"); url.append("&feedscount=5"); ServiceUtils.dout("timeline url:" + url.toString()); try { String result = HttpUtils.doGet(url.toString()); if (result == null) { return; } System.out.println("result:" + result); Gson gson = new Gson(); bottlelist = gson.fromJson(result, BottleTimelineInfo.class); if (bottlelist.getResults().getAuthok() == 1) { mBottleList = bottlelist.getBts_list(); Message message = Message.obtain(handler); message.what = EXEU_GET_TIMELINE; handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_GET_TIMELINE_FAILED, bottlelist.getResults() .getErrmsg()); handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } private void getTimeLineForRefresh(int mode) { if (AppContext.getInstance().getLogin_uid() == 0 || AppContext.getInstance().getLogin_token() == null) { initConfig(); } StringBuffer url = new StringBuffer(UrlConfig.get_bt_timeline); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&mode=" + mode); url.append("&count=10"); url.append("&page=1"); url.append("&likescount=5"); url.append("&feedscount=5"); ServiceUtils.dout("timeline url:" + url.toString()); try { String result = HttpUtils.doGet(url.toString()); if (result == null) { return; } System.out.println("result:" + result); Gson gson = new Gson(); bottlelist = gson.fromJson(result, BottleTimelineInfo.class); if (bottlelist.getResults().getAuthok() == 1) { mBottleList = bottlelist.getBts_list(); handler.sendEmptyMessage(EXEU_GET_TIMELINE); } else { Message message = handler.obtainMessage(EXEU_GET_TIMELINE_FAILED, bottlelist.getResults().getErrmsg()); handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } private void getMoreTimeLine(int page, int mode) { StringBuffer url = new StringBuffer(UrlConfig.get_bt_timeline); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&mode=" + mode); url.append("&count=10"); url.append("&page=" + page); url.append("&likescount=10"); url.append("&feedscount=5"); ServiceUtils.dout("timeline url:" + url.toString()); try { String result = HttpUtils.doGet(url.toString()); if (result == null) { return; } System.out.println("result:" + result); Gson gson = new Gson(); bottlelist = null; bottlelist = gson.fromJson(result, BottleTimelineInfo.class); Message message = null; if (bottlelist.getResults().getAuthok() == 1) { if (null != bottlelist.getBts_list() && bottlelist.getBts_list().size() > 0) { mBottleList.addAll(bottlelist.getBts_list()); message = Message.obtain(handler); message.what = EXEU_GET_MORE_TIMELINE; handler.sendMessage(message); } else { message = Message.obtain(handler); message.what = EXEU_GET_MORE_TIMELINE_NOTHING; handler.sendMessage(message); } } else { message = handler.obtainMessage(EXEU_GET_TIMELINE_FAILED, bottlelist.getResults().getErrmsg()); handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } private void setAdapterForThis() { if (null != bottlelist) { LanguageConfigTable languageConfigTable = new LanguageConfigTable(); LanguageConfig languageCon = languageConfigTable.getBottleLanguageConfig(); RelativeLayout mProfileInfo = (RelativeLayout) mheaderView .findViewById(R.id.rl_tlime_profile_bottle); View line_profile_bottle = (View)mheaderView.findViewById(R.id.line_profile_bottle); RelativeLayout mThrowBottle = (RelativeLayout) mheaderView .findViewById(R.id.rl_tlime_throw_bottle); View line_throw_bottle = (View)mheaderView.findViewById(R.id.line_throw_bottle); RelativeLayout mGainBottle = (RelativeLayout) mheaderView .findViewById(R.id.rl_tlime_gain_bottle); View line_gain_bottle = (View)mheaderView.findViewById(R.id.line_gain_bottle); LoginUserInfoTable loginUserInfoTable = new LoginUserInfoTable(); LoginUserInfoEntry loginUserInfoEntry = loginUserInfoTable .getLoginUserInfo(AppContext.getInstance().getLogin_uid()); if (null != loginUserInfoEntry && loginUserInfoEntry.getBasicinfo_fullfill() == 0) { mProfileInfo.setVisibility(View.VISIBLE); line_profile_bottle.setVisibility(View.VISIBLE); RemoteImageView img_head = (RemoteImageView) mheaderView .findViewById(R.id.iv_author_photo); LoginUserInfoTable userInfoTable = new LoginUserInfoTable(); if (null != userInfoTable.getLoginUserInfo(AppContext .getInstance().getLogin_uid())) { String avatar = userInfoTable.getLoginUserInfo( AppContext.getInstance().getLogin_uid()) .getAvatar(); if (!TextUtils.isEmpty(avatar)) { img_head.setDefaultImage(R.drawable.avatar_default_small); img_head.setImageUrl(avatar); } } ImageView img_Profile = (ImageView) mheaderView .findViewById(R.id.iv_profile_info); img_Profile.setOnClickListener(this); TextView tvProfileTips = (TextView) mheaderView .findViewById(R.id.tv_bottle_profile_tips_2); tvProfileTips.setText(loginUserInfoEntry.getBasicinfo_tip()); Button bt_profile = (Button) mheaderView .findViewById(R.id.bt_bottle_profile_try); bt_profile.setOnClickListener(this); } else { mProfileInfo.setVisibility(View.GONE); line_profile_bottle.setVisibility(View.GONE); } if (bottlelist.getShowtips().getShow_sendbt_tips() == 1) { mThrowBottle.setVisibility(View.VISIBLE); line_throw_bottle.setVisibility(View.VISIBLE); RemoteImageView img_head = (RemoteImageView) mheaderView .findViewById(R.id.iv_throw_author_photo); if (null != loginUserInfoTable.getLoginUserInfo(AppContext .getInstance().getLogin_uid())) { String avatar = loginUserInfoTable.getLoginUserInfo( AppContext.getInstance().getLogin_uid()) .getAvatar(); if (!TextUtils.isEmpty(avatar)) { img_head.setDefaultImage(R.drawable.avatar_default_small); img_head.setImageUrl(avatar); } } String bottleThrowTips1 = null; String bottleThrowTips2 = null; if (AppContext.language == 1) { bottleThrowTips1 = languageCon.getBottle_throw_tips_cn(); bottleThrowTips2 = languageCon.getBottle_throw_tips_2_cn(); }else { bottleThrowTips1 = languageCon.getBottle_throw_tips_en(); bottleThrowTips2 = languageCon.getBottle_throw_tips_2_en(); } TextView tvThrowTips = (TextView) mheaderView .findViewById(R.id.tv_bottle_throw_tips); tvThrowTips.setText(bottleThrowTips1); TextView tvThrowTip2 = (TextView) mheaderView .findViewById(R.id.tv_bottle_throw_tips_2); tvThrowTip2.setText(bottleThrowTips2); ImageView img_Throw = (ImageView) mheaderView.findViewById(R.id.iv_send_bottle); img_Throw.setOnClickListener(this); Button bt_throw = (Button) mheaderView.findViewById(R.id.bt_bottle_throw_try); bt_throw.setOnClickListener(this); } else { mThrowBottle.setVisibility(View.GONE); line_throw_bottle.setVisibility(View.GONE); } if (bottlelist.getShowtips().getShow_gainbt_tips() == 1) { mGainBottle.setVisibility(View.VISIBLE); line_gain_bottle.setVisibility(View.VISIBLE); RemoteImageView img_head = (RemoteImageView) mheaderView .findViewById(R.id.iv_gain_author_photo); if (null != loginUserInfoTable.getLoginUserInfo(AppContext .getInstance().getLogin_uid())) { String avatar = loginUserInfoTable.getLoginUserInfo( AppContext.getInstance().getLogin_uid()).getAvatar(); if (!TextUtils.isEmpty(avatar)) { img_head.setDefaultImage(R.drawable.avatar_default_small); img_head.setImageUrl(avatar); } } String bottleGainTips1 = null; String bottleGainTips2 = null; if (AppContext.language == 1) { bottleGainTips1 = languageCon.getBottle_gain_tips_cn(); bottleGainTips2 = languageCon.getBottle_gain_tips_2_cn(); }else { bottleGainTips1 = languageCon.getBottle_gain_tips_en(); bottleGainTips2 = languageCon.getBottle_gain_tips_2_en(); } TextView tvGainTips = (TextView) mheaderView .findViewById(R.id.tv_bottle_gain_tips); tvGainTips.setText(bottleGainTips1); TextView tvGainTip2 = (TextView) mheaderView .findViewById(R.id.tv_bottle_gain_tips_2); tvGainTip2.setText(bottleGainTips2); ImageView img_Gain = (ImageView) mheaderView .findViewById(R.id.iv_gain_bottle); img_Gain.setOnClickListener(this); Button bt_gain = (Button) mheaderView .findViewById(R.id.bt_bottle_gain_try); bt_gain.setOnClickListener(this); } else { mGainBottle.setVisibility(View.GONE); line_gain_bottle.setVisibility(View.GONE); } if (mProfileInfo.getVisibility() == View.VISIBLE && mThrowBottle.getVisibility() == View.VISIBLE && mGainBottle.getVisibility() == View.VISIBLE ) { line_gain_bottle.setVisibility(View.GONE); }else if (mProfileInfo.getVisibility() == View.VISIBLE && mThrowBottle.getVisibility() == View.VISIBLE && mGainBottle.getVisibility() == View.GONE) { line_throw_bottle.setVisibility(View.GONE); } else if (mProfileInfo.getVisibility() == View.VISIBLE && mThrowBottle.getVisibility() == View.GONE && mGainBottle.getVisibility() == View.GONE) { line_profile_bottle.setVisibility(View.GONE); } else if (mProfileInfo.getVisibility() == View.GONE && mThrowBottle.getVisibility() == View.VISIBLE && mGainBottle.getVisibility() == View.VISIBLE) { line_gain_bottle.setVisibility(View.GONE); } else if (mProfileInfo.getVisibility() == View.GONE && mThrowBottle.getVisibility() == View.VISIBLE && mGainBottle.getVisibility() == View.GONE) { line_throw_bottle.setVisibility(View.GONE); } else if (mProfileInfo.getVisibility() == View.GONE && mThrowBottle.getVisibility() == View.GONE && mGainBottle.getVisibility() == View.VISIBLE) { line_gain_bottle.setVisibility(View.GONE); } // listView.addFooterView(v); // if // (mProfileInfo.getVisibility()==View.VISIBLE||mThrowBottle.getVisibility()==View.VISIBLE||mGainBottle.getVisibility()==View.VISIBLE) // { // chatHistoryAdapter = new PublicActivityAdapter(activity,this, // bottlelist,true); // }else { mTimeLineAdapter = new PublicActivityAdapter(activity, this, mBottleList, false); // } listView.setAdapter(mTimeLineAdapter); } } /** 喜欢pop */ private void initLikePopupWindow() { LayoutInflater mLayoutInflater = LayoutInflater.from(activity); mLikeView = mLayoutInflater.inflate(R.layout.pop_bottle_like, null); ImageView iv_unlike = (ImageView) mLikeView .findViewById(R.id.iv_unlike); ImageView iv_like = (ImageView) mLikeView.findViewById(R.id.iv_like); iv_unlike.setOnClickListener(this); iv_like.setOnClickListener(this); mLikePopview = new CustomPopupWindow(mLikeView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); mLikePopview.setBackgroundDrawable(getResources().getDrawable( R.drawable.like_frame_right)); mLikePopview.setOutsideTouchable(true); mLikePopview.update(); mLikePopview.setTouchable(true); mLikePopview.setFocusable(true); } ViewHolder holder; BottleEntry bottleEntry; public int position; View itemView = null; private BottleEntry mBottleEntry; public void showInfoPopupWindow(View achorView, int btId, ViewHolder holder, int position) { this.btId = btId; this.position = position; this.holder = holder; if (mLikePopview.isShowing()) { mLikePopview.dismiss(); } else { // mLikePopview.showAtLocation(achorView, Gravity.RIGHT, 0, 0); mLikePopview.showAsDropDown(achorView, -150, -70); } } public void doOpenBottle(int btId, int position) { this.btId = btId; this.position = position; UICore.eventTask(this, activity, EXEU_OPEN_BOTTLE_OPERATION, "", null); } public void doDropBottle(int btId, int position) { this.btId = btId; this.position = position; UICore.eventTask(this, activity, EXEU_DROP_BOTTLE_OPERATION, "", null); } private void dropBottle(int btId) { StringBuffer url = new StringBuffer(UrlConfig.discard_bt); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&btid=" + btId); ServiceUtils.dout("dropBottle url:" + url.toString()); try { String results = HttpUtils.doGet(url.toString()); ServiceUtils.dout("dropBottle result:" + results); if (null != results) { JSONObject obj = new JSONObject(results); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); String errmsg = resultObj.getString("errmsg"); String successmsg = resultObj.getString("successmsg"); if (success == 1) { Message message = handler.obtainMessage( EXEU_DROP_BOTTLE_SUCCESS, successmsg); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_DROP_BOTTLE_FAILED, errmsg); handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); } } private void openBottle(int btId) { StringBuffer url = new StringBuffer(UrlConfig.open_bt); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&btid=" + btId); ServiceUtils.dout("openBottle url:" + url.toString()); try { String results = HttpUtils.doGet(url.toString()); ServiceUtils.dout("openBottle result:" + results); if (null != results) { JSONObject obj = new JSONObject(results); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); String errmsg = resultObj.getString("errmsg"); String successmsg = resultObj.getString("successmsg"); if (success == 1) { StringBuffer mSingleBottleUrl = new StringBuffer( UrlConfig.get_bt_timeline); mSingleBottleUrl.append("?clitype=2"); mSingleBottleUrl.append("&language=" + AppContext.language); mSingleBottleUrl.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); mSingleBottleUrl.append("&login_token=" + AppContext.getInstance().getLogin_token()); mSingleBottleUrl.append("&mode=4&btid=" + btId); mSingleBottleUrl.append("&feedscount=5"); ServiceUtils.dout("get open bottle url:" + mSingleBottleUrl.toString()); String singleResult = HttpUtils.doGet(mSingleBottleUrl .toString()); ServiceUtils.dout("get open bottle results :" + singleResult.toString()); Gson gson = new Gson(); BottleTimelineInfo singleBottleInfo = gson.fromJson( singleResult, BottleTimelineInfo.class); // singleBottleInfo.get // BottleEntry mNewBottleEntry = // singleBottleInfo.getBts_list().get(0); mBottleList.set(position, singleBottleInfo.getBts_list() .get(0)); Message message = handler.obtainMessage( EXEU_OPEN_BOTTLE_SUCCESS, successmsg); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_OPEN_BOTTLE_FAILED, errmsg); handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); } } private void getSingleBottle(int btId) { StringBuffer mSingleBottleUrl = new StringBuffer( UrlConfig.get_bt_timeline); mSingleBottleUrl.append("?clitype=2"); mSingleBottleUrl.append("&language=" + AppContext.language); mSingleBottleUrl.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); mSingleBottleUrl.append("&login_token=" + AppContext.getInstance().getLogin_token()); mSingleBottleUrl.append("&mode=4&btid=" + btId); mSingleBottleUrl.append("&likescount=5"); mSingleBottleUrl.append("&feedscount=5"); ServiceUtils.dout("getSingleBottle url:" + mSingleBottleUrl.toString()); String singleResult = null; try { singleResult = HttpUtils.doGet(mSingleBottleUrl.toString()); ServiceUtils.dout("getSingleBottle results :" + singleResult.toString()); Gson gson = new Gson(); BottleTimelineInfo singleBottleInfo = gson.fromJson(singleResult, BottleTimelineInfo.class); if (singleBottleInfo.getResults().getAuthok() == 1) { mBottleEntry = singleBottleInfo.getBts_list().get(0); Message message = handler .obtainMessage(EXEU_GET_SINGLE_BOTTLE_SUCCESS); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_GET_TIMELINE_FAILED, singleBottleInfo.getResults() .getErrmsg()); handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } /** * 喜欢瓶子的操作 * * @param btId * 瓶子ID * @param likeType * 喜欢or不喜欢 <---> 1 or 2 */ private void likeOperation(int btId, int likeType) { StringBuffer url = new StringBuffer(UrlConfig.likeop_bt); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&btid=" + btId); url.append("&liketype=" + likeType); ServiceUtils.dout("likeOperation url:" + url.toString()); try { String results = HttpUtils.doGet(url.toString()); ServiceUtils.dout("likeOperation result:" + results); if (null != results) { JSONObject obj = new JSONObject(results); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); String errmsg = resultObj.getString("errmsg"); String successmsg = resultObj.getString("successmsg"); Message message = null; if (success == 1) { switch (likeType) { case 1: message = handler.obtainMessage(EXEU_LIKE_OPERATION, successmsg); handler.sendMessage(message); break; case 2: message = handler.obtainMessage(EXEU_UNLIKE_OPERATION, successmsg); handler.sendMessage(message); break; default: break; } } else { message = handler.obtainMessage(EXEU_LIKE_OPERATION_FAILED, errmsg); handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); } } public void doMenuItemSelect(int mode) { this.mode = mode; this.page = 1; UICore.eventTask(this, activity, EXEU_GET_MENU_TIMELINE, "", null); } @Override public boolean handleMessage(Message msg) { switch (msg.what) { case EXEU_GET_TIMELINE: setAdapterForThis(); listView.onRefreshComplete(); new Thread() { public void run() { getPushNotice(); }; }.start(); break; case EXEU_GET_MORE_TIMELINE: mTimeLineAdapter.notifyDataSetChanged(); // listView.setSelection(visibleLastIndex - visibleItemCount + 1); // // 设置选中项 break; case EXEU_DROP_BOTTLE_SUCCESS: mBottleList.remove(position); mTimeLineAdapter.notifyDataSetChanged(); String message = (String) msg.obj; activity.onToast(message); break; case EXEU_DROP_BOTTLE_FAILED: activity.onToast((String) msg.obj); break; case EXEU_OPEN_BOTTLE_SUCCESS: mTimeLineAdapter.notifyDataSetChanged(); activity.onToast((String) msg.obj); break; case EXEU_SET_BTPIC_PAINT: activity.onToast((String) msg.obj); UICore.eventTask(this, activity, EXEU_GET_SINGLE_BOTTLE_SUCCESS, "EXEU_GET_TIMELINE", null); break; case EXEU_OPEN_BOTTLE_FAILED: activity.onToast((String) msg.obj); break; case EXEU_LIKE_OPERATION: activity.onToast((String) msg.obj); UICore.eventTask(this, activity, EXEU_GET_SINGLE_BOTTLE_SUCCESS, "EXEU_GET_TIMELINE", null); break; case EXEU_UNLIKE_OPERATION: activity.onToast((String) msg.obj); UICore.eventTask(this, activity, EXEU_GET_SINGLE_BOTTLE_SUCCESS, "EXEU_GET_TIMELINE", null); break; case EXEU_LIKE_OPERATION_FAILED: activity.onToast((String) msg.obj); break; case EXEU_GET_SINGLE_BOTTLE_SUCCESS: mBottleList.set(position, mBottleEntry); mTimeLineAdapter.notifyDataSetChanged(); break; case EXEU_SEND_BOTTLE_PRIV_SUCCESS: final Bundle bundle = msg.getData(); try { BottleTypeTable table = new BottleTypeTable(); BottleTypeEntry bottleEntry = table.getBottleType(bundle.getInt("type")); int locationSelect = bottleEntry.getBttype_location_select(); String[] choices = new String[2]; if (locationSelect > 1) { choices[0] = getString(R.string.choose_location_here_throw); choices[1] = getString(R.string.choose_location_search_throw); } else { choices = new String[1]; choices[0] = getString(R.string.choose_location_here_throw); } chooseAction(choices, locationSelect , bundle.getInt("type")); } catch (Exception e) { e.printStackTrace(); } break; case EXEU_SEND_BOTTLE_PRIV_SUCCESS_NOT_ENABLE: activity.onToast((String) msg.obj); break; case EXEU_SEND_BOTTLE_PRIV_FAILED: activity.onToast((String) msg.obj); break; case EXEU_GET_TIMELINE_FAILED: activity.onToast((String) msg.obj); break; case EXEU_REFRESH_TIMELINE: new Thread() { public void run() { getPushNotice(); }; }.start(); break; case EXEU_GET_MORE_TIMELINE_NOTHING: activity.onToast(TextUtil.R("no_more_data")); loadMoreView.setVisibility(View.GONE); mTimeLineAdapter.notifyDataSetChanged(); // listView.setSelection(visibleLastIndex - visibleItemCount); break; case throw_bottle_init_location: // try { // int bottleid = Integer.parseInt(msg.obj.toString()); // Intent intent2 = new Intent(activity, ThrowBottleSettingActivity.class); // intent2.putExtra("bttype_id", bottleid); // intent2.putExtra("bt_geo_lng", longitude); // intent2.putExtra("bt_geo_lat", latitude); // startActivity(intent2); // } catch (Exception e) { // e.printStackTrace(); // } break; case EXEU_PASTERDIR_PAY: activity.onToast((String) msg.obj); break; case EXEU_PUSH_NOTICE: ((HomeActivity) getActivity()).pushNoticeUpdateUI(); break; default: break; } return false; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.iv_send_bottle: Intent throwIntent = new Intent(activity, ChooseBottleActivity.class); throwIntent.putExtra("type", "throw"); startActivity(throwIntent); break; case R.id.iv_gain_bottle: Intent tryIntent = new Intent(activity, ChooseBottleActivity.class); tryIntent.putExtra("type", "try"); startActivity(tryIntent); break; case R.id.iv_profile_info: Intent settingIntent = new Intent(activity, SettingActivity.class); startActivity(settingIntent); break; case R.id.iv_unlike:// 不喜欢 mLikePopview.dismiss(); UICore.eventTask(this, activity, EXEU_UNLIKE_OPERATION, "", null); break; case R.id.iv_like:// 喜欢 mLikePopview.dismiss(); UICore.eventTask(this, activity, EXEU_LIKE_OPERATION, "", null); break; case R.id.bt_bottle_throw_try: Intent throwIntent2 = new Intent(activity, ChooseBottleActivity.class); throwIntent2.putExtra("type", "throw"); startActivity(throwIntent2); break; case R.id.bt_bottle_gain_try: Intent tryIntent2 = new Intent(activity, ChooseBottleActivity.class); tryIntent2.putExtra("type", "try"); startActivity(tryIntent2); break; case R.id.bt_bottle_profile_try: Intent settingIntent2 = new Intent(activity, SettingActivity.class); startActivity(settingIntent2); break; default: break; } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { try { if (mTimeLineAdapter != null) { int itemsLastIndex = mTimeLineAdapter.getCount() + 2; // 数据集最后一项的索引 int lastIndex = itemsLastIndex + 1; // 加上底部的loadMoreView项 和 head项 ServiceUtils.dout(TAG + " lastIndex: " + lastIndex); ServiceUtils.dout(TAG + " visibleLastIndex:" + visibleLastIndex); if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == lastIndex) { // 如果是自动加载,可以在这里放置异步加载数据的代码 page++; loadMoreView.setVisibility(View.VISIBLE); UICore.eventTask(this, activity, EXEU_GET_MORE_TIMELINE, null, null); Log.i("LOADMORE", "loading..."); } } } catch (Exception e) { e.printStackTrace(); } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { listView.setFirstVisiableItem(firstVisibleItem); this.visibleItemCount = visibleItemCount; visibleLastIndex = firstVisibleItem + visibleItemCount; } public void doGetBottleInfo() { UICore.eventTask(this, activity, EXEU_GET_BOTTLE_INFO, "", null); } public void initConfig() { String country = getResources().getConfiguration().locale.getCountry(); if (country.equals("CN")) { AppContext.setLanguage(1); } else { AppContext.setLanguage(0); } SharedPreferences preferences = getActivity().getSharedPreferences("Preferences_userinfo", Activity.MODE_APPEND); int login_uid = preferences.getInt("login_uid", 0); String login_token = preferences.getString("login_token", null); AppContext.getInstance().setLogin_uid(login_uid); AppContext.getInstance().setLogin_token(login_token); if (login_uid == 0 || login_token == null) { Intent intent = new Intent(getActivity(), SplashActivity.class); getActivity().startActivity(intent); getActivity().finish(); } } private void chooseAction(String[] choices, final int locationSelected, final int bottleId) { final Context dialogContext = new ContextThemeWrapper(activity, android.R.style.Theme_Light); final ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (which == 0) { Intent intent2 = new Intent(activity, ThrowBottleSettingActivity.class); intent2.putExtra("bttype_id", bottleId); intent2.putExtra("bt_geo_lng", AppContext.getInstance().getLongitude()); intent2.putExtra("bt_geo_lat", AppContext.getInstance().getLatitude()); startActivity(intent2); } else { Intent intent = new Intent(activity, ChooseLocationTabsActivity.class); intent.putExtra("type", "throw"); intent.putExtra("bottleId", bottleId); intent.putExtra("locationSelect", locationSelected); startActivity(intent); } } }); builder.create().show(); } }
Java
package com.outsourcing.bottle.ui.fragment; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Handler.Callback; import android.os.Message; import android.support.v4.app.Fragment; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import com.outsourcing.bottle.R; import com.outsourcing.bottle.domain.LocationEntry; import com.outsourcing.bottle.domain.UrlConfig; import com.outsourcing.bottle.ui.BottleTipsActivity; import com.outsourcing.bottle.ui.ChooseLocationTabsActivity; import com.outsourcing.bottle.ui.ThrowBottleSettingActivity; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.BasicUIEvent; import com.outsourcing.bottle.util.HttpUtils; import com.outsourcing.bottle.util.UICore; /** * * @author 06peng * */ public class NearByFragment extends Fragment implements BasicUIEvent, Callback { private final int init_location_info = 1; private final int gain_bottle = 3; private final int gain_bottle_success = 4; private final int gain_bottle_error = 5; private final int throw_bottle = 6; private ListView listView; private ChooseLocationTabsActivity activity; private List<LocationEntry> locations; private LocationAdapter adapter; private LocationEntry myLocation; private Handler handler; private ImageView refresh; private EditText keywordView; public NearByFragment() { super(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); handler = new Handler(this); this.activity = (ChooseLocationTabsActivity) getActivity(); UICore.eventTask(this, activity, init_location_info, getString(R.string.init_data), null); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.choose_location, null); listView = (ListView) view.findViewById(R.id.choose_location_list); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { LocationEntry entry = locations.get(arg2); if (activity.type.equals("try")) { UICore.eventTask(NearByFragment.this, activity, gain_bottle, getString(R.string.init_data), entry); } else { UICore.eventTask(NearByFragment.this, activity, throw_bottle, getString(R.string.init_data), entry); } } }); refresh = (ImageView) view.findViewById(R.id.choose_location_refresh); refresh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { search(); } }); keywordView = (EditText) view.findViewById(R.id.choose_location_search_edit); keywordView.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { search(); return false; } }); return view; } @Override public void onResume() { super.onResume(); adapter = new LocationAdapter(); listView.setAdapter(adapter); } @Override public void execute(int mes, Object obj) { switch (mes) { case init_location_info: initLocationInfo(obj == null ? null : (String)obj); locate(); handler.sendEmptyMessage(init_location_info); break; case gain_bottle: LocationEntry entry = (LocationEntry) obj; gainBottle(entry); break; case throw_bottle: LocationEntry entry_throw = (LocationEntry) obj; Message msg = Message.obtain(handler, throw_bottle, entry_throw); handler.sendMessage(msg); break; default: break; } } private void initLocationInfo(String name) { String location = String.valueOf(AppContext.getInstance().getLatitude()) + "," + String.valueOf(AppContext.getInstance().getLongitude()); String url = UrlConfig.search_offset + "?"; url += "latlng=" + location; if (name != null) { url += "&name=" + name; } url += "&language=" + (AppContext.language == 1 ? "zh" : "en") + "&login_uid=" + AppContext.getInstance().getLogin_uid(); try { String result = HttpUtils.doGet(url); JSONObject obj = new JSONObject(result); JSONArray arrays = obj.getJSONArray("results"); locations = new ArrayList<LocationEntry>(); for (int i = 1;i < arrays.length();i++) { JSONObject object = arrays.getJSONObject(i); JSONObject geometryObj = object.getJSONObject("geometry"); JSONObject locationObj = geometryObj.getJSONObject("location"); double latitudeObj = locationObj.getDouble("lat"); double longitudeObj = locationObj.getDouble("lng"); LocationEntry entry = new LocationEntry(); entry.setLocationName(object.getString("name")); entry.setAddress(object.getString("vicinity")); JSONArray typeArray = object.getJSONArray("types"); entry.setType(typeArray.getString(0)); entry.setLatitude(latitudeObj); entry.setLongitude(longitudeObj); entry.setReference(object.getString("reference")); locations.add(entry); } } catch (Exception e) { e.printStackTrace(); } } private void locate() { myLocation = new LocationEntry(); myLocation.setLatitude(AppContext.getInstance().getLatitude()); myLocation.setLongitude(AppContext.getInstance().getLongitude()); String params = String.valueOf(AppContext.getInstance().getLatitude()) + "," + String.valueOf(AppContext.getInstance().getLongitude()); String language = AppContext.language == 1 ? "zh" : "en"; String url = "http://www.mobibottle.com/openapi/geocode_offset.json?" + "latlng="+params+"&sensor=true&language=" + language + "&login_uid=" + AppContext.getInstance().getLogin_uid(); try { String result = HttpUtils.doGet(url); JSONObject object = new JSONObject(result); JSONArray arrays = object.getJSONArray("results"); for (int i = 0;i < arrays.length();i++) { JSONObject jsonObject = arrays.getJSONObject(i); if (jsonObject != null) { JSONArray addressArrays = jsonObject.getJSONArray("address_components"); for (int j = 0;j < addressArrays.length();j++) { JSONObject obj = addressArrays.getJSONObject(j); JSONArray typeArray = obj.getJSONArray("types"); for (int k = 0;k < typeArray.length();k++) { String typename = typeArray.getString(k); if (typename.equals("locality")) { myLocation.setCity(obj.getString("long_name")); } else if (typename.equals("administrative_area_level_1")) { myLocation.setProvince(obj.getString("long_name")); } else if (typename.equals("country")) { myLocation.setCountry(obj.getString("long_name")); } } } break; } } } catch (Exception e) { e.printStackTrace(); } } private void gainBottle(LocationEntry entry) { String url = UrlConfig.gain_bt; HashMap<String, String> paramsMap = new HashMap<String, String>(); paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid())); paramsMap.put("login_token", AppContext.getInstance().getLogin_token()); paramsMap.put("nettypeid", String.valueOf(activity.bottleId)); paramsMap.put("bt_geo_lng", String.valueOf(entry.getLongitude())); paramsMap.put("bt_geo_lat", String.valueOf(entry.getLatitude())); paramsMap.put("bt_geo_reference", entry.getReference()); try { String result = HttpUtils.doPost(activity, url, paramsMap); JSONObject obj = new JSONObject(result); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); if (success == 1) { String successmsg = resultObj.getString("successmsg"); int gainbt_type = resultObj.getInt("gainbt_type"); String gainbt_msg = resultObj.getString("gainbt_msg"); Object[] objs = new Object[3]; objs[0] = successmsg; objs[1] = gainbt_type; objs[2] = gainbt_msg; Message msg = Message.obtain(handler, gain_bottle_success, objs); handler.sendMessage(msg); } else { String errmsg = resultObj.getString("errmsg"); Message msg = Message.obtain(handler, gain_bottle_error, errmsg); handler.sendMessage(msg); } } catch (Exception e) { e.printStackTrace(); } } public void search() { String keyword = keywordView.getText().toString().trim(); UICore.eventTask(NearByFragment.this, activity, init_location_info, getString(R.string.init_data), keyword); } public class LocationAdapter extends BaseAdapter { @Override public int getCount() { return locations == null ? 0 : locations.size(); } @Override public Object getItem(int arg0) { return locations == null ? null : locations.get(arg0); } @Override public long getItemId(int arg0) { return arg0; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view; ViewHolder holder = new ViewHolder(); if (convertView != null) { view = convertView; holder = (ViewHolder) view.getTag(); } else { view = LayoutInflater.from(activity).inflate(R.layout.choose_location_listitem, null); holder.nameView = (TextView) view.findViewById(R.id.choose_location_listitem_name); holder.vicinityView = (TextView) view.findViewById(R.id.choose_location_listitem_vicinity); holder.typeView = (TextView) view.findViewById(R.id.choose_location_listitem_type); view.setTag(holder); } LocationEntry entry = locations.get(position); if (entry != null) { holder.nameView.setText(entry.getLocationName()); holder.vicinityView.setText(entry.getAddress()); holder.typeView.setText(entry.getType()); } return view; } } public static class ViewHolder { TextView nameView; TextView vicinityView; TextView typeView; } @Override public boolean handleMessage(Message msg) { switch (msg.what) { case init_location_info: adapter = new LocationAdapter(); listView.setAdapter(adapter); break; case gain_bottle_error: activity.onToast((String) msg.obj); break; case gain_bottle_success: Object[] objs = (Object[]) msg.obj; activity.onToast((String) objs[0]); Intent intent = new Intent(activity, BottleTipsActivity.class); intent.putExtra("type", "try"); intent.putExtra("bottleId", Integer.parseInt(objs[1].toString())); intent.putExtra("gainbt_msg", objs[2].toString()); startActivity(intent); break; case throw_bottle: LocationEntry entry = (LocationEntry) msg.obj; Intent intent2 = new Intent(activity, ThrowBottleSettingActivity.class); intent2.putExtra("bttype_id", activity.bottleId); intent2.putExtra("bt_geo_lng", entry.getLongitude()); intent2.putExtra("bt_geo_lat", entry.getLatitude()); intent2.putExtra("reference", entry.getReference()); startActivity(intent2); break; default: break; } return false; } }
Java
package com.outsourcing.bottle.ui.fragment; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.json.JSONArray; import org.json.JSONObject; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Handler.Callback; import android.os.Message; import android.support.v4.app.Fragment; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; import com.outsourcing.bottle.R; import com.outsourcing.bottle.domain.LocationEntry; import com.outsourcing.bottle.domain.PlatformBindConfig; import com.outsourcing.bottle.domain.UrlConfig; import com.outsourcing.bottle.ui.BottleTipsActivity; import com.outsourcing.bottle.ui.ChooseLocationTabsActivity; import com.outsourcing.bottle.ui.ThrowBottleSettingActivity; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.BasicUIEvent; import com.outsourcing.bottle.util.HttpUtils; import com.outsourcing.bottle.util.UICore; /** * * @author 06peng * */ public class CountryFragment extends Fragment implements BasicUIEvent, Callback { private final int search_location = 2; private final int gain_bottle = 3; private final int gain_bottle_success = 4; private final int gain_bottle_error = 5; private final int throw_bottle = 6; private ListView listView; private ChooseLocationTabsActivity activity; private int currentItem; private List<LocationEntry> locations; private LocationAdapter adapter; private LocationEntry myLocation; private Handler handler; private ImageView refresh; private EditText keywordView; public CountryFragment() { super(); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); handler = new Handler(this); this.activity = (ChooseLocationTabsActivity) getActivity(); Bundle bundle = getArguments(); if (bundle != null) { currentItem = bundle.getInt("currentItem"); } UICore.eventTask(this, activity, search_location, "search_location", null); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.choose_location, null); listView = (ListView) view.findViewById(R.id.choose_location_list); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { LocationEntry entry = locations.get(arg2); if (activity.type.equals("try")) { UICore.eventTask(CountryFragment.this, activity, gain_bottle, getString(R.string.init_data), entry); } else { UICore.eventTask(CountryFragment.this, activity, throw_bottle, getString(R.string.init_data), entry); } } }); refresh = (ImageView) view.findViewById(R.id.choose_location_refresh); refresh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { search(); } }); keywordView = (EditText) view.findViewById(R.id.choose_location_search_edit); keywordView.setHint(R.string.choose_location_country); keywordView.setOnEditorActionListener(new OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { search(); return false; } }); return view; } @Override public void onResume() { super.onResume(); adapter = new LocationAdapter(); listView.setAdapter(adapter); } @Override public void execute(int mes, Object obj) { switch (mes) { case search_location: locate(); getSearchLocation(obj == null ? "" : (String)obj); handler.sendEmptyMessage(search_location); break; case gain_bottle: LocationEntry entry = (LocationEntry) obj; gainBottle(entry); break; case throw_bottle: LocationEntry entry_throw = (LocationEntry) obj; Message msg = Message.obtain(handler, throw_bottle, entry_throw); handler.sendMessage(msg); break; default: break; } } public void search() { String keyword = keywordView.getText().toString().trim(); UICore.eventTask(CountryFragment.this, activity, search_location, getString(R.string.init_data), keyword); } private void locate() { myLocation = new LocationEntry(); myLocation.setLatitude(AppContext.getInstance().getLatitude()); myLocation.setLongitude(AppContext.getInstance().getLongitude()); String params = String.valueOf(AppContext.getInstance().getLatitude()) + "," + String.valueOf(AppContext.getInstance().getLongitude()); String language = AppContext.language == 1 ? "zh" : "en"; String url = "http://www.mobibottle.com/openapi/geocode_offset.json?" + "latlng="+params+"&sensor=true&language=" + language + "&login_uid=" + AppContext.getInstance().getLogin_uid(); try { String result = HttpUtils.doGet(url); JSONObject object = new JSONObject(result); JSONArray arrays = object.getJSONArray("results"); for (int i = 0;i < arrays.length();i++) { JSONObject jsonObject = arrays.getJSONObject(i); if (jsonObject != null) { JSONArray addressArrays = jsonObject.getJSONArray("address_components"); for (int j = 0;j < addressArrays.length();j++) { JSONObject obj = addressArrays.getJSONObject(j); JSONArray typeArray = obj.getJSONArray("types"); for (int k = 0;k < typeArray.length();k++) { String typename = typeArray.getString(k); if (typename.equals("locality")) { myLocation.setCity(obj.getString("long_name")); } else if (typename.equals("administrative_area_level_1")) { myLocation.setProvince(obj.getString("long_name")); } else if (typename.equals("country")) { myLocation.setCountry(obj.getString("long_name")); } } } break; } } } catch (Exception e) { e.printStackTrace(); } } private void getSearchLocation(String keyword) { String url = "http://www.mobibottle.com/openapi/google_get_autocomplete.json?"; String language = AppContext.language == 1 ? "zh" : "en" + "&login_uid=" + AppContext.getInstance().getLogin_uid(); if (currentItem == 1) { String input = keyword + "+" + myLocation.getCountry() + "+" + myLocation.getProvince() + "+" + myLocation.getCity(); url += "input=" + input + "&sensor=false&language=" + language + "&key=" + PlatformBindConfig.Goolge_Places_AppKey; } else if (currentItem == 2) { String input = keyword + "+" + myLocation.getCountry(); url += "input=" + input + "&sensor=false&language=" + language + "&key=" + PlatformBindConfig.Goolge_Places_AppKey; } else if (currentItem == 3) { url += "input=" + keyword + "&sensor=false&language=" + language + "&key=" + PlatformBindConfig.Goolge_Places_AppKey; } System.out.println(url); try { String result = HttpUtils.doGet(url); JSONObject obj = new JSONObject(result); JSONArray arrays = obj.getJSONArray("predictions"); locations = new ArrayList<LocationEntry>(); for (int i = 0;i < arrays.length();i++) { LocationEntry entry = new LocationEntry(); JSONObject object = arrays.getJSONObject(i); entry.setAddress(object.getString("description")); entry.setReference(object.getString("reference")); JSONArray typeArrays = object.getJSONArray("types"); String type = typeArrays.getString(0); entry.setType(type); JSONArray termsArrays = object.getJSONArray("terms"); JSONObject tearmObj = termsArrays.getJSONObject(0); entry.setLocationName(tearmObj.getString("value")); locations.add(entry); } } catch (Exception e) { e.printStackTrace(); } } private void gainBottle(LocationEntry entry) { String url = UrlConfig.gain_bt; HashMap<String, String> paramsMap = new HashMap<String, String>(); paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid())); paramsMap.put("login_token", AppContext.getInstance().getLogin_token()); paramsMap.put("nettypeid", String.valueOf(activity.bottleId)); paramsMap.put("bt_geo_lng", String.valueOf(entry.getLongitude())); paramsMap.put("bt_geo_lat", String.valueOf(entry.getLatitude())); paramsMap.put("bt_geo_reference", entry.getReference()); try { String result = HttpUtils.doPost(activity, url, paramsMap); JSONObject obj = new JSONObject(result); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); if (success == 1) { String successmsg = resultObj.getString("successmsg"); int gainbt_type = resultObj.getInt("gainbt_type"); String gainbt_msg = resultObj.getString("gainbt_msg"); Object[] objs = new Object[3]; objs[0] = successmsg; objs[1] = gainbt_type; objs[2] = gainbt_msg; Message msg = Message.obtain(handler, gain_bottle_success, objs); handler.sendMessage(msg); } else { String errmsg = resultObj.getString("errmsg"); Message msg = Message.obtain(handler, gain_bottle_error, errmsg); handler.sendMessage(msg); } } catch (Exception e) { e.printStackTrace(); } } public class LocationAdapter extends BaseAdapter { @Override public int getCount() { return locations == null ? 0 : locations.size(); } @Override public Object getItem(int arg0) { return locations == null ? null : locations.get(arg0); } @Override public long getItemId(int arg0) { return arg0; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view; ViewHolder holder = new ViewHolder(); if (convertView != null) { view = convertView; holder = (ViewHolder) view.getTag(); } else { view = LayoutInflater.from(activity).inflate(R.layout.choose_location_listitem, null); holder.nameView = (TextView) view.findViewById(R.id.choose_location_listitem_name); holder.vicinityView = (TextView) view.findViewById(R.id.choose_location_listitem_vicinity); holder.typeView = (TextView) view.findViewById(R.id.choose_location_listitem_type); view.setTag(holder); } LocationEntry entry = locations.get(position); if (entry != null) { holder.nameView.setText(entry.getLocationName()); holder.vicinityView.setText(entry.getAddress()); holder.typeView.setText(entry.getType()); } return view; } } public static class ViewHolder { TextView nameView; TextView vicinityView; TextView typeView; } @Override public boolean handleMessage(Message msg) { switch (msg.what) { case search_location: adapter = new LocationAdapter(); listView.setAdapter(adapter); break; case gain_bottle_error: activity.onToast((String) msg.obj); break; case gain_bottle_success: Object[] objs = (Object[]) msg.obj; activity.onToast((String) objs[0]); Intent intent = new Intent(activity, BottleTipsActivity.class); intent.putExtra("type", "try"); intent.putExtra("bottleId", Integer.parseInt(objs[1].toString())); intent.putExtra("gainbt_msg", objs[2].toString()); startActivity(intent); break; case throw_bottle: LocationEntry entry = (LocationEntry) msg.obj; Intent intent2 = new Intent(activity, ThrowBottleSettingActivity.class); intent2.putExtra("bttype_id", activity.bottleId); intent2.putExtra("bt_geo_lng", entry.getLongitude()); intent2.putExtra("bt_geo_lat", entry.getLatitude()); intent2.putExtra("reference", entry.getReference()); startActivity(intent2); break; default: break; } return false; } }
Java
package com.outsourcing.bottle.ui.fragment; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import com.outsourcing.bottle.R; import com.outsourcing.bottle.ui.SetAvatarAndNameActivity; import com.outsourcing.bottle.util.AppContext; /** * * @author 06peng * */ public class RegisterFragment extends Fragment { int currentItem; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.register_fragment, null); ImageView logo = (ImageView) view.findViewById(R.id.logo); ImageView logoTips = (ImageView) view.findViewById(R.id.logo_tips); ImageButton button = (ImageButton) view.findViewById(R.id.register_finish); Bundle bundle = getArguments(); if (bundle != null) { currentItem = bundle.getInt("logo"); switch (currentItem) { case 1: logo.setImageResource(R.drawable.splash_slide_1); if (AppContext.language == 1) { logoTips.setImageResource(R.drawable.text_01_cn); } else { logoTips.setImageResource(R.drawable.text_01_en); } break; case 2: logo.setImageResource(R.drawable.splash_slide_2); if (AppContext.language == 1) { logoTips.setImageResource(R.drawable.text_02_cn); } else { logoTips.setImageResource(R.drawable.text_02_en); } break; case 3: logo.setImageResource(R.drawable.splash_slide_3); if (AppContext.language == 1) { logoTips.setImageResource(R.drawable.text_03_cn); } else { logoTips.setImageResource(R.drawable.text_03_en); } break; case 4: logo.setImageResource(R.drawable.splash_slide_4); if (AppContext.language == 1) { logoTips.setImageResource(R.drawable.text_04_cn); } else { logoTips.setImageResource(R.drawable.text_04_en); } button.setVisibility(View.VISIBLE); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), SetAvatarAndNameActivity.class); getActivity().startActivity(intent); } }); break; default: logo.setImageResource(R.drawable.logo_new); break; } } return view; } }
Java
package com.outsourcing.bottle.ui.fragment; import java.util.List; import org.json.JSONObject; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.Handler.Callback; import android.os.Message; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.google.gson.Gson; import com.outsourcing.bottle.R; import com.outsourcing.bottle.adapter.ExchangeTimeLineAdapter; import com.outsourcing.bottle.db.LanguageConfigTable; import com.outsourcing.bottle.db.LoginUserInfoTable; import com.outsourcing.bottle.db.PushNoticeInfoTable; import com.outsourcing.bottle.domain.ExchangeTimelineInfo; import com.outsourcing.bottle.domain.ExsessionsEntry; import com.outsourcing.bottle.domain.LanguageConfig; import com.outsourcing.bottle.domain.LoginUserInfoEntry; import com.outsourcing.bottle.domain.PushNoticeInfo; import com.outsourcing.bottle.domain.UrlConfig; import com.outsourcing.bottle.remoteimage.RemoteImageView; import com.outsourcing.bottle.ui.ChooseFriendActivity; import com.outsourcing.bottle.ui.ExchangeInfoDetailActivity; import com.outsourcing.bottle.ui.ExchangePicDetailActivity; import com.outsourcing.bottle.ui.ExpandEditActivity; import com.outsourcing.bottle.ui.HomeActivity; import com.outsourcing.bottle.ui.SettingActivity; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.BasicUIEvent; import com.outsourcing.bottle.util.HttpUtils; import com.outsourcing.bottle.util.ServiceUtils; import com.outsourcing.bottle.util.TextUtil; import com.outsourcing.bottle.util.UICore; import com.outsourcing.bottle.widget.CustomListView; import com.outsourcing.bottle.widget.CustomPopupWindow; /** * * @author 06peng * */ public class ExchangeFragment extends Fragment implements BasicUIEvent, OnClickListener, Callback, OnScrollListener { private static final String TAG = ExchangeFragment.class.getSimpleName(); public static final int EXEU_GET_EXCHANGE_TIMELINE = 0; private static final int EXEU_REJECT_EX_SUCCESS = 3; private static final int EXEU_REJECT_EX_FAILED = 4; private static final int EXEU_ACCEPT_EX_SUCCESS = 5; private static final int EXEU_ACCEPT_EX_FAILED = 6; private static final int EXEU_VISIBLE_INFOEX_SUCCESS = 7; private static final int EXEU_VISIBLE_INFOEX_FAILED = 8; private static final int EXEU_INVISIBLE_INFOEX_SUCCESS = 9; private static final int EXEU_INVISIBLE_INFOEX_FAILED = 10; private static final int EXEU_REJECT_PICEX_SUCCESS = 11; private static final int EXEU_REJECT_PICEX_FAILED = 12; private static final int EXEU_VISIBLE_PICEX_SUCCESS = 13; private static final int EXEU_VISIBLE_PICEX_FAILED = 14; private static final int EXEU_INVISIBLE_PICEX_SUCCESS = 15; private static final int EXEU_INVISIBLE_PICEX_FAILED = 16; private static final int EXEU_LIKE_OP_PICEX_SUCCESS = 17; private static final int EXEU_LIKE_OP_PICEX_FAILED = 18; private static final int EXEU_GET_EXCHANGE_TIMELINE_MORE = 19; private static final int EXEU_GET_EXCHANGE_TIMELINE_MORE_NOTHING = 20; private static final int EXEU_GOTO_EXCHANGE = 21; private static final int INIT_HAS_EXS_ERROR = 22; private static final int EXEU_GOTO_PROFILE = 23; private static final int EXEU_GOTO_PHOTO = 24; private static final int INIT_HAS_EXS_PROFILE = 25; private static final int INIT_HAS_EXS_PHOTO = 26; private static final int EXEU_GET_SINGLE_EXSESSION = 27; private static final int EXEU_UNLIKE_OPERATION = 28; private static final int EXEU_LIKE_OPERATION = 29; private static final int EXEU_GET_DATA_FAILED = 30; private static final int EXEU_REFRESH_EXCHANGE_TIMELINE = 31; private static final int EXEU_GET_SINGLE_EXCHANGE_TIMELINE = 32; private static final int EXEU_REGET_TIMELINE = 33; private static final int EXEU_SET_BTPIC_PAINT = 34; private static final int EXEU_PUSH_NOTICE = 35; private int mode = 0; private int page = 1; private View mHeaderView = null; private FrameLayout mContentView = null; private Handler handler = null; private HomeActivity activity = null; private ExchangeTimeLineAdapter mExchangeAdapter; private CustomListView listView = null; private View loadMoreView = null; private List<ExsessionsEntry> exchangTimelineList = null; private ExchangeTimelineInfo exchangeTimelineInfo = null; private int visibleLastIndex = 0; // 最后的可视项索引 private int visibleItemCount; // 当前窗口可见项总数 public boolean init = false; private int ouid; private int exsType; public int exsid; private int picid; public int position; private View mLikeView; private CustomPopupWindow mLikePopview; ExsessionsEntry mExsessionsEntry; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); activity = (HomeActivity) getActivity(); handler = new Handler(this); ServiceUtils.dout(TAG + "onCreate"); // if (AppContext.getInstance().getCurrentItem() == 0) { // if (!init) { // ServiceUtils.dout(TAG + " get first data...."); // UICore.eventTask(this, activity, EXEU_GET_EXCHANGE_TIMELINE, getString(R.string.init_data), null); // } // } if (!init) { ServiceUtils.dout(TAG + " get first data...."); // new Thread() { // public void run() { // getExchangeTimeLine(mode); // }; // }.start(); UICore.eventTask(this, activity, EXEU_GET_EXCHANGE_TIMELINE, getString(R.string.init_data), null); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.root_layout, null); mContentView = (FrameLayout) view.findViewById(R.id.mainView); // mContentView.setonRefreshListener(new OnRefreshListener() { // // @Override // public void onRefresh() { // } // }); // mContentView.setonScrollChangeListener(new OnScrollChangeBottom() { // // @Override // public void onScrollBottom() { // } // }); if (!init) { listView = (CustomListView) LayoutInflater.from(activity).inflate(R.layout.main_refresh_list, null); // listView = (ListView)contentView.findViewById(R.id.list_view); // listView = (RefreshListView) view.findViewById(R.id.list_view); listView.setonRefreshListener(new CustomListView.OnRefreshListener() { @Override public void onRefresh() { page = 1; UICore.eventTask(ExchangeFragment.this, activity, EXEU_REFRESH_EXCHANGE_TIMELINE, null, null); } }); loadMoreView = inflater.inflate(R.layout.refreshable_list_footer, null); loadMoreView.setVisibility(View.GONE); mHeaderView = LayoutInflater.from(activity).inflate( R.layout.exchange_list_header, null); listView.addHeaderView(mHeaderView); listView.addFooterView(loadMoreView); listView.setOnScrollListener(this); } initLikePopupWindow(); return view; // // View view = inflater.inflate(R.layout.bottle_fragment, null); // // listView = (RefreshListView) view.findViewById(R.id.list_view); // listView.setOnRefreshListener(new RefreshListView.OnRefreshListener() { // // @Override // public void onRefresh() { //// refresh(); // } // }); // loadMoreView = inflater.inflate(R.layout.refreshable_list_footer, null); // loadMoreView.setVisibility(View.GONE); // mHeaderView = LayoutInflater.from(activity).inflate( // R.layout.exchange_list_header, null); // listView.addHeaderView(mHeaderView); // listView.addFooterView(loadMoreView); // listView.setOnScrollListener(this); // 添加滑动监听 // // initLikePopupWindow(); // return view; } public void doGetExTimeline_Refresh() { UICore.eventTask(this, activity, EXEU_REFRESH_EXCHANGE_TIMELINE, "EXEU_GET_EXCHANGE_TIMELINE", null); } @Override public void onResume() { super.onResume(); ServiceUtils.dout(TAG + "onResume"); // if (init) { // Message message = Message.obtain(handler); // message.what = EXEU_REGET_TIMELINE; // handler.sendMessage(message); // } if (AppContext.getInstance().isFromExchangeTime() == true) { AppContext.getInstance().setFromExchangeTime(false); doGetSingleExsession(position, exsid); } if (AppContext.getInstance().isFromExchangeTimeToChangeFriend()) { AppContext.getInstance().setFromExchangeTimeToChangeFriend( false); page = 1; UICore.eventTask(ExchangeFragment.this, activity, EXEU_REFRESH_EXCHANGE_TIMELINE, "EXEU_GET_EXCHANGE_TIMELINE", null); } } @Override public void onPause() { super.onStop(); // if (null != mContentView) { // mContentView.removeAllViews(); // } } @Override public boolean handleMessage(Message msg) { switch (msg.what) { case EXEU_GET_EXCHANGE_TIMELINE: setListHeader(); if (null != mContentView) { mContentView.removeAllViews(); } mContentView.addView(listView); // if (init) { // listView.setSelection(visibleLastIndex - visibleItemCount); // } init = true; new Thread() { public void run() { getPushNotice(); }; }.start(); break; case EXEU_REGET_TIMELINE: if (null != mContentView) { mContentView.removeAllViews(); } mContentView.addView(listView); listView.setSelection(visibleLastIndex - visibleItemCount+1); break; case EXEU_REFRESH_EXCHANGE_TIMELINE: ((HomeActivity) getActivity()).pushNoticeUpdateUI(); // mExchangeAdapter.notifyDataSetChanged(); setListHeader(); if (null != mContentView) { mContentView.removeAllViews(); } mContentView.addView(listView); listView.onRefreshComplete(); new Thread() { public void run() { getPushNotice(); }; }.start(); // listView.setSelection(1); break; case EXEU_PUSH_NOTICE: ((HomeActivity) getActivity()).pushNoticeUpdateUI(); break; case EXEU_GET_EXCHANGE_TIMELINE_MORE: mExchangeAdapter.notifyDataSetChanged(); // listView.setSelection(visibleLastIndex - visibleItemCount + 1); // // 设置选中项 break; case EXEU_GET_SINGLE_EXCHANGE_TIMELINE: mExchangeAdapter.notifyDataSetChanged(); break; case EXEU_REJECT_EX_SUCCESS: doGetSingleExsession(position, exsid); // page = 1; // UICore.eventTask(this, activity, EXEU_GET_EXCHANGE_TIMELINE, // getString(R.string.init_data), null); activity.onToast((String) msg.obj); break; case EXEU_REJECT_EX_FAILED: activity.onToast((String) msg.obj); break; case EXEU_ACCEPT_EX_SUCCESS: doGetSingleExsession(position, exsid); // page = 1; // UICore.eventTask(this, activity, EXEU_GET_EXCHANGE_TIMELINE, // getString(R.string.init_data), null); activity.onToast((String) msg.obj); break; case EXEU_SET_BTPIC_PAINT: doGetSingleExsession(position, exsid); activity.onToast((String) msg.obj); break; case EXEU_ACCEPT_EX_FAILED: activity.onToast((String) msg.obj); break; case EXEU_VISIBLE_INFOEX_SUCCESS: doGetSingleExsession(position, exsid); // page = 1; // UICore.eventTask(this, activity, EXEU_GET_EXCHANGE_TIMELINE, // getString(R.string.init_data), null); activity.onToast((String) msg.obj); break; case EXEU_VISIBLE_INFOEX_FAILED: activity.onToast((String) msg.obj); break; case EXEU_INVISIBLE_INFOEX_FAILED: activity.onToast((String) msg.obj); break; case EXEU_INVISIBLE_INFOEX_SUCCESS: doGetSingleExsession(position, exsid); // page = 1; // UICore.eventTask(this, activity, EXEU_GET_EXCHANGE_TIMELINE, // getString(R.string.init_data), null); activity.onToast((String) msg.obj); break; case EXEU_REJECT_PICEX_SUCCESS: doGetSingleExsession(position, exsid); // page = 1; // UICore.eventTask(this, activity, EXEU_GET_EXCHANGE_TIMELINE, // getString(R.string.init_data), null); activity.onToast((String) msg.obj); break; case EXEU_REJECT_PICEX_FAILED: activity.onToast((String) msg.obj); break; case EXEU_VISIBLE_PICEX_SUCCESS: doGetSingleExsession(position, exsid); // page = 1; // UICore.eventTask(this, activity, EXEU_GET_EXCHANGE_TIMELINE, // getString(R.string.init_data), null); activity.onToast((String) msg.obj); break; case EXEU_VISIBLE_PICEX_FAILED: activity.onToast((String) msg.obj); break; case EXEU_INVISIBLE_PICEX_SUCCESS: doGetSingleExsession(position, exsid); // page = 1; // UICore.eventTask(this, activity, EXEU_GET_EXCHANGE_TIMELINE, // getString(R.string.init_data), null); activity.onToast((String) msg.obj); break; case EXEU_INVISIBLE_PICEX_FAILED: activity.onToast((String) msg.obj); break; case EXEU_LIKE_OP_PICEX_SUCCESS: doGetSingleExsession(position, exsid); activity.onToast((String) msg.obj); break; case EXEU_LIKE_OP_PICEX_FAILED: activity.onToast((String) msg.obj); break; case INIT_HAS_EXS_ERROR: activity.onToast((String) msg.obj); break; case EXEU_GET_EXCHANGE_TIMELINE_MORE_NOTHING: activity.onToast(TextUtil.R("no_more_data")); loadMoreView.setVisibility(View.GONE); // listView.setSelection(visibleLastIndex - visibleItemCount); break; case EXEU_GOTO_PROFILE: Intent intentExchangePro = new Intent(activity, ExchangeInfoDetailActivity.class); intentExchangePro.putExtra("ouid", ouid); intentExchangePro.putExtra("page", 1); activity.startActivity(intentExchangePro); break; case EXEU_GOTO_PHOTO: Intent intentExchangePic = new Intent(activity, ExchangePicDetailActivity.class); intentExchangePic.putExtra("ouid", ouid); intentExchangePic.putExtra("page", 1); activity.startActivity(intentExchangePic); break; case INIT_HAS_EXS_PROFILE: Intent intentProfile = new Intent(activity, ExpandEditActivity.class); Bundle bundleProfile = new Bundle(); bundleProfile.putString("from_type", AppContext.REPLY_INFOEX); bundleProfile.putString("reply_infoex_type", "apply"); bundleProfile.putInt("ouid", ouid); intentProfile.putExtras(bundleProfile); startActivity(intentProfile); break; case INIT_HAS_EXS_PHOTO: Intent intentPhoto = new Intent(activity, ExpandEditActivity.class); Bundle bundlePhoto = new Bundle(); bundlePhoto.putString("from_type", AppContext.APPLY_PICEX); bundlePhoto.putInt("ouid", ouid); intentPhoto.putExtras(bundlePhoto); startActivity(intentPhoto); break; case EXEU_GET_DATA_FAILED: activity.onToast((String) msg.obj); break; default: break; } return false; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.iv_profile_info: activity.onToast("profile"); Intent settingIntent = new Intent(activity, SettingActivity.class); startActivity(settingIntent); break; case R.id.iv_exphoto: activity.onToast("exphoto"); break; case R.id.iv_exprofile: activity.onToast("exprofile"); break; case R.id.iv_unlike:// 不喜欢 mLikePopview.dismiss(); UICore.eventTask(this, activity, EXEU_UNLIKE_OPERATION, "", null); break; case R.id.iv_like:// 喜欢 mLikePopview.dismiss(); UICore.eventTask(this, activity, EXEU_LIKE_OPERATION, "", null); break; default: break; } } private void setListHeader() { LanguageConfigTable languageConfigTable = new LanguageConfigTable(); LanguageConfig languageCon = languageConfigTable.getBottleLanguageConfig(); RelativeLayout mProfileInfo = (RelativeLayout) mHeaderView .findViewById(R.id.rl_tlime_profile_bottle); View line_profile = (View)mHeaderView.findViewById(R.id.line_tlime_profile_bottle); RelativeLayout mExProfile = (RelativeLayout) mHeaderView .findViewById(R.id.rl_tlime_exchange_profile); View line_exchange_profile = (View)mHeaderView.findViewById(R.id.line_exchange_profile); mExProfile.setVisibility(View.GONE); RelativeLayout mExPhoto = (RelativeLayout) mHeaderView .findViewById(R.id.rl_exchange_photo); mExPhoto.setVisibility(View.GONE); View line_exchange_photo = (View)mHeaderView.findViewById(R.id.line_exchange_photo); LoginUserInfoTable loginUserInfoTable = new LoginUserInfoTable(); final LoginUserInfoEntry loginUserInfoEntry = loginUserInfoTable .getLoginUserInfo(AppContext.getInstance().getLogin_uid()); if (null != loginUserInfoEntry && loginUserInfoEntry.getBasicinfo_fullfill() == 0) { mProfileInfo.setVisibility(View.VISIBLE); line_profile.setVisibility(View.VISIBLE); RemoteImageView img_head = (RemoteImageView) mHeaderView .findViewById(R.id.iv_author_photo_3); img_head.setOnClickListener(this); LoginUserInfoTable userInfoTable = new LoginUserInfoTable(); if (null != userInfoTable.getLoginUserInfo(AppContext .getInstance().getLogin_uid())) { String avatar = userInfoTable.getLoginUserInfo( AppContext.getInstance().getLogin_uid()) .getAvatar(); if (!TextUtils.isEmpty(avatar)) { img_head.setDefaultImage(R.drawable.avatar_default_small); img_head.setImageUrl(avatar); } } ImageView img_Profile = (ImageView) mHeaderView .findViewById(R.id.iv_profile_info); img_Profile.setOnClickListener(this); TextView tvProfileTips = (TextView) mHeaderView .findViewById(R.id.tv_bottle_profile_tips_2); tvProfileTips.setText(loginUserInfoEntry.getBasicinfo_tip()); Button bt_profile = (Button) mHeaderView .findViewById(R.id.bt_profile_info_try); bt_profile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent settingIntent = new Intent(activity, SettingActivity.class); startActivity(settingIntent); } }); } else { mProfileInfo.setVisibility(View.GONE); line_profile.setVisibility(View.GONE); } if (exchangeTimelineInfo.getShowtips().getShow_infoex_tips() == 1) { mExProfile.setVisibility(View.VISIBLE); line_exchange_profile.setVisibility(View.VISIBLE); ImageView iv_exprofile = (ImageView) mHeaderView .findViewById(R.id.iv_exprofile); iv_exprofile.setOnClickListener(this); RemoteImageView img_head = (RemoteImageView) mHeaderView .findViewById(R.id.iv_author_photo_1); img_head.setOnClickListener(this); if (null != loginUserInfoTable.getLoginUserInfo(AppContext .getInstance().getLogin_uid())) { String avatar = loginUserInfoTable.getLoginUserInfo( AppContext.getInstance().getLogin_uid()) .getAvatar(); if (!TextUtils.isEmpty(avatar)) { img_head.setDefaultImage(R.drawable.avatar_default_small); img_head.setImageUrl(avatar); } } String infoTips1 = null; String infoTips2 = null; if (AppContext.language == 1) { infoTips1 = languageCon.getExchange_profile_tip_cn(); infoTips2 = languageCon.getExchange_profile_tip_2_cn(); }else { infoTips1 = languageCon.getExchange_profile_tip_en(); infoTips2 = languageCon.getExchange_profile_tip_2_en(); } TextView tvInfoTips = (TextView) mHeaderView .findViewById(R.id.tv_exchange_info_tips); tvInfoTips.setText(infoTips1); TextView tvInfoTip2 = (TextView) mHeaderView .findViewById(R.id.tv_exchange_info_tips_2); tvInfoTip2.setText(infoTips2); Button btExProfile = (Button) mHeaderView .findViewById(R.id.bt_exchange_profile_try); btExProfile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (null != loginUserInfoEntry && loginUserInfoEntry.getBasicinfo_fullfill() == 0) { String basicinfo_tip = loginUserInfoEntry.getBasicinfo_tip(); AlertDialog.Builder alertDialog = new AlertDialog.Builder(activity); alertDialog.setMessage(basicinfo_tip); alertDialog.setPositiveButton(TextUtil.R("confirm_ok"), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(activity, SettingActivity.class); startActivity(intent); } }); alertDialog.setNegativeButton(TextUtil.R("confirm_cancel"), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); alertDialog.create().show(); } else { Intent intent = new Intent(activity, ChooseFriendActivity.class); intent.putExtra("choose_friend_type", AppContext.CHOOSE_FRIEND_EXCHANGE_INFO_TYPE); startActivity(intent); } } }); } else { mExProfile.setVisibility(View.GONE); line_exchange_profile.setVisibility(View.GONE); } if (exchangeTimelineInfo.getShowtips().getShow_picex_tips() == 1) { mExPhoto.setVisibility(View.VISIBLE); line_exchange_photo.setVisibility(View.VISIBLE); RemoteImageView img_head = (RemoteImageView) mHeaderView .findViewById(R.id.iv_author_photo_2); img_head.setOnClickListener(this); if (null != loginUserInfoTable.getLoginUserInfo(AppContext .getInstance().getLogin_uid())) { String avatar = loginUserInfoTable.getLoginUserInfo( AppContext.getInstance().getLogin_uid()) .getAvatar(); if (!TextUtils.isEmpty(avatar)) { img_head.setDefaultImage(R.drawable.avatar_default_small); img_head.setImageUrl(avatar); } } String photoTips1 = null; String photoTips2 = null; if (AppContext.language == 1) { photoTips1 = languageCon.getExchange_photo_tip_cn(); photoTips2 = languageCon.getExchange_photo_tip_2_cn(); }else { photoTips1 = languageCon.getExchange_photo_tip_en(); photoTips2 = languageCon.getExchange_photo_tip_2_en(); } TextView tvPhotoTips = (TextView) mHeaderView .findViewById(R.id.tv_exchange_photo_tips); tvPhotoTips.setText(photoTips1); TextView tvPhotoTip2 = (TextView) mHeaderView .findViewById(R.id.tv_exchange_photo_tips_2); tvPhotoTip2.setText(photoTips2); ImageView iv_exphoto = (ImageView) mHeaderView .findViewById(R.id.iv_exphoto); iv_exphoto.setOnClickListener(this); Button btExPhoto = (Button) mHeaderView .findViewById(R.id.bt_exchange_photo_try); btExPhoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(activity, ChooseFriendActivity.class); intent.putExtra("choose_friend_type", AppContext.CHOOSE_FRIEND_EXCHANGE_PHOTO_TYPE); startActivity(intent); } }); } else { mExPhoto.setVisibility(View.GONE); line_exchange_photo.setVisibility(View.GONE); } if (null != exchangTimelineList) { mExchangeAdapter = new ExchangeTimeLineAdapter(activity, this, exchangTimelineList); listView.setAdapter(mExchangeAdapter); // Utility.setListViewHeightBasedOnChildren(listView); } if (mProfileInfo.getVisibility() == View.VISIBLE && mExProfile.getVisibility() == View.VISIBLE && mExPhoto.getVisibility() == View.VISIBLE ) { line_exchange_photo.setVisibility(View.GONE); }else if (mProfileInfo.getVisibility() == View.VISIBLE && mExProfile.getVisibility() == View.VISIBLE && mExPhoto.getVisibility() == View.GONE) { line_exchange_profile.setVisibility(View.GONE); } else if (mProfileInfo.getVisibility() == View.VISIBLE && mExProfile.getVisibility() == View.GONE && mExPhoto.getVisibility() == View.GONE) { line_profile.setVisibility(View.GONE); } else if (mProfileInfo.getVisibility() == View.GONE && mExProfile.getVisibility() == View.VISIBLE && mExPhoto.getVisibility() == View.VISIBLE) { line_exchange_photo.setVisibility(View.GONE); } else if (mProfileInfo.getVisibility() == View.GONE && mExProfile.getVisibility() == View.VISIBLE && mExPhoto.getVisibility() == View.GONE) { line_exchange_profile.setVisibility(View.GONE); } else if (mProfileInfo.getVisibility() == View.GONE && mExProfile.getVisibility() == View.GONE && mExPhoto.getVisibility() == View.VISIBLE) { line_exchange_photo.setVisibility(View.GONE); } } @Override public void execute(int mes, Object obj) { switch (mes) { case EXEU_GET_EXCHANGE_TIMELINE: getExchangeTimeLine(mode); break; case EXEU_REFRESH_EXCHANGE_TIMELINE: refreshExchangeTimeLine(mode); break; case EXEU_GET_EXCHANGE_TIMELINE_MORE: getExchangeTimeLineMore(mode, page); break; case EXEU_GOTO_EXCHANGE: getHasExs(exsType, ouid); break; case EXEU_REJECT_EX_SUCCESS: rejectInfoex(ouid); break; case EXEU_ACCEPT_EX_SUCCESS: acceptInfoex(ouid); break; case EXEU_VISIBLE_INFOEX_SUCCESS: visibleInfoex(ouid); break; case EXEU_INVISIBLE_INFOEX_SUCCESS: invisibleInfoex(ouid); break; case EXEU_REJECT_PICEX_SUCCESS: rejectPicex(ouid); break; case EXEU_VISIBLE_PICEX_SUCCESS: visiblePicex(ouid); break; case EXEU_INVISIBLE_PICEX_SUCCESS: invisiblePicex(ouid); break; case EXEU_GET_SINGLE_EXSESSION: getSingleExchange(exsid, position); break; case EXEU_LIKE_OPERATION: likeIOperationPicex(ouid, picid, 0); break; case EXEU_UNLIKE_OPERATION: likeIOperationPicex(ouid, picid, 1); break; case EXEU_SET_BTPIC_PAINT: int optype = (Integer)obj; setExpicPaint(ouid, picid, optype); break; default: break; } } private void getExchangeTimeLine(int mode) { if (AppContext.getInstance().getLogin_uid() == 0 || AppContext.getInstance().getLogin_token() == null) { initConfig(); } StringBuffer url = new StringBuffer(UrlConfig.get_ex_timeline); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&mode=" + mode); url.append("&count=10"); url.append("&page=1"); url.append("&picfeedscount=5"); url.append("&feedscount=5"); ServiceUtils.dout("getExchangeTimeline url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); if (results == null) { return; } ServiceUtils.dout("getExchangeTimeline results: " + results); Gson gson = new Gson(); exchangeTimelineInfo = gson.fromJson(results, ExchangeTimelineInfo.class); if (exchangeTimelineInfo.getResults().getAuthok() == 1) { exchangTimelineList = exchangeTimelineInfo.getExsessions_list(); Message message = Message.obtain(handler); message.what = EXEU_GET_EXCHANGE_TIMELINE; handler.sendMessage(message); } else { Message message = handler.obtainMessage(EXEU_GET_DATA_FAILED, exchangeTimelineInfo.getResults().getErrmsg()); handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } private void refreshExchangeTimeLine(int mode) { StringBuffer url = new StringBuffer(UrlConfig.get_ex_timeline); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&mode=" + mode); url.append("&count=10"); url.append("&page=1"); url.append("&picfeedscount=5"); url.append("&feedscount=5"); ServiceUtils.dout("refreshExchangeTimeline url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); if (results == null) { return; } ServiceUtils.dout("getExchangeTimeline results: " + results); Gson gson = new Gson(); exchangeTimelineInfo = gson.fromJson(results, ExchangeTimelineInfo.class); if (exchangeTimelineInfo.getResults().getAuthok() == 1) { exchangTimelineList = exchangeTimelineInfo.getExsessions_list(); handler.sendEmptyMessage(EXEU_REFRESH_EXCHANGE_TIMELINE); } else { Message message = handler.obtainMessage(EXEU_GET_DATA_FAILED, exchangeTimelineInfo.getResults().getErrmsg()); handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } private void getPushNotice() { StringBuffer url = new StringBuffer(UrlConfig.push_notice); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); try { String result = HttpUtils.doGet(url.toString()); if (result != null) { JSONObject obj = new JSONObject(result); JSONObject resultObj = obj.getJSONObject("results"); if (resultObj.getInt("authok") == 1) { JSONObject pushObj = obj.getJSONObject("push_notice"); PushNoticeInfoTable table = new PushNoticeInfoTable(); PushNoticeInfo pushInfo = new PushNoticeInfo(); table.clearTable(); pushInfo.setMessage_avatar(pushObj.getString("message_avatar")); pushInfo.setMessage_content(pushObj.getString("message_content")); pushInfo.setNew_btfeed_count(pushObj.getInt("new_btfeed_count")); pushInfo.setNew_exfeed_count(pushObj.getInt("new_exfeed_count")); pushInfo.setNew_message_count(pushObj.getInt("new_message_count")); pushInfo.setNew_notice_count(pushObj.getInt("new_notice_count")); pushInfo.setNew_maybeknow_count(pushObj.getInt("new_maybeknow_count")); table.savePushNoticeInfo(pushInfo, AppContext.getInstance().getLogin_uid()); Message message = Message.obtain(handler); message.what = EXEU_PUSH_NOTICE; handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); } } private void getExchangeTimeLineMore(int mode, int page) { StringBuffer url = new StringBuffer(UrlConfig.get_ex_timeline); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&mode=" + mode); url.append("&count=10"); url.append("&page=" + page); url.append("&picfeedscount=5"); url.append("&feedscount=5"); ServiceUtils.dout("getExchangeTimelineMore url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); if (results == null) { return; } ServiceUtils.dout("getExchangeTimelineMore results: " + results); Gson gson = new Gson(); exchangeTimelineInfo = gson.fromJson(results, ExchangeTimelineInfo.class); if (exchangeTimelineInfo.getResults().getAuthok() == 1) { // exchangTimelineList = // exchangeTimelineInfo.getExsessions_list(); if (null != exchangeTimelineInfo.getExsessions_list() && exchangeTimelineInfo.getExsessions_list().size() > 0) { exchangTimelineList.addAll(exchangeTimelineInfo .getExsessions_list()); Message message = Message.obtain(handler); message.what = EXEU_GET_EXCHANGE_TIMELINE_MORE; handler.sendMessage(message); } else { Message message = Message.obtain(handler); message.what = EXEU_GET_EXCHANGE_TIMELINE_MORE_NOTHING; handler.sendMessage(message); } } else { Message message = handler.obtainMessage(EXEU_GET_DATA_FAILED, exchangeTimelineInfo.getResults().getErrmsg()); handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); Message message = Message.obtain(handler); message.what = EXEU_GET_EXCHANGE_TIMELINE_MORE_NOTHING; handler.sendMessage(message); } } public void doGetSingleExsession(int position, int exsid) { this.exsid = exsid; this.position = position; UICore.eventTask(ExchangeFragment.this, activity, EXEU_GET_SINGLE_EXSESSION, getString(R.string.init_data), null); } private void getSingleExchange(int exsid, int position) { StringBuffer url = new StringBuffer(UrlConfig.get_ex_timeline); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&mode=4&exsid=" + exsid); url.append("&picfeedscount=5"); url.append("&feedscount=5"); ServiceUtils.dout("getSingleExchange url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); if (results == null) { return; } ServiceUtils.dout("getSingleExchange results: " + results); Gson gson = new Gson(); ExchangeTimelineInfo exchangeTimelineInfo = gson.fromJson(results, ExchangeTimelineInfo.class); if (exchangeTimelineInfo.getResults().getAuthok() == 1) { List<ExsessionsEntry> mSingleExList = exchangeTimelineInfo .getExsessions_list(); if (null != mSingleExList && mSingleExList.size() > 0) { mExsessionsEntry = mSingleExList.get(0); exchangTimelineList.set(position, mExsessionsEntry); Message message = Message.obtain(handler); message.what = EXEU_GET_SINGLE_EXCHANGE_TIMELINE; handler.sendMessage(message); } } else { Message message = handler.obtainMessage(EXEU_GET_DATA_FAILED, exchangeTimelineInfo.getResults().getErrmsg()); handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } public void doRejectInfoex(int ouid, int position, int exsid) { this.ouid = ouid; this.position = position; this.exsid = exsid; UICore.eventTask(this, activity, EXEU_REJECT_EX_SUCCESS, "", null); } private void rejectInfoex(int ouid) { StringBuffer url = new StringBuffer(UrlConfig.reject_infoex); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); ServiceUtils.dout("rejectInfoex url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); ServiceUtils.dout("rejectInfoex result:" + results); if (null != results) { JSONObject obj = new JSONObject(results); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); String errmsg = resultObj.getString("errmsg"); String successmsg = resultObj.getString("successmsg"); if (success == 1) { Message message = handler.obtainMessage( EXEU_REJECT_EX_SUCCESS, successmsg); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_REJECT_EX_FAILED, errmsg); handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); } } public void doAcceptInfoex(int ouid, int position, int exsid) { this.ouid = ouid; this.position = position; this.exsid = exsid; LoginUserInfoTable loginUserInfoTable = new LoginUserInfoTable(); LoginUserInfoEntry loginUserInfoEntry = loginUserInfoTable .getLoginUserInfo(AppContext.getInstance().getLogin_uid()); if (null != loginUserInfoEntry && loginUserInfoEntry.getBasicinfo_fullfill() == 0) { String basicinfo_tip = loginUserInfoEntry.getBasicinfo_tip(); AlertDialog.Builder alertDialog = new AlertDialog.Builder(activity); alertDialog.setMessage(basicinfo_tip); alertDialog.setPositiveButton(TextUtil.R("confirm_ok"), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(activity, SettingActivity.class); startActivity(intent); } }); alertDialog.setNegativeButton(TextUtil.R("confirm_cancel"), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); alertDialog.create().show(); } else { UICore.eventTask(this, activity, EXEU_ACCEPT_EX_SUCCESS, "", null); } } private void acceptInfoex(int ouid) { StringBuffer url = new StringBuffer(UrlConfig.accept_infoex); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); ServiceUtils.dout("acceptInfoex url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); ServiceUtils.dout("acceptInfoex result:" + results); if (null != results) { JSONObject obj = new JSONObject(results); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); String errmsg = resultObj.getString("errmsg"); String successmsg = resultObj.getString("successmsg"); if (success == 1) { Message message = handler.obtainMessage( EXEU_ACCEPT_EX_SUCCESS, successmsg); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_ACCEPT_EX_FAILED, errmsg); handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); } } public void doVisibleInfoex(int ouid, int position, int exsid) { this.ouid = ouid; this.position = position; this.exsid = exsid; UICore.eventTask(this, activity, EXEU_VISIBLE_INFOEX_SUCCESS, "", null); } private void visibleInfoex(int ouid) { StringBuffer url = new StringBuffer(UrlConfig.visible_infoex); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); ServiceUtils.dout("visibleInfoex url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); ServiceUtils.dout("visibleInfoex result:" + results); if (null != results) { JSONObject obj = new JSONObject(results); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); String errmsg = resultObj.getString("errmsg"); String successmsg = resultObj.getString("successmsg"); if (success == 1) { Message message = handler.obtainMessage( EXEU_VISIBLE_INFOEX_SUCCESS, successmsg); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_VISIBLE_INFOEX_FAILED, errmsg); handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); } } public void doInvisibleInfoex(int ouid, int position, int exsid) { this.ouid = ouid; this.position = position; this.exsid = exsid; UICore.eventTask(this, activity, EXEU_INVISIBLE_INFOEX_SUCCESS, "", null); } private void invisibleInfoex(int ouid) { StringBuffer url = new StringBuffer(UrlConfig.invisible_infoex); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); ServiceUtils.dout("invisibleInfoex url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); ServiceUtils.dout("invisibleInfoex result:" + results); if (null != results) { JSONObject obj = new JSONObject(results); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); String errmsg = resultObj.getString("errmsg"); String successmsg = resultObj.getString("successmsg"); if (success == 1) { Message message = handler.obtainMessage( EXEU_INVISIBLE_INFOEX_SUCCESS, successmsg); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_INVISIBLE_INFOEX_FAILED, errmsg); handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); } } public void doRejectPicex(int ouid, int position, int exsid) { this.ouid = ouid; this.position = position; this.exsid = exsid; UICore.eventTask(this, activity, EXEU_REJECT_PICEX_SUCCESS, "", null); } private void rejectPicex(int ouid) { StringBuffer url = new StringBuffer(UrlConfig.reject_picex); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); ServiceUtils.dout("rejectPicex url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); ServiceUtils.dout("rejectPicex result:" + results); if (null != results) { JSONObject obj = new JSONObject(results); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); String errmsg = resultObj.getString("errmsg"); String successmsg = resultObj.getString("successmsg"); if (success == 1) { Message message = handler.obtainMessage( EXEU_REJECT_PICEX_SUCCESS, successmsg); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_REJECT_PICEX_FAILED, errmsg); handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); } } public void doVisiblePicex(int ouid, int position, int exsid) { this.ouid = ouid; this.position = position; this.exsid = exsid; UICore.eventTask(this, activity, EXEU_VISIBLE_PICEX_SUCCESS, "", null); } private void visiblePicex(int ouid) { StringBuffer url = new StringBuffer(UrlConfig.visible_picex); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); ServiceUtils.dout("visiblePicex url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); ServiceUtils.dout("visiblePicex result:" + results); if (null != results) { JSONObject obj = new JSONObject(results); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); String errmsg = resultObj.getString("errmsg"); String successmsg = resultObj.getString("successmsg"); if (success == 1) { Message message = handler.obtainMessage( EXEU_VISIBLE_PICEX_SUCCESS, successmsg); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_VISIBLE_PICEX_FAILED, errmsg); handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); } } public void doInvisiblePicex(int ouid, int position, int exsid) { this.ouid = ouid; this.position = position; this.exsid = exsid; UICore.eventTask(this, activity, EXEU_INVISIBLE_PICEX_SUCCESS, "", null); } private void invisiblePicex(int ouid) { StringBuffer url = new StringBuffer(UrlConfig.invisible_picex); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); ServiceUtils.dout("invisiblePicex url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); ServiceUtils.dout("invisiblePicex result:" + results); if (null != results) { JSONObject obj = new JSONObject(results); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); String errmsg = resultObj.getString("errmsg"); String successmsg = resultObj.getString("successmsg"); if (success == 1) { Message message = handler.obtainMessage( EXEU_INVISIBLE_PICEX_SUCCESS, successmsg); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_INVISIBLE_PICEX_FAILED, errmsg); handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); } } public void doExchange(int exsType, int ouid) { this.ouid = ouid; this.exsType = exsType; UICore.eventTask(this, activity, EXEU_GOTO_EXCHANGE, "has_exs", null); } private void getHasExs(int exsType, int ouid) { StringBuffer url = new StringBuffer(UrlConfig.get_has_exs); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); try { String result = HttpUtils.doGet(url.toString()); if (result != null) { JSONObject object = new JSONObject(result); JSONObject resultObj = object.getJSONObject("results"); int authok = resultObj.getInt("authok"); if (authok == 0) { String errmsg = resultObj.getString("errmsg"); Message msg = Message.obtain(handler, INIT_HAS_EXS_ERROR, errmsg); handler.sendMessage(msg); } else { JSONObject hasExsObj = object.getJSONObject("has_exs"); if (exsType == AppContext.CHOOSE_FRIEND_EXCHANGE_INFO_TYPE) { int has_infoexs = hasExsObj.getInt("has_infoexs"); if (has_infoexs == 1) { handler.sendEmptyMessage(EXEU_GOTO_PROFILE); } else { handler.sendEmptyMessage(INIT_HAS_EXS_PROFILE); } } else if (exsType == AppContext.CHOOSE_FRIEND_EXCHANGE_PHOTO_TYPE) { int has_picexs = hasExsObj.getInt("has_picexs"); if (has_picexs == 1) { handler.sendEmptyMessage(EXEU_GOTO_PHOTO); } else { handler.sendEmptyMessage(INIT_HAS_EXS_PHOTO); } } } } } catch (Exception e) { e.printStackTrace(); } } private void likeIOperationPicex(int ouid, int picid, int liketype) { StringBuffer url = new StringBuffer(UrlConfig.likeop_picex); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); url.append("&picid=" + picid); url.append("&liketype=" + liketype); ServiceUtils.dout("likeIOperationPicex url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); ServiceUtils.dout("likeIOperationPicex result:" + results); if (null != results) { JSONObject obj = new JSONObject(results); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); String errmsg = resultObj.getString("errmsg"); String successmsg = resultObj.getString("successmsg"); if (success == 1) { Message message = handler.obtainMessage( EXEU_LIKE_OP_PICEX_SUCCESS, successmsg); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_LIKE_OP_PICEX_FAILED, errmsg); handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); } } /** 喜欢pop */ private void initLikePopupWindow() { LayoutInflater mLayoutInflater = LayoutInflater.from(activity); mLikeView = mLayoutInflater.inflate(R.layout.pop_bottle_like, null); ImageView iv_unlike = (ImageView) mLikeView .findViewById(R.id.iv_unlike); ImageView iv_like = (ImageView) mLikeView.findViewById(R.id.iv_like); iv_unlike.setOnClickListener(this); iv_like.setOnClickListener(this); mLikePopview = new CustomPopupWindow(mLikeView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); mLikePopview.setBackgroundDrawable(getResources().getDrawable( R.drawable.like_frame_right)); mLikePopview.setOutsideTouchable(true); mLikePopview.update(); mLikePopview.setTouchable(true); mLikePopview.setFocusable(true); } public void showInfoPopupWindow(View achorView, int picid, int ouid, int exsid,int position) { this.ouid = ouid; this.picid = picid; this.exsid = exsid; this.position = position; if (mLikePopview.isShowing()) { mLikePopview.dismiss(); } else { // mLikePopview.showAtLocation(achorView, Gravity.RIGHT, 0, 0); mLikePopview.showAsDropDown(achorView, -150, -70); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); } public void doMenuItemSelect(int mode) { this.mode = mode; this.page = 1; UICore.eventTask(this, activity, EXEU_GET_EXCHANGE_TIMELINE, "", null); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { listView.setFirstVisiableItem(firstVisibleItem); this.visibleItemCount = visibleItemCount; visibleLastIndex = firstVisibleItem + visibleItemCount; } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { try { if (mExchangeAdapter != null) { int itemsLastIndex = mExchangeAdapter.getCount() + 2; // 数据集最后一项的索引 int lastIndex = itemsLastIndex+1; // 加上底部的loadMoreView项 和 head项 ServiceUtils.dout(TAG + " visibleLastIndex:" + visibleLastIndex); ServiceUtils.dout(TAG + " lastIndex:" + lastIndex); if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == lastIndex) { // 如果是自动加载,可以在这里放置异步加载数据的代码 page++; loadMoreView.setVisibility(View.VISIBLE); UICore.eventTask(this, activity, EXEU_GET_EXCHANGE_TIMELINE_MORE, null, null); Log.i("LOADMORE", "loading..."); } } } catch (Exception e) { e.printStackTrace(); } } public void initConfig() { String country = getResources().getConfiguration().locale.getCountry(); if (country.equals("CN")) { AppContext.setLanguage(1); } else { AppContext.setLanguage(0); } SharedPreferences preferences = getActivity().getSharedPreferences("Preferences_userinfo", Activity.MODE_APPEND); int login_uid = preferences.getInt("login_uid", 0); String login_token = preferences.getString("login_token", null); AppContext.getInstance().setLogin_uid(login_uid); AppContext.getInstance().setLogin_token(login_token); } public void doExpicPaint(int ouid, int picid,int optype,int exsid,int position){ this.ouid = ouid; this.picid = picid; this.exsid = exsid; this.position = position; UICore.eventTask(this, activity, EXEU_SET_BTPIC_PAINT, "", optype); } /** * * @param ouid * @param picid * @param optype 设置是否允许涂鸦。选择项:不允许(0)、允许(1) */ private void setExpicPaint(int ouid, int picid,int optype) { StringBuffer url = new StringBuffer(UrlConfig.set_expic_paint); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); url.append("&picid=" + picid); url.append("&optype=" + optype); try { String result = HttpUtils.doGet(url.toString()); if (result != null) { JSONObject object = new JSONObject(result); JSONObject resultObj = object.getJSONObject("results"); int authok = resultObj.getInt("success"); if (authok == 0) { String errmsg = resultObj.getString("errmsg"); Message msg = Message.obtain(handler, EXEU_GET_DATA_FAILED, errmsg); handler.sendMessage(msg); } else { String successmsg = resultObj.getString("successmsg"); Message msg = Message.obtain(handler, EXEU_SET_BTPIC_PAINT, successmsg); handler.sendMessage(msg); } } } catch (Exception e) { e.printStackTrace(); } } }
Java
package com.outsourcing.bottle.ui; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.json.JSONObject; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.Handler.Callback; import android.os.Message; import android.text.Html; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ext.SatelliteMenu; import android.view.ext.SatelliteMenu.SateliteClickedListener; import android.view.ext.SatelliteMenuItem; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.RelativeLayout; import android.widget.TextView; import com.google.gson.Gson; import com.outsourcing.bottle.BasicActivity; import com.outsourcing.bottle.R; import com.outsourcing.bottle.db.LoginUserInfoTable; import com.outsourcing.bottle.db.PushNoticeInfoTable; import com.outsourcing.bottle.domain.LoginUserInfoEntry; import com.outsourcing.bottle.domain.NoticeEntry; import com.outsourcing.bottle.domain.NoticeInfo; import com.outsourcing.bottle.domain.PushNoticeInfo; import com.outsourcing.bottle.domain.UrlConfig; import com.outsourcing.bottle.remoteimage.RemoteImageView; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.BasicUIEvent; import com.outsourcing.bottle.util.HttpUtils; import com.outsourcing.bottle.util.ImageLoader; import com.outsourcing.bottle.util.TextUtil; import com.outsourcing.bottle.util.UICore; import com.outsourcing.bottle.widget.CustomListView; /** * * @author 06peng * */ public class NoticeListActivity extends BasicActivity implements BasicUIEvent, Callback, OnClickListener { private ImageView backView; private ImageView moreView; // private ImageView noticeView; // private LinearLayout messageCountLayout; // private TextView countView; private CustomListView listView; private int visibleLastIndex = 0; // 最后的可视项索引 public int visibleItemCount; // 当前窗口可见项总数 private View loadMoreView; private LinearLayout bottomLayout; private ImageView avatarView; private TextView contentView; private TextView btnCount; // private ImageView messageView; private int newNoticeCount; private int newMessageCount; private int newBottleFeedCount; private int newExchangeFeedCount; private int newMaybeKownCount; private String message_content; private String message_avatar; private final int init_notice_info = 1; private final int error = 2; private final int user_baseinfo_notfull = 3; private final int complete_info = 4; private final int accept_friend = 5; private final int reject_friend = 6; private final int more = 7; private int page = 1; private final int menu_uploadphoto = 105; private final int menu_exprofile = 14; private final int menu_exphoto = 13; private final int menu_gainbt = 12; private final int menu_sendbt = 11; private Handler handler; private List<NoticeEntry> noticeList; private ImageLoader userImageLoader; private ImageLoader photoImageLoader; private NoticeAdapter adapter; private PushBroadcastReceiver receiver; private PushNoticeInfo pushInfo; @Override protected void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); setContentView(R.layout.notice_list); handler = new Handler(this); userImageLoader = new ImageLoader(this, AppContext.UserAvatarIcon); photoImageLoader = new ImageLoader(this, AppContext.BottleTimelineIcon); initWidget(); initSateMenu(); UICore.eventTask(this, this, init_notice_info, "init_notice_info", null); } private void initWidget() { backView = (ImageView) findViewById(R.id.topbar_back); backView.setOnClickListener(this); moreView = (ImageView) findViewById(R.id.topbar_menu); moreView.setOnClickListener(this); // noticeView = (ImageView) findViewById(R.id.topbar_notice); // noticeView.setOnClickListener(this); // messageCountLayout = (LinearLayout) findViewById(R.id.notice_layout); // messageCountLayout.setVisibility(View.GONE); // countView = (TextView) findViewById(R.id.notice_count); listView = (CustomListView) findViewById(R.id.notice_list); loadMoreView = LayoutInflater.from(this).inflate(R.layout.refreshable_list_footer, null); loadMoreView.setVisibility(View.GONE); listView.addFooterView(loadMoreView); listView.setonRefreshListener(new CustomListView.OnRefreshListener() { @Override public void onRefresh() { page = 1; new Thread() { public void run() { initNoticeInfo(); }; }.start(); } }); listView.setOnScrollListener(new OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { int itemsLastIndex = adapter.getCount() + 1; // 数据集最后一项的索引 int lastIndex = itemsLastIndex + 1; // 加上底部的loadMoreView项 和 head项 if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == lastIndex) { // 如果是自动加载,可以在这里放置异步加载数据的代码 loadMoreView.setVisibility(View.VISIBLE); page++; new Thread() { @Override public void run() { loadMoreNoticeInfo(); } }.start(); } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { listView.setFirstVisiableItem(firstVisibleItem); NoticeListActivity.this.visibleItemCount = visibleItemCount; visibleLastIndex = firstVisibleItem + visibleItemCount; } }); bottomLayout = (LinearLayout) findViewById(R.id.notice_bottom_layout); bottomLayout.setOnClickListener(this); avatarView = (ImageView) findViewById(R.id.notice_avatar); contentView = (TextView) findViewById(R.id.notice_text); btnCount = (TextView) findViewById(R.id.notice_number); // messageView = (ImageView) findViewById(R.id.notice_message_count); // messageView.setOnClickListener(this); // messageView.setVisibility(View.VISIBLE); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { if (arg2 == adapter.getCount() + 1) { return; } NoticeEntry entry = noticeList.get(arg2 - 1); /** * 通知类型,选择项:照片类通知(0)、瓶子类通知(1)、接受好友申请通知(2)、申请好友通知(3) * */ if (entry.getNotice_type() == 0) { Intent intent = new Intent(NoticeListActivity.this, UserPhotoActivity.class); intent.putExtra("ouid", entry.getUid()); intent.putExtra("picid", entry.getNotice_picid()); startActivity(intent); } else if (entry.getNotice_type() == 1) { Intent intent = new Intent(NoticeListActivity.this, BottleDetailActivity.class); intent.putExtra("btid", entry.getNotice_btid()); intent.putExtra("type", 1); startActivity(intent); } else if (entry.getNotice_type() == 2) { Intent intent = new Intent(NoticeListActivity.this, UserSpaceActivity.class); intent.putExtra("ouid", entry.getUid()); startActivity(intent); } else if (entry.getNotice_type() == 3) { doFriendAction(entry.getNickname(), entry.getUid()); } } }); } private void updateUI() { pushNoticeUpdateUI(); if (noticeList != null && !noticeList.isEmpty()) { adapter = new NoticeAdapter(); listView.setAdapter(adapter); } } @Override public void onClick(View v) { if (v == backView) { finish(); } else if (v == moreView) { Intent intent = new Intent(NoticeListActivity.this, HomeActivity.class); intent.putExtra("currentItem", 1); startActivity(intent); finish(); } // else if (v == noticeView) { // Intent intent = new Intent(this, MessageListActivity.class); // startActivity(intent); // } else if (v == bottomLayout) { doFeedsAction(); } // else if (v == messageView) { // doMessageAction(); // } } @Override public boolean handleMessage(Message msg) { switch (msg.what) { case init_notice_info: updateUI(); listView.onRefreshComplete(); receiver = new PushBroadcastReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction("push"); registerReceiver(receiver, filter); break; case user_baseinfo_notfull: showChoseMes(getString(R.string.exchange_complete_profile_tips), complete_info); break; case accept_friend: onToast((String) msg.obj); UICore.eventTask(this, this, init_notice_info, "init_notice_info", null); break; case reject_friend: onToast((String) msg.obj); UICore.eventTask(this, this, init_notice_info, "init_notice_info", null); break; case error: onToast((String) msg.obj); break; case more: adapter.notifyDataSetChanged(); loadMoreView.setVisibility(View.GONE); break; default: break; } return false; } @Override public void execute(int mes, Object obj) { switch (mes) { case init_notice_info: initNoticeInfo(); break; case accept_friend: acceptFriend((String) obj); break; case reject_friend: rejectFriend((String) obj); break; default: break; } } private void initNoticeInfo() { StringBuffer url = new StringBuffer(UrlConfig.get_mynoticeslist); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&count=" + 20); url.append("&page=" + page); try { String result = HttpUtils.doGet(url.toString()); if (result == null) { return; } Gson gson = new Gson(); NoticeInfo info = gson.fromJson(result, NoticeInfo.class); if (info.getResults().getAuthok() == 0) { Message msg = Message.obtain(handler, error, info.getResults().getErrmsg()); handler.sendMessage(msg); } else { getPushNotice(); noticeList = info.getNotices_list(); PushNoticeInfoTable table = new PushNoticeInfoTable(); pushInfo = table.getPushNoticeInfo(AppContext.getInstance().getLogin_uid()); if (null != pushInfo) { newBottleFeedCount = pushInfo.getNew_btfeed_count(); newExchangeFeedCount = pushInfo.getNew_exfeed_count(); newMessageCount = pushInfo.getNew_message_count(); newNoticeCount = pushInfo.getNew_notice_count(); newMaybeKownCount = pushInfo.getNew_maybeknow_count(); message_content = pushInfo.getMessage_content(); message_avatar = pushInfo.getMessage_avatar(); } handler.sendEmptyMessage(init_notice_info); } } catch (Exception e) { e.printStackTrace(); } } private void getPushNotice() { StringBuffer url = new StringBuffer(UrlConfig.push_notice); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); try { String result = HttpUtils.doGet(url.toString()); if (result != null) { JSONObject obj = new JSONObject(result); JSONObject resultObj = obj.getJSONObject("results"); if (resultObj.getInt("authok") == 1) { JSONObject pushObj = obj.getJSONObject("push_notice"); PushNoticeInfoTable table = new PushNoticeInfoTable(); PushNoticeInfo pushInfo = new PushNoticeInfo(); table.clearTable(); pushInfo.setMessage_avatar(pushObj.getString("message_avatar")); pushInfo.setMessage_content(pushObj.getString("message_content")); pushInfo.setNew_btfeed_count(pushObj.getInt("new_btfeed_count")); pushInfo.setNew_exfeed_count(pushObj.getInt("new_exfeed_count")); pushInfo.setNew_message_count(pushObj.getInt("new_message_count")); pushInfo.setNew_notice_count(pushObj.getInt("new_notice_count")); pushInfo.setNew_maybeknow_count(pushObj.getInt("new_maybeknow_count")); table.savePushNoticeInfo(pushInfo, AppContext.getInstance().getLogin_uid()); } } } catch (Exception e) { e.printStackTrace(); } } private void loadMoreNoticeInfo() { StringBuffer url = new StringBuffer(UrlConfig.get_mynoticeslist); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&count=" + 20); url.append("&page=" + page); try { String result = HttpUtils.doGet(url.toString()); if (result == null) { return; } Gson gson = new Gson(); NoticeInfo info = gson.fromJson(result, NoticeInfo.class); if (info.getResults().getAuthok() == 0) { Message msg = Message.obtain(handler, error, info.getResults().getErrmsg()); handler.sendMessage(msg); } else { List<NoticeEntry> moreList = info.getNotices_list(); noticeList.addAll(moreList); handler.sendEmptyMessage(more); } } catch (Exception e) { e.printStackTrace(); } } private void acceptFriend(String ouid) { String url = UrlConfig.accept_friend; HashMap<String, String> paramsMap = new HashMap<String, String>(); paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid())); paramsMap.put("login_token", AppContext.getInstance().getLogin_token()); paramsMap.put("ouid", ouid); try { String result = HttpUtils.doPost(this, url, paramsMap); if (result != null) { JSONObject object = new JSONObject(result); JSONObject resultObj = object.getJSONObject("results"); int success = resultObj.getInt("success"); if (success == 0) { String errmsg = resultObj.getString("errmsg"); Message msg = Message.obtain(handler, error, errmsg); handler.sendMessage(msg); } else { String successmsg = resultObj.getString("successmsg"); Message msg = Message.obtain(handler, accept_friend, successmsg); handler.sendMessage(msg); } } } catch (Exception e) { e.printStackTrace(); } } private void rejectFriend(String ouid) { String url = UrlConfig.reject_friend; HashMap<String, String> paramsMap = new HashMap<String, String>(); paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid())); paramsMap.put("login_token", AppContext.getInstance().getLogin_token()); paramsMap.put("ouid", ouid); try { String result = HttpUtils.doPost(this, url, paramsMap); if (result != null) { JSONObject object = new JSONObject(result); JSONObject resultObj = object.getJSONObject("results"); int success = resultObj.getInt("success"); if (success == 0) { String errmsg = resultObj.getString("errmsg"); Message msg = Message.obtain(handler, error, errmsg); handler.sendMessage(msg); } else { String successmsg = resultObj.getString("successmsg"); Message msg = Message.obtain(handler, accept_friend, successmsg); handler.sendMessage(msg); } } } catch (Exception e) { e.printStackTrace(); } } public class NoticeAdapter extends BaseAdapter { @Override public int getCount() { return noticeList.size(); } @Override public Object getItem(int arg0) { return noticeList.get(arg0); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView != null && convertView.getId() == R.id.notice_list_item_layout) { holder = (ViewHolder) convertView.getTag(); } else { convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.notice_list_item, null); holder = new ViewHolder(); holder.avatarView = (RemoteImageView) convertView.findViewById(R.id.notice_item_avatar); holder.nameView = (TextView) convertView.findViewById(R.id.notice_item_nameandcontent); holder.timeView = (TextView) convertView.findViewById(R.id.notice_item_time); holder.photoView = (ImageView) convertView.findViewById(R.id.notice_item_photo); holder.layout = (RelativeLayout) convertView.findViewById(R.id.notice_item_photo_layout); convertView.setTag(holder); } final NoticeEntry entry = noticeList.get(position); if (entry != null) { if (entry.getIsnew() == 1) { Drawable drawable = getResources().getDrawable(R.drawable.star); holder.nameView.setCompoundDrawables(null, null, drawable, null); } holder.avatarView.setDefaultImage(R.drawable.avatar_default_big); holder.avatarView.setImageUrl(entry.getAvatar(), position, listView); String name = "<font color=#419AD9>" + entry.getNickname() + "</font>"; holder.nameView.setText(Html.fromHtml(name + "&nbsp;" + (entry.getIsnew() == 1 ? "<font color=red>"+entry.getContent()+"</font>" : entry.getContent()))); holder.timeView.setText(entry.getNotice_time()); if (TextUtil.notEmpty(entry.getNotice_smallpic())) { holder.layout.setVisibility(View.VISIBLE); photoImageLoader.DisplayImage(entry.getNotice_smallpic(), holder.photoView, R.drawable.album_nophoto); holder.photoView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(NoticeListActivity.this, UserPhotoActivity.class); intent.putExtra("picid", entry.getNotice_picid()); intent.putExtra("ouid", entry.getUid()); startActivity(intent); } }); } else { holder.layout.setVisibility(View.GONE); } holder.avatarView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent spaceIntent = new Intent(NoticeListActivity.this, UserSpaceActivity.class); spaceIntent.putExtra("ouid", entry.getUid()); startActivity(spaceIntent); } }); } return convertView; } } public static class ViewHolder { RemoteImageView avatarView; TextView nameView; TextView timeView; ImageView photoView; RelativeLayout layout; } private void initSateMenu() { SatelliteMenu menu = (SatelliteMenu) findViewById(R.id.menu); menu.setVisibility(View.VISIBLE); if (CanvasWidth >= 480) { menu.setSatelliteDistance(200); } else { menu.setSatelliteDistance(100); } List<SatelliteMenuItem> items = new ArrayList<SatelliteMenuItem>(); items.add(new SatelliteMenuItem(menu_exprofile, R.drawable.menu_exprofile)); items.add(new SatelliteMenuItem(menu_exphoto, R.drawable.menu_exphoto)); items.add(new SatelliteMenuItem(menu_gainbt, R.drawable.menu_gainbt)); items.add(new SatelliteMenuItem(menu_sendbt, R.drawable.menu_sendbt)); items.add(new SatelliteMenuItem(menu_uploadphoto, R.drawable.menu_uploadphoto)); menu.addItems(items); menu.setOnItemClickedListener(new SateliteClickedListener() { public void eventOccured(int id) { switch (id) { case menu_sendbt: //扔瓶子 new Thread() { public void run() { try { Thread.sleep(500); Intent throwIntent = new Intent(NoticeListActivity.this, ChooseBottleActivity.class); throwIntent.putExtra("type", "throw"); startActivity(throwIntent); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; case menu_gainbt: //捞瓶子 new Thread() { public void run() { try { Thread.sleep(500); Intent tryIntent = new Intent(NoticeListActivity.this, ChooseBottleActivity.class); tryIntent.putExtra("type", "try"); startActivity(tryIntent); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; case menu_exphoto: //交换照片 new Thread() { public void run() { try { Thread.sleep(500); Intent exchangeInfoIntent = new Intent(NoticeListActivity.this, ChooseFriendActivity.class); exchangeInfoIntent.putExtra("choose_friend_type", AppContext.CHOOSE_FRIEND_EXCHANGE_PHOTO_TYPE); startActivity(exchangeInfoIntent); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; case menu_exprofile: //交换资料 new Thread() { public void run() { try { Thread.sleep(500); LoginUserInfoTable userTable = new LoginUserInfoTable(); LoginUserInfoEntry userEntry = userTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid()); if (userEntry.getBasicinfo_fullfill() == 0) { handler.sendEmptyMessage(user_baseinfo_notfull); } else { Intent exchangeFileIntent = new Intent(NoticeListActivity.this, ChooseFriendActivity.class); exchangeFileIntent.putExtra("choose_friend_type", AppContext.CHOOSE_FRIEND_EXCHANGE_INFO_TYPE); startActivity(exchangeFileIntent); } } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; case menu_uploadphoto: new Thread() { public void run() { try { Thread.sleep(500); Intent intent = new Intent(NoticeListActivity.this, ExpandEditActivity.class); Bundle extras = new Bundle(); extras.putString("from_type", AppContext.UPLOAD_PHOTO); extras.putInt("albumid", 0); extras.putInt("ouid", AppContext.getInstance().getLogin_uid()); intent.putExtras(extras); startActivity(intent); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; default: break; } } }); } @Override public void sysMesPositiveButtonEvent(int what) { if (what == complete_info) { Intent intent = new Intent(this, SettingActivity.class); startActivity(intent); } } private void doFriendAction(String nickname, final int ouid) { final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light); String cancel = getString(R.string.bt_title_back); String[] choices; choices = new String[3]; choices[0] = nickname + getString(R.string.user_info_space); choices[1] = getString(R.string.bottle_txt_notice_accept); choices[2] = getString(R.string.bottle_txt_notice_reject); final ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); switch (which) { case 0: Intent intent = new Intent(NoticeListActivity.this, UserSpaceActivity.class); intent.putExtra("ouid", ouid); startActivity(intent); break; case 1: UICore.eventTask(NoticeListActivity.this, NoticeListActivity.this, accept_friend, "accept_friend", String.valueOf(ouid)); break; case 2: UICore.eventTask(NoticeListActivity.this, NoticeListActivity.this, reject_friend, "reject_friend", String.valueOf(ouid)); break; } } }); builder.setNegativeButton(cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } public void doMessageAction() { final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light); String[] choices = new String[2]; if (newNoticeCount > 0) { choices[0] = newNoticeCount + getString(R.string.bottle_txt_notice_list); } else { choices[0] = getString(R.string.bottle_txt_notice_list); } if (newMessageCount > 0) { choices[1] = newMessageCount + getString(R.string.bottle_txt_message_list); } else { choices[1] = getString(R.string.bottle_txt_message_list); } final ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (which == 0) { Intent intent = new Intent(NoticeListActivity.this, NoticeListActivity.class); startActivity(intent); } else { Intent intent = new Intent(NoticeListActivity.this, MessageListActivity.class); startActivity(intent); } } }); builder.create().show(); } public void doFeedsAction() { final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light); final List<String> choices = new ArrayList<String>(); if (newBottleFeedCount > 0) { choices.add(newBottleFeedCount + getString(R.string.bottle_txt_new_bottle_feed)); } if (newExchangeFeedCount > 0) { choices.add(newExchangeFeedCount + getString(R.string.bottle_txt_new_exchange_feed)); } if (newNoticeCount > 0) { choices.add(newNoticeCount + getString(R.string.bottle_txt_notice_list)); } if (newMessageCount > 0) { choices.add(newMessageCount + getString(R.string.bottle_txt_message_list)); } if (newMaybeKownCount > 0) { choices.add(newMaybeKownCount + getString(R.string.bottle_txt_new_maybe_kown)); } final ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (choices.get(which).indexOf(getString(R.string.bottle_txt_new_bottle_feed)) != -1) { Intent intent = new Intent(NoticeListActivity.this, HomeActivity.class); AppContext.getInstance().setCurrentItem(1); startActivity(intent); } else if (choices.get(which).indexOf(getString(R.string.bottle_txt_new_exchange_feed)) != -1) { Intent intent = new Intent(NoticeListActivity.this, HomeActivity.class); AppContext.getInstance().setCurrentItem(0); startActivity(intent); } else if (choices.get(which).indexOf(getString(R.string.bottle_txt_notice_list)) != -1) { Intent intent = new Intent(NoticeListActivity.this, NoticeListActivity.class); startActivity(intent); } else if (choices.get(which).indexOf(getString(R.string.bottle_txt_message_list)) != -1) { Intent intent = new Intent(NoticeListActivity.this, MessageListActivity.class); startActivity(intent); } else if (choices.get(which).indexOf(getString(R.string.bottle_txt_new_maybe_kown)) != -1) { Intent intent = new Intent(NoticeListActivity.this, HomeActivity.class); AppContext.getInstance().setCurrentItem(2); AppContext.getInstance().setGotoMaybeKown(true); startActivity(intent); } } }); builder.create().show(); } public void pushNoticeUpdateUI() { if (newBottleFeedCount + newExchangeFeedCount + newMessageCount + newNoticeCount + newMaybeKownCount > 0) { bottomLayout.setVisibility(View.VISIBLE); contentView.setText(message_content); btnCount.setText(newBottleFeedCount + newExchangeFeedCount + newMessageCount + newNoticeCount + newMaybeKownCount + ""); userImageLoader.DisplayImage(message_avatar, avatarView, R.drawable.avatar_default_big); } else { bottomLayout.setVisibility(View.GONE); } } public class PushBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); if (bundle != null) { newBottleFeedCount = bundle.getInt("bottle_feed_count"); newExchangeFeedCount = bundle.getInt("exchange_feed_count"); newMessageCount = bundle.getInt("message_count"); newNoticeCount = bundle.getInt("notice_count"); message_content = bundle.getString("message_content"); message_avatar = bundle.getString("message_avatar"); newMaybeKownCount = bundle.getInt("maybe_kown_count"); pushNoticeUpdateUI(); } } } @Override protected void onDestroy() { super.onDestroy(); try { if (receiver != null) { unregisterReceiver(receiver); } } catch (Exception e) { e.printStackTrace(); } } }
Java
package com.outsourcing.bottle.ui; import java.util.ArrayList; import java.util.List; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Handler; import android.os.Handler.Callback; import android.os.Message; import android.text.Html; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ext.SatelliteMenu; import android.view.ext.SatelliteMenu.SateliteClickedListener; import android.view.ext.SatelliteMenuItem; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.GridView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.TextView; import com.google.gson.Gson; import com.outsourcing.bottle.BasicActivity; import com.outsourcing.bottle.R; import com.outsourcing.bottle.db.LoginUserInfoTable; import com.outsourcing.bottle.db.PushNoticeInfoTable; import com.outsourcing.bottle.domain.LoginUserInfoEntry; import com.outsourcing.bottle.domain.PhotoEntry; import com.outsourcing.bottle.domain.PhotoInfo; import com.outsourcing.bottle.domain.PhotoUserInfoEntry; import com.outsourcing.bottle.domain.PushNoticeInfo; import com.outsourcing.bottle.domain.UrlConfig; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.HttpUtils; import com.outsourcing.bottle.util.ImageLoader; import com.outsourcing.bottle.util.TextUtil; import com.outsourcing.bottle.util.UICore; import com.outsourcing.bottle.widget.ElasticScrollView; import com.outsourcing.bottle.widget.ElasticScrollView.OnRefreshListener; import com.outsourcing.bottle.widget.ElasticScrollView.OnScrollChangeBottom; /** * * @author 06peng * */ public class PhotosActivity extends BasicActivity implements Callback, OnClickListener { private ImageView backView; private TextView titleView; private ImageView uploadView; private ImageView avatarView; private TextView nicknameView; private ImageView sexView; private TextView memoView; private TextView doingView; private TextView addressView; private GridView gridView; private ImageView editView; private ElasticScrollView elasticScrollView; private View contentView; private Handler handler; private Bitmap bitmap; private int ouid; private int albumid; private PhotoUserInfoEntry userEntry; private List<PhotoEntry> photoList; private final int init_photo_info = 1; private final int error = 2; private final int user_baseinfo_notfull = 3; private final int complete_info = 4; private final int get_more_photo = 5; public static final int upload_photo_requestcode = 6; public static final int eidt_album_requestcode = 7; public static final int delete_photo_requestcode = 8; private final int menu_uploadphoto = 15; private final int menu_exprofile = 14; private final int menu_exphoto = 13; private final int menu_gainbt = 12; private final int menu_sendbt = 11; private PhotoAdapter adapter; private int page = 1; private int count = 15; private ImageView homeView; private LinearLayout bottomLayout; private ImageView bottomAvatarView; private TextView bottomContentView; private TextView btnCount; // private ImageView messageView; private ImageLoader loader; private int newNoticeCount; private int newMessageCount; private int newBottleFeedCount; private int newExchangeFeedCount; private int newMaybeKownCount; private String message_content; private String message_avatar; private PushBroadcastReceiver receiver; private PushNoticeInfo pushInfo; private Button bt_album; @Override protected void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); setContentView(R.layout.photos_elastic_scrolll); handler = new Handler(this); loader = new ImageLoader(this, AppContext.UserAvatarIcon); ouid = getIntent().getIntExtra("ouid", 0); albumid = getIntent().getIntExtra("albumid", 0); initWidget(); initSateMenu(); UICore.eventTask(this, this, init_photo_info, "init_photo_info", null); } private void initWidget() { homeView = (ImageView) findViewById(R.id.topbar_home); homeView.setOnClickListener(this); backView = (ImageView) findViewById(R.id.topbar_back); backView.setOnClickListener(this); uploadView = (ImageView) findViewById(R.id.topbar_menu); uploadView.setOnClickListener(this); uploadView.setImageResource(R.drawable.uploadphoto); titleView = (TextView) findViewById(R.id.topbar_title); titleView.setVisibility(View.VISIBLE); bottomLayout = (LinearLayout) findViewById(R.id.notice_bottom_layout); bottomLayout.setOnClickListener(this); bottomAvatarView = (ImageView) findViewById(R.id.notice_avatar); bottomContentView = (TextView) findViewById(R.id.notice_text); btnCount = (TextView) findViewById(R.id.notice_number); // messageView = (ImageView) findViewById(R.id.notice_message_count); // messageView.setOnClickListener(this); elasticScrollView = (ElasticScrollView) findViewById(R.id.refresh_view); elasticScrollView.setonRefreshListener(new OnRefreshListener() { @Override public void onRefresh() { page = 1; UICore.eventTask(PhotosActivity.this, PhotosActivity.this, init_photo_info, null, null); } }); elasticScrollView.setonScrollChangeListener(new OnScrollChangeBottom() { @Override public void onScrollBottom() { page++; UICore.eventTask(PhotosActivity.this, PhotosActivity.this, get_more_photo, null, null); } }); contentView = LayoutInflater.from(this).inflate(R.layout.user_photos, null); elasticScrollView.addChild(contentView); avatarView = (ImageView) contentView.findViewById(R.id.user_photo_avatar); nicknameView = (TextView) contentView.findViewById(R.id.user_photo_nickname); sexView = (ImageView) contentView.findViewById(R.id.user_photo_sex); memoView = (TextView) contentView.findViewById(R.id.user_photo_memo); doingView = (TextView) contentView.findViewById(R.id.user_photo_doing); addressView = (TextView) contentView.findViewById(R.id.user_photo_address); editView = (ImageView) contentView.findViewById(R.id.user_photo_edit_ablum_title); bt_album = (Button)contentView.findViewById(R.id.bt_album); editView.setOnClickListener(this); gridView = (GridView) contentView.findViewById(R.id.user_photo_grid); gridView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Intent intent = new Intent(PhotosActivity.this, UserPhotoActivity.class); intent.putExtra("ouid", ouid); intent.putExtra("picid", photoList.get(arg2).getPic_id()); intent.putExtra("albumid", albumid); startActivityForResult(intent, delete_photo_requestcode); } }); } private void updateUI() { uploadView.setVisibility(View.VISIBLE); homeView.setVisibility(View.VISIBLE); findViewById(R.id.photo_scroll_layout).setVisibility(View.VISIBLE); if (userEntry != null) { if (userEntry.getOuid() == AppContext.getInstance().getLogin_uid()) { editView.setVisibility(View.VISIBLE); } else { editView.setVisibility(View.GONE); } nicknameView.setText(userEntry.getNickname()); if (userEntry.getSex() == 1) { sexView.setBackgroundResource(R.drawable.male); } else if (userEntry.getSex() == 2) { sexView.setBackgroundResource(R.drawable.female); } if (TextUtil.notEmpty(userEntry.getMemo())) { memoView.setText("-" + userEntry.getMemo()); memoView.setVisibility(View.VISIBLE); } else { memoView.setVisibility(View.GONE); } if (bitmap != null) { avatarView.setImageBitmap(bitmap); } if (TextUtil.notEmpty(userEntry.getCity()) && TextUtil.notEmpty(userEntry.getCountry())) { addressView.setVisibility(View.VISIBLE); if (AppContext.language == 1) { addressView.setText(getString(R.string.user_from) + userEntry.getCountry() + " " + userEntry.getCity()); } else { addressView.setText(getString(R.string.user_from) + userEntry.getCity() + " " + userEntry.getCountry()); } } else { addressView.setVisibility(View.GONE); } String html = "<font color=black>"+getString(R.string.user_info_doing)+"</font>"; doingView.setText(Html.fromHtml(html + userEntry.getDoing())); titleView.setText(userEntry.getAlbum_title()); bt_album.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(PhotosActivity.this, AlbumsActivity.class); intent.putExtra("ouid", userEntry.getOuid()); startActivity(intent); } }); } if (photoList != null && !photoList.isEmpty()) { adapter = new PhotoAdapter(); gridView.setAdapter(adapter); } } @Override public void onClick(View v) { if (v == backView) { finish(); } else if (v == homeView) { Intent intent = new Intent(this, HomeActivity.class); intent.putExtra("currentItem", 1); startActivity(intent); } else if (v == editView) { Intent intent = new Intent(this, ExpandEditActivity.class); Bundle extras = new Bundle(); extras.putString("from_type", AppContext.EDIT_ALBUM); extras.putInt("albumid", albumid); extras.putString("albumname", userEntry.getAlbum_title()); extras.putString("album_from", "photos"); intent.putExtras(extras); startActivityForResult(intent, eidt_album_requestcode); } else if (v == uploadView) { Intent intent = new Intent(this, ExpandEditActivity.class); Bundle extras = new Bundle(); extras.putString("from_type", AppContext.UPLOAD_PHOTO); extras.putInt("albumid", albumid); extras.putString("upload_from", "photos"); intent.putExtras(extras); startActivityForResult(intent, upload_photo_requestcode); } // else if (v == messageView) { // doMessageAction(); // } else if (v == bottomLayout) { doFeedsAction(); } } @Override public boolean handleMessage(Message msg) { switch (msg.what) { case init_photo_info: updateUI(); if (adapter != null && adapter.getCount() >= count) { elasticScrollView.setMoreCount(true); } else { elasticScrollView.setMoreCount(false); } elasticScrollView.onRefreshComplete(); pushNoticeUpdateUI(); receiver = new PushBroadcastReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction("push"); registerReceiver(receiver, filter); break; case error: onToast((String) msg.obj); break; case user_baseinfo_notfull: showChoseMes(getString(R.string.exchange_complete_profile_tips), complete_info); break; case get_more_photo: if (adapter != null) { adapter.notifyDataSetChanged(); } elasticScrollView.onScrollChangeComplete(); break; default: break; } return false; } @Override public void execute(int mes, Object obj) { switch (mes) { case init_photo_info: initPhotoInfo(); break; case get_more_photo: getMorePhoto(); break; default: break; } } private void initPhotoInfo() { StringBuffer url = new StringBuffer(UrlConfig.get_albumpics_list); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); url.append("&count=" + count); url.append("&page=" + page); url.append("&albumid=" + albumid); try { String result = HttpUtils.doGet(url.toString()); if (result == null) { return; } Gson gson = new Gson(); PhotoInfo info = gson.fromJson(result, PhotoInfo.class); if (info.getResults().getAuthok() == 0) { Message msg = Message.obtain(handler, error, info.getResults().getErrmsg()); handler.sendMessage(msg); } else { PushNoticeInfoTable table = new PushNoticeInfoTable(); pushInfo = table.getPushNoticeInfo(AppContext.getInstance().getLogin_uid()); if (pushInfo != null) { newBottleFeedCount = pushInfo.getNew_btfeed_count(); newExchangeFeedCount = pushInfo.getNew_exfeed_count(); newMessageCount = pushInfo.getNew_message_count(); newNoticeCount = pushInfo.getNew_notice_count(); newMaybeKownCount = pushInfo.getNew_maybeknow_count(); message_content = pushInfo.getMessage_content(); message_avatar = pushInfo.getMessage_avatar(); } userEntry = info.getUser_info(); photoList = info.getAlbumpics_list(); bitmap = HttpUtils.getBitmapFromUrl(PhotosActivity.this, userEntry.getAvatar()); handler.sendEmptyMessage(init_photo_info); } } catch (Exception e) { e.printStackTrace(); } } private void getMorePhoto() { StringBuffer url = new StringBuffer(UrlConfig.get_albumpics_list); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); url.append("&count=" + count); url.append("&page=" + page); url.append("&albumid=" + albumid); try { String result = HttpUtils.doGet(url.toString()); if (result == null) { return; } Gson gson = new Gson(); PhotoInfo info = gson.fromJson(result, PhotoInfo.class); if (info.getResults().getAuthok() == 0) { Message msg = Message.obtain(handler, error, info.getResults().getErrmsg()); handler.sendMessage(msg); } else { List<PhotoEntry> morePhotoList = info.getAlbumpics_list(); if (morePhotoList != null && !morePhotoList.isEmpty()) { photoList.addAll(morePhotoList); } handler.sendEmptyMessage(get_more_photo); } } catch (Exception e) { e.printStackTrace(); } } public class PhotoAdapter extends BaseAdapter { @Override public int getCount() { return photoList.size(); } @Override public Object getItem(int arg0) { return photoList.get(arg0); } @Override public long getItemId(int arg0) { return arg0; } @Override public View getView(int arg0, View arg1, ViewGroup arg2) { ViewHolder holder; if (arg1 == null) { arg1 = LayoutInflater.from(getApplicationContext()).inflate(R.layout.user_photo_item, null); holder = new ViewHolder(); holder.image = (ImageView) arg1.findViewById(R.id.photo_image); // holder.commentLayout = (LinearLayout) arg1.findViewById(R.id.photo_comment_layout); holder.doodle = (TextView)arg1.findViewById(R.id.photo_comment_doodle); holder.count = (TextView) arg1.findViewById(R.id.photo_comment_count); arg1.setTag(holder); } else { holder = (ViewHolder) arg1.getTag(); } PhotoEntry entry = photoList.get(arg0); if (entry != null) { loader.DisplayImage(entry.getPic_url(), holder.image, R.drawable.album_nophoto); if (entry.getIs_doodle() == 1) { holder.doodle.setVisibility(View.VISIBLE); } else { holder.doodle.setVisibility(View.GONE); } if (entry.getComments_num() > 0) { // holder.commentLayout.setVisibility(View.VISIBLE); holder.count.setVisibility(View.VISIBLE); holder.count.setText(entry.getComments_num() + ""); } else { holder.count.setVisibility(View.INVISIBLE); // holder.commentLayout.setVisibility(View.INVISIBLE); } } return arg1; } } public static class ViewHolder { public TextView doodle; TextView count; ImageView image; LinearLayout commentLayout; } SatelliteMenu menu; private void initSateMenu() { if (menu == null) { LinearLayout layout = (LinearLayout) findViewById(R.id.menu_layout); menu = new SatelliteMenu(this); // menu.setExpandDuration(500); if (CanvasWidth >= 480) { menu.setSatelliteDistance(200); } else { menu.setSatelliteDistance(100); } menu.setTotalSpacingDegree(90.0f); menu.setCloseItemsOnClick(true); layout.addView(menu); List<SatelliteMenuItem> items = new ArrayList<SatelliteMenuItem>(); items.add(new SatelliteMenuItem(menu_exprofile, R.drawable.menu_exprofile)); items.add(new SatelliteMenuItem(menu_exphoto, R.drawable.menu_exphoto)); items.add(new SatelliteMenuItem(menu_gainbt, R.drawable.menu_gainbt)); items.add(new SatelliteMenuItem(menu_sendbt, R.drawable.menu_sendbt)); items.add(new SatelliteMenuItem(menu_uploadphoto, R.drawable.menu_uploadphoto)); menu.addItems(items); } menu.setOnItemClickedListener(new SateliteClickedListener() { public void eventOccured(int id) { switch (id) { case menu_sendbt: //扔瓶子 new Thread() { public void run() { try { Thread.sleep(500); Intent throwIntent = new Intent(PhotosActivity.this, ChooseBottleActivity.class); throwIntent.putExtra("type", "throw"); startActivity(throwIntent); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; case menu_gainbt: //捞瓶子 new Thread() { public void run() { try { Thread.sleep(500); Intent tryIntent = new Intent(PhotosActivity.this, ChooseBottleActivity.class); tryIntent.putExtra("type", "try"); startActivity(tryIntent); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; case menu_exphoto: //交换照片 new Thread() { public void run() { try { Thread.sleep(500); Intent exchangeInfoIntent = new Intent(PhotosActivity.this, ChooseFriendActivity.class); exchangeInfoIntent.putExtra("choose_friend_type", AppContext.CHOOSE_FRIEND_EXCHANGE_PHOTO_TYPE); startActivity(exchangeInfoIntent); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; case menu_exprofile: //交换资料 new Thread() { public void run() { try { Thread.sleep(500); LoginUserInfoTable userTable = new LoginUserInfoTable(); LoginUserInfoEntry userEntry = userTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid()); if (userEntry.getBasicinfo_fullfill() == 0) { handler.sendEmptyMessage(user_baseinfo_notfull); } else { Intent exchangeFileIntent = new Intent(PhotosActivity.this, ChooseFriendActivity.class); exchangeFileIntent.putExtra("choose_friend_type", AppContext.CHOOSE_FRIEND_EXCHANGE_INFO_TYPE); startActivity(exchangeFileIntent); } } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; case menu_uploadphoto: new Thread() { public void run() { try { Thread.sleep(500); Intent intent = new Intent(PhotosActivity.this, ExpandEditActivity.class); Bundle extras = new Bundle(); extras.putString("from_type", AppContext.UPLOAD_PHOTO); extras.putInt("albumid", 0); extras.putInt("ouid", AppContext.getInstance().getLogin_uid()); intent.putExtras(extras); startActivity(intent); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; default: break; } } }); } @Override public void sysMesPositiveButtonEvent(int what) { if (what == complete_info) { Intent intent = new Intent(this, SettingActivity.class); startActivity(intent); } } @Override protected void onActivityResult(int arg0, int arg1, Intent arg2) { if (arg1 == RESULT_OK) { if (arg0 == upload_photo_requestcode) { UICore.eventTask(this, this, init_photo_info, "init_photo_info", null); } else if (arg0 == eidt_album_requestcode) { UICore.eventTask(this, this, init_photo_info, "init_photo_info", null); } else if (arg0 == delete_photo_requestcode) { UICore.eventTask(this, this, init_photo_info, "init_photo_info", null); } } super.onActivityResult(arg0, arg1, arg2); } public void doMessageAction() { final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light); String[] choices = new String[2]; if (newNoticeCount > 0) { choices[0] = newNoticeCount + getString(R.string.bottle_txt_notice_list); } else { choices[0] = getString(R.string.bottle_txt_notice_list); } if (newMessageCount > 0) { choices[1] = newMessageCount + getString(R.string.bottle_txt_message_list); } else { choices[1] = getString(R.string.bottle_txt_message_list); } final ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (which == 0) { Intent intent = new Intent(PhotosActivity.this, NoticeListActivity.class); startActivity(intent); } else { Intent intent = new Intent(PhotosActivity.this, MessageListActivity.class); startActivity(intent); } } }); builder.create().show(); } public void doFeedsAction() { final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light); final List<String> choices = new ArrayList<String>(); if (newBottleFeedCount > 0) { choices.add(newBottleFeedCount + getString(R.string.bottle_txt_new_bottle_feed)); } if (newExchangeFeedCount > 0) { choices.add(newExchangeFeedCount + getString(R.string.bottle_txt_new_exchange_feed)); } if (newNoticeCount > 0) { choices.add(newNoticeCount + getString(R.string.bottle_txt_notice_list)); } if (newMessageCount > 0) { choices.add(newMessageCount + getString(R.string.bottle_txt_message_list)); } if (newMaybeKownCount > 0) { choices.add(newMaybeKownCount + getString(R.string.bottle_txt_new_maybe_kown)); } final ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (choices.get(which).indexOf(getString(R.string.bottle_txt_new_bottle_feed)) != -1) { Intent intent = new Intent(PhotosActivity.this, HomeActivity.class); AppContext.getInstance().setCurrentItem(1); startActivity(intent); } else if (choices.get(which).indexOf(getString(R.string.bottle_txt_new_exchange_feed)) != -1) { Intent intent = new Intent(PhotosActivity.this, HomeActivity.class); AppContext.getInstance().setCurrentItem(0); startActivity(intent); } else if (choices.get(which).indexOf(getString(R.string.bottle_txt_notice_list)) != -1) { Intent intent = new Intent(PhotosActivity.this, NoticeListActivity.class); startActivity(intent); } else if (choices.get(which).indexOf(getString(R.string.bottle_txt_message_list)) != -1) { Intent intent = new Intent(PhotosActivity.this, MessageListActivity.class); startActivity(intent); } else if (choices.get(which).indexOf(getString(R.string.bottle_txt_new_maybe_kown)) != -1) { Intent intent = new Intent(PhotosActivity.this, HomeActivity.class); AppContext.getInstance().setCurrentItem(2); AppContext.getInstance().setGotoMaybeKown(true); startActivity(intent); } } }); builder.create().show(); } public void pushNoticeUpdateUI() { if (newBottleFeedCount + newExchangeFeedCount + newMessageCount + newNoticeCount + newMaybeKownCount > 0) { bottomLayout.setVisibility(View.VISIBLE); bottomContentView.setText(message_content); btnCount.setText(newBottleFeedCount + newExchangeFeedCount + newMessageCount + newNoticeCount + newMaybeKownCount + ""); loader.DisplayImage(message_avatar, bottomAvatarView, R.drawable.avatar_default_big); } else { bottomLayout.setVisibility(View.GONE); } } public class PushBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); if (bundle != null) { newBottleFeedCount = bundle.getInt("bottle_feed_count"); newExchangeFeedCount = bundle.getInt("exchange_feed_count"); newMessageCount = bundle.getInt("message_count"); newNoticeCount = bundle.getInt("notice_count"); message_content = bundle.getString("message_content"); message_avatar = bundle.getString("message_avatar"); newMaybeKownCount = bundle.getInt("maybe_kown_count"); pushNoticeUpdateUI(); } } } @Override protected void onDestroy() { super.onDestroy(); try { if (receiver != null) { unregisterReceiver(receiver); } } catch (Exception e) { e.printStackTrace(); } } }
Java
package com.outsourcing.bottle.ui; import it.sephiroth.android.library.imagezoom.ImageViewTouch; import it.sephiroth.android.library.imagezoom.ImageViewTouchBase; import java.io.File; import java.io.FileOutputStream; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.concurrent.Future; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Bitmap.CompressFormat; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.DisplayMetrics; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.Animation.AnimationListener; import com.aviary.android.feather.Constants; import com.aviary.android.feather.FeatherActivity; import com.aviary.android.feather.FilterManager; import com.aviary.android.feather.FilterManager.FeatherContext; import com.aviary.android.feather.async_tasks.DownloadImageAsyncTask; import com.aviary.android.feather.async_tasks.ExifTask; import com.aviary.android.feather.async_tasks.DownloadImageAsyncTask.OnImageDownloadListener; import com.aviary.android.feather.effects.AbstractEffectPanel.ContentPanel; import com.aviary.android.feather.graphics.ToolIconsDrawable; import com.aviary.android.feather.library.content.EffectEntry; import com.aviary.android.feather.library.filters.FilterLoaderFactory; import com.aviary.android.feather.library.filters.NativeFilterProxy; import com.aviary.android.feather.library.services.FutureListener; import com.aviary.android.feather.library.services.LocalDataService; import com.aviary.android.feather.library.services.ThreadPoolService; import com.aviary.android.feather.library.utils.IOUtils; import com.aviary.android.feather.library.utils.StringUtils; import com.aviary.android.feather.library.utils.SystemUtils; import com.aviary.android.feather.library.utils.UIConfiguration; import com.aviary.android.feather.library.utils.ImageLoader.ImageSizes; import com.aviary.android.feather.utils.UIUtils; import com.aviary.android.feather.widget.BottombarViewFlipper; import com.aviary.android.feather.widget.IToast; import com.aviary.android.feather.widget.ToolbarView; import com.outsourcing.bottle.BasicActivity; import com.outsourcing.bottle.R; import com.outsourcing.bottle.util.Utility; /** * * @author 06peng * */ public class CropImage2Activity extends BasicActivity implements OnImageDownloadListener,FeatherContext{ private static final String TAG = CropImage2Activity.class.getSimpleName(); private Bitmap mBitmap; /** session id for the hi-res post processing */ private String mSessionId; /** delay between click and panel opening */ private static final int TOOLS_OPEN_DELAY_TIME = 50; protected FilterManager mFilterManager; private MyUIHandler mUIHandler; /** api key. */ protected String mApiKey = ""; /** The default result code. */ private int pResultCode = RESULT_CANCELED; @Override protected void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); setContentView(R.layout.crop_view_news); mImageView = (ImageViewTouch) findViewById( R.id.crop_image ); mDrawingViewContainer = (ViewGroup) findViewById( R.id.crop_drawing_view_container ); mInlineProgressLoader = findViewById( R.id.crop_image_loading_view ); init(); onInitializeUtils(); initializeUI(); // initiate the filter manager mUIHandler = new MyUIHandler( this ); mFilterManager = new FilterManager( this, mUIHandler, mApiKey ); // mFilterManager.setOnToolListener( this ); // mFilterManager.setOnBitmapChangeListener( this ); // mFilterManager.setDragLayer( mDragLayer ); Uri srcUri = handleIntent( getIntent() ); if ( srcUri == null ) { onSetResult( RESULT_CANCELED, null ); finish(); return; } LocalDataService data = mFilterManager.getService( LocalDataService.class ); data.setSourceImageUri( srcUri ); // download the requested image loadImage( srcUri ); loadEgg(); } private void loadEgg() { final EffectEntry entry= new EffectEntry( FilterLoaderFactory.Filters.CROP, R.drawable.feather_tool_icon_crop, R.string.crop); mUIHandler.postDelayed( new Runnable() { @Override public void run() { mFilterManager.activateEffect(entry); } }, TOOLS_OPEN_DELAY_TIME ); } String path = null; private void init() { path = getIntent().getStringExtra("path"); Log.d("may", "path=" + path); mBitmap = BitmapFactory.decodeFile(path); } public void onClick(View v) { switch (v.getId()) { case R.id.cancel: break; // case R.id.crop: // mCrop.crop(mBitmap); // break; case R.id.save: // inputDialog(); break; } } /** * Initialize ui. */ @SuppressWarnings("deprecation") private void initializeUI() { // register the toolbar listeners mImageView.setDoubleTapEnabled( false ); } /** * Initialize utility classes */ protected void onInitializeUtils() { UIUtils.init( this ); Constants.init( this ); NativeFilterProxy.init( this, null ); } private static class MyUIHandler extends Handler { private WeakReference<CropImage2Activity> mParent; MyUIHandler( CropImage2Activity parent ) { mParent = new WeakReference<CropImage2Activity>( parent ); } @Override public void handleMessage( Message msg ) { super.handleMessage( msg ); CropImage2Activity parent = mParent.get(); if ( null != parent ) { switch ( msg.what ) { case FilterManager.STATE_OPENING: break; case FilterManager.STATE_OPENED: break; case FilterManager.STATE_CLOSING: parent.mImageView.setVisibility( View.VISIBLE ); break; case FilterManager.STATE_CLOSED: break; case FilterManager.STATE_DISABLED: break; case FilterManager.STATE_CONTENT_READY: parent.mImageView.setVisibility( View.GONE ); break; case FilterManager.STATE_READY: break; } } } } /** inline progress loader. */ private View mInlineProgressLoader; /** The maim image view. */ private ImageViewTouch mImageView; /** The main drawing view container for tools implementing {@link ContentPanel}. */ private ViewGroup mDrawingViewContainer; /* * (non-Javadoc) * * @see android.app.Activity#onContentChanged() */ @Override public void onContentChanged() { super.onContentChanged(); } String mOutputFilePath; /** * Once you've chosen an image you can start the feather activity * * @param uri */ private void startFeather( Uri uri ) { if ( !Utility.isExternalStorageAvilable() ) { return; } // create a temporary file where to store the resulting image File file = Utility.getNextFileName(); if ( null != file ) { mOutputFilePath = file.getAbsolutePath(); } else { new AlertDialog.Builder( this ).setTitle( android.R.string.dialog_alert_title ).setMessage( "Failed to create a new File" ) .show(); return; } Intent newIntent = new Intent( this, FeatherActivity.class ); newIntent.putExtra( "From_Type", Constants.ACTIVITY_EDIT ); // set the source image uri newIntent.setData( uri ); // pass the required api_key and secret ( see // http://developers.aviary.com/ ) newIntent.putExtra( "API_KEY", Utility.API_KEY ); newIntent.putExtra( "output", Uri.parse( "file://" + mOutputFilePath ) ); newIntent.putExtra( Constants.EXTRA_OUTPUT_FORMAT, Bitmap.CompressFormat.JPEG.name() ); newIntent.putExtra( Constants.EXTRA_OUTPUT_QUALITY, 100 ); newIntent.putExtra( Constants.EXTRA_TOOLS_DISABLE_VIBRATION, true ); final DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics( metrics ); int max_size = Math.min( metrics.widthPixels, metrics.heightPixels ); // you can pass the maximum allowed image size, otherwise feather will determine // the max size based on the device memory // Here we're passing the current display size as max image size because after // the execution of Aviary we're saving the HI-RES image so we don't need a big // image for the preview max_size = (int) ( (double) max_size / 0.8 ); newIntent.putExtra( "max-image-size", max_size ); // Enable/disable the default borders for the effects newIntent.putExtra( "effect-enable-borders", true ); mSessionId = StringUtils.getSha256( System.currentTimeMillis() + Utility.API_KEY ); Log.d( TAG, "session: " + mSessionId + ", size: " + mSessionId.length() ); newIntent.putExtra( "output-hires-session-id", mSessionId ); startActivity(newIntent); } public void saveBitmap(String dir,Bitmap bmp) { File file = new File(dir); String path = null; if (!file.exists()) file.mkdirs(); try { path = file.getPath() + "/upload.jpeg"; FileOutputStream fileOutputStream = new FileOutputStream(path); bmp.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream); fileOutputStream.flush(); fileOutputStream.close(); } catch (Exception e) { e.printStackTrace(); } } protected Uri handleIntent( Intent intent ) { LocalDataService service = mFilterManager.getService( LocalDataService.class ); if ( intent != null && intent.getData() != null ) { Uri data = intent.getData(); if ( SystemUtils.isIceCreamSandwich() ) { if ( data.toString().startsWith( "content://com.android.gallery3d.provider" ) ) { // use the com.google provider, not the com.android provider ( for ICS only ) data = Uri.parse( data.toString().replace( "com.android.gallery3d", "com.google.android.gallery3d" ) ); } } Bundle extras = intent.getExtras(); if ( extras != null ) { Uri destUri = (Uri) extras.getParcelable( Constants.EXTRA_OUTPUT ); mApiKey = extras.getString( Constants.API_KEY ); if ( destUri != null ) { service.setDestImageUri( destUri ); String outputFormatString = extras.getString( Constants.EXTRA_OUTPUT_FORMAT ); if ( outputFormatString != null ) { CompressFormat format = Bitmap.CompressFormat.valueOf( outputFormatString ); service.setOutputFormat( format ); } } if ( extras.containsKey( Constants.EXTRA_HIDE_EXIT_UNSAVE_CONFIRMATION ) ) { mHideExitAlertConfirmation = extras.getBoolean( Constants.EXTRA_HIDE_EXIT_UNSAVE_CONFIRMATION ); } } return data; } return null; } protected void loadImage( Uri data ) { if ( null != mDownloadTask ) { mDownloadTask.setOnLoadListener( null ); mDownloadTask = null; } mDownloadTask = new DownloadImageAsyncTask( data ); mDownloadTask.setOnLoadListener( this ); mDownloadTask.execute( getBaseContext() ); } /** Main image downloader task **/ private DownloadImageAsyncTask mDownloadTask; /** The Constant ALERT_CONFIRM_EXIT. */ private static final int ALERT_CONFIRM_EXIT = 0; /** The Constant ALERT_DOWNLOAD_ERROR. */ private static final int ALERT_DOWNLOAD_ERROR = 1; /** The Constant ALERT_REVERT_IMAGE. */ private static final int ALERT_REVERT_IMAGE = 2; /** hide exit alert confirmation. */ protected boolean mHideExitAlertConfirmation = false; /* * (non-Javadoc) * * @see com.aviary.android.feather.async_tasks.DownloadImageAsyncTask.OnImageDownloadListener#onDownloadStart() */ @Override public void onDownloadStart() { mImageView.setVisibility( View.INVISIBLE ); mInlineProgressLoader.setVisibility( View.VISIBLE ); } @SuppressWarnings("deprecation") @Override public void onDownloadError( String error ) { mDownloadTask = null; hideProgressLoader(); showDialog( ALERT_DOWNLOAD_ERROR ); } @Override public void onDownloadComplete( Bitmap result, ImageSizes sizes ) { mDownloadTask = null; mImageView.setImageBitmap( result, true, null, UIConfiguration.IMAGE_VIEW_MAX_ZOOM ); Animation animation = AnimationUtils.loadAnimation( this, android.R.anim.fade_in ); animation.setFillEnabled( true ); mImageView.setVisibility( View.VISIBLE ); mImageView.startAnimation( animation ); hideProgressLoader(); int[] originalSize = { -1, -1 }; if ( null != sizes ) { originalSize = sizes.getRealSize(); onImageSize( sizes.getOriginalSize(), sizes.getNewSize(), sizes.getBucketSize() ); } if ( mFilterManager != null ) { if ( mFilterManager.getEnabled() ) { mFilterManager.onReplaceImage( result, originalSize ); } else { mFilterManager.onActivate( result, originalSize ); } } computeOriginalFilePath(); loadExif(); } protected void onImageSize( String originalSize, String scaledSize, String bucket ) { HashMap<String, String> attributes = new HashMap<String, String>(); attributes.put( "originalSize", originalSize ); attributes.put( "newSize", scaledSize ); attributes.put( "bucketSize", bucket ); } /** * Hide progress loader. */ private void hideProgressLoader() { Animation fadeout = new AlphaAnimation( 1, 0 ); fadeout.setDuration( getResources().getInteger( R.integer.feather_config_mediumAnimTime ) ); fadeout.setAnimationListener( new AnimationListener() { @Override public void onAnimationStart( Animation animation ) {} @Override public void onAnimationRepeat( Animation animation ) {} @Override public void onAnimationEnd( Animation animation ) { mInlineProgressLoader.setVisibility( View.GONE ); } } ); mInlineProgressLoader.startAnimation( fadeout ); } /** * Try to compute the original file absolute path */ protected void computeOriginalFilePath() { final LocalDataService data = mFilterManager.getService( LocalDataService.class ); if ( null != data ) { data.setSourceImagePath( null ); Uri uri = data.getSourceImageUri(); if ( null != uri ) { String path = IOUtils.getRealFilePath( this, uri ); if ( null != path ) { data.setSourceImagePath( path ); } } } } /** * load the original file EXIF data and store the result into the local data instance */ protected void loadExif() { final LocalDataService data = mFilterManager.getService( LocalDataService.class ); ThreadPoolService thread = mFilterManager.getService( ThreadPoolService.class ); if ( null != data && thread != null ) { final String path = data.getSourceImagePath(); FutureListener<Bundle> listener = new FutureListener<Bundle>() { @Override public void onFutureDone( Future<Bundle> future ) { try { Bundle result = future.get(); if ( null != result ) { data.setOriginalExifBundle( result ); } } catch ( Throwable e ) { e.printStackTrace(); } } }; if ( null != path ) { thread.submit( new ExifTask(), listener, path ); } else { } } } /* * (non-Javadoc) * * @see android.app.Activity#onCreateDialog(int) */ @Override protected Dialog onCreateDialog( int id ) { Dialog dialog = null; switch ( id ) { case ALERT_CONFIRM_EXIT: dialog = new AlertDialog.Builder( this ).setTitle( R.string.confirm ).setMessage( R.string.confirm_quit_message ) .setPositiveButton( R.string.yes_leave, new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog, int which ) { dialog.dismiss(); onBackPressed( true ); } } ).setNegativeButton( R.string.keep_editing, new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog, int which ) { dialog.dismiss(); } } ).create(); break; case ALERT_DOWNLOAD_ERROR: dialog = new AlertDialog.Builder( this ).setTitle( R.string.attention ) .setMessage( R.string.error_download_image_message ).create(); break; case ALERT_REVERT_IMAGE: dialog = new AlertDialog.Builder( this ).setTitle( R.string.revert_dialog_title ) .setMessage( R.string.revert_dialog_message ) .setPositiveButton( android.R.string.yes, new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog, int which ) { dialog.dismiss(); onRevert(); } } ).setNegativeButton( android.R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog, int which ) { dialog.dismiss(); } } ).create(); break; } return dialog; } /** * Revert the original image. */ private void onRevert() { LocalDataService service = mFilterManager.getService( LocalDataService.class ); loadImage( service.getSourceImageUri() ); } /* * (non-Javadoc) * * @see android.app.Activity#onBackPressed() */ @SuppressWarnings("deprecation") @Override public void onBackPressed() { if ( !mFilterManager.onBackPressed() ) { if ( mFilterManager.getBitmapIsChanged() ) { if ( mHideExitAlertConfirmation ) { super.onBackPressed(); } else { showDialog( ALERT_CONFIRM_EXIT ); } } else { super.onBackPressed(); } } } /** * On back pressed. * * @param force * the super backpressed behavior */ protected void onBackPressed( boolean force ) { if ( force ) super.onBackPressed(); else onBackPressed(); } /** * Override the internal setResult in order to register the internal close status. * * @param resultCode * the result code * @param data * the data */ protected final void onSetResult( int resultCode, Intent data ) { pResultCode = resultCode; setResult( resultCode, data ); } @Override public ImageViewTouchBase getMainImage() { return mImageView; } @Override public BottombarViewFlipper getBottomBar() { return null; } @Override public ViewGroup getOptionsPanelContainer() { // TODO Auto-generated method stub return null; } @Override public ViewGroup getDrawingImageContainer() { return mDrawingViewContainer; } @Override public void showToolProgress() { // TODO Auto-generated method stub } @Override public void hideToolProgress() { // TODO Auto-generated method stub } private IToast mToastLoader; @Override public void showModalProgress() { if ( mToastLoader == null ) { mToastLoader = UIUtils.createModalLoaderToast(); } mToastLoader.show(); } @Override public void hideModalProgress() { if ( mToastLoader != null ) { mToastLoader.hide(); } } @Override public ToolbarView getToolbar() { return null; } }
Java
package com.outsourcing.bottle.ui; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.json.JSONObject; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Handler.Callback; import android.os.Message; import android.os.Process; import android.view.Gravity; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.view.ext.SatelliteMenu; import android.view.ext.SatelliteMenu.SateliteClickedListener; import android.view.ext.SatelliteMenuItem; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.Gallery; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ListView; import android.widget.PopupWindow; import android.widget.RelativeLayout; import android.widget.TextView; import com.google.gson.Gson; import com.outsourcing.bottle.BasicActivity; import com.outsourcing.bottle.R; import com.outsourcing.bottle.adapter.PublicActivityAdapter; import com.outsourcing.bottle.adapter.TabAdapter; import com.outsourcing.bottle.db.LoginUserInfoTable; import com.outsourcing.bottle.domain.BottleTimelineInfo; import com.outsourcing.bottle.domain.LoginUserInfo; import com.outsourcing.bottle.domain.LoginUserInfoEntry; import com.outsourcing.bottle.domain.UrlConfig; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.HttpUtils; import com.outsourcing.bottle.util.ServiceUtils; import com.outsourcing.bottle.util.TextUtil; import com.outsourcing.bottle.util.UICore; public class HomeOldActivity extends BasicActivity implements Callback, OnClickListener { private final int EXEU_GET_TIMELINE = 0; private final int menu_exprofile = 4; private final int menu_exphoto = 3; private final int menu_gainbt = 2; private final int menu_sendbt = 1; private ImageView backView; private ImageButton menuView; private Gallery gallery = null; private TabAdapter textAdapter; private static final String[] TAB_NAMES = { "Exchange", "Bottle", "BTfriend" }; private ListView listView = null; private HomeOldActivity context = null; private Handler handler = null; BottleTimelineInfo bottlelist = null; // ----------------------Gallery用到的常量----------------------------- private int showingIndex = -1; private static final int TIME_OUT_DISPLAY = 300; private int toShowIndex = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = this; handler = new Handler(this); TextUtil.setCtxForGetResString(context); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.home); initLayout(); initLikePopupWindow(); UICore.eventTask(this, this, EXEU_GET_TIMELINE, getString(R.string.init_data), null); } @Override public void execute(int mes, Object obj) { switch (mes) { case EXEU_GET_TIMELINE: getLoginUserInfo(); getTimeLine(); break; default: break; } } /** * 获取用户基本资料 */ private void getLoginUserInfo(){ StringBuffer url = new StringBuffer(UrlConfig.get_loginuser_info); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); ServiceUtils.dout("login url:"+url.toString()); try { String result = HttpUtils.doGet(url.toString()); Gson gson = new Gson(); LoginUserInfo loginUserInfo = gson.fromJson(result, LoginUserInfo.class); LoginUserInfoTable loginUserInfoTable = new LoginUserInfoTable(); if (null != loginUserInfoTable.getLoginUserInfo(AppContext .getInstance().getLogin_uid())) { loginUserInfoTable.deleteLoginUserInfoById(AppContext .getInstance().getLogin_uid()); loginUserInfoTable.saveLoginUserInfo(loginUserInfo .getLoginuser_info(), AppContext.getInstance() .getLogin_uid()); }else { loginUserInfoTable.saveLoginUserInfo(loginUserInfo .getLoginuser_info(), AppContext.getInstance() .getLogin_uid()); } } catch (Exception e) { e.printStackTrace(); } } private void getTimeLine() { StringBuffer url = new StringBuffer(UrlConfig.get_bt_timeline); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&mode=0"); url.append("&count=20"); url.append("&page=1"); url.append("&likescount=10"); url.append("&feedscount=5"); ServiceUtils.dout("timeline url:"+url.toString()); try { String result = HttpUtils.doGet(url.toString()); System.out.println("result:" + result); Gson gson = new Gson(); long firstTime = System.currentTimeMillis(); bottlelist = gson.fromJson(result, BottleTimelineInfo.class); ServiceUtils.dout("wastTime:" + (System.currentTimeMillis() - firstTime)); Message message = Message.obtain(handler); message.what = EXEU_GET_TIMELINE; handler.sendMessage(message); } catch (Exception e) { e.printStackTrace(); } } /** * 喜欢瓶子的操作 * @param btId 瓶子ID * @param likeType 喜欢or不喜欢 <---> 1 or 2 */ private void likeOperation(int btId,int likeType){ StringBuffer url = new StringBuffer(UrlConfig.likeop_bt); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&btid="+btId); url.append("&liketype="+likeType); ServiceUtils.dout("lokeOperation url:"+url.toString()); try { String results = HttpUtils.doGet(url.toString()); ServiceUtils.dout("lokeOperation result:"+results); if (null!=results) { JSONObject obj = new JSONObject(results); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); String errmsg = resultObj.getString("errmsg"); String successmsg = resultObj.getString("successmsg"); if (success == 1) { onToast(successmsg); }else { onToast(errmsg); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void openBottle(int btId){ StringBuffer url = new StringBuffer(UrlConfig.open_bt); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&btid="+btId); ServiceUtils.dout("openBottle url:"+url.toString()); try { String results = HttpUtils.doGet(url.toString()); ServiceUtils.dout("openBottle result:"+results); if (null!=results) { JSONObject obj = new JSONObject(results); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); String errmsg = resultObj.getString("errmsg"); String successmsg = resultObj.getString("successmsg"); if (success == 1) { StringBuffer mSingleBottleUrl = new StringBuffer(UrlConfig.get_bt_timeline); mSingleBottleUrl.append("?mode=4&bit="+btId); ServiceUtils.dout("get open bottle url:"+mSingleBottleUrl.toString()); onToast(successmsg); }else { onToast(errmsg); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void dropBottle(int btId){ StringBuffer url = new StringBuffer(UrlConfig.discard_bt); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&btid="+btId); ServiceUtils.dout("dropBottle url:"+url.toString()); try { String results = HttpUtils.doGet(url.toString()); ServiceUtils.dout("dropBottle result:"+results); if (null!=results) { JSONObject obj = new JSONObject(results); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); String errmsg = resultObj.getString("errmsg"); String successmsg = resultObj.getString("successmsg"); if (success == 1) { onToast(successmsg); }else { onToast(errmsg); } } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void initLayout() { gallery = (Gallery) findViewById(R.id.gallery); gallery.setFocusable(true); gallery.requestFocus(); gallery.requestFocusFromTouch(); gallery.setClickable(true); textAdapter = new TabAdapter(this, Arrays.asList(TAB_NAMES)); gallery.setAdapter(textAdapter); gallery.setSelection(34); gallery.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { TabAdapter adapter = (TabAdapter) parent.getAdapter(); adapter.setSelectedTab(position); System.out .println("onItemClick:" + position % TAB_NAMES.length); switch (position % TAB_NAMES.length) { case 0: break; case 1: break; case 2: break; } } }); gallery.setOnItemSelectedListener(new Gallery.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View arg1, int position, long arg3) { // -------------------------------------------------- toShowIndex = position; final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (showingIndex != toShowIndex) { showingIndex = toShowIndex; System.out.println("position:" + toShowIndex % 3); // 业务逻辑处理 } } }; Thread checkChange = new Thread() { @Override public void run() { int myIndex = toShowIndex; try { sleep(TIME_OUT_DISPLAY); if (myIndex == toShowIndex) { handler.sendEmptyMessage(0); } } catch (InterruptedException e) { e.printStackTrace(); } } }; checkChange.start(); } @Override public void onNothingSelected(AdapterView<?> arg0) { System.out.println("NothingSelected"); } }); listView = (ListView) findViewById(R.id.list_view); SatelliteMenu menu = (SatelliteMenu) findViewById(R.id.menu); List<SatelliteMenuItem> items = new ArrayList<SatelliteMenuItem>(); items.add(new SatelliteMenuItem(menu_exprofile, R.drawable.menu_exprofile)); items.add(new SatelliteMenuItem(menu_exphoto, R.drawable.menu_exphoto)); items.add(new SatelliteMenuItem(menu_gainbt, R.drawable.menu_gainbt)); items.add(new SatelliteMenuItem(menu_sendbt, R.drawable.menu_sendbt)); menu.addItems(items); menu.setOnItemClickedListener(new SateliteClickedListener() { public void eventOccured(int id) { switch (id) { case menu_sendbt: new Thread(){ public void run() { try { Thread.sleep(500); Intent throwIntent = new Intent(HomeOldActivity.this, ChooseBottleActivity.class); throwIntent.putExtra("type", "throw"); startActivity(throwIntent); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; case menu_gainbt: new Thread(){ public void run() { try { Thread.sleep(500); Intent tryIntent = new Intent(HomeOldActivity.this, ChooseBottleActivity.class); tryIntent.putExtra("type", "try"); startActivity(tryIntent); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; case menu_exphoto: break; case menu_exprofile: break; default: break; } } }); backView = (ImageView) findViewById(R.id.topbar_back); backView.setOnClickListener(this); menuView = (ImageButton) findViewById(R.id.topbar_menu); menuView.setOnClickListener(this); } PublicActivityAdapter chatHistoryAdapter; private void setAdapterForThis() { // List<BottleEntry> messages = new ArrayList<BottleEntry>(); // messages.add(new BottleEntry(R.drawable.headphoto, // R.drawable.btn_sendbt)); // messages.add(new BottleEntry(R.drawable.headphoto, // R.drawable.btn_profile)); // messages.add(new BottleEntry(R.drawable.headphoto, // R.drawable.btn_gainbt)); // messages.add(new BottleEntry(R.drawable.headphoto, // R.drawable.bottle_type_1)); // messages.add(new BottleEntry(R.drawable.headphoto, // R.drawable.bottle_type_2)); if (null != bottlelist) { View mheaderView = LayoutInflater.from(this).inflate(R.layout.bottle_list_header, null); RelativeLayout mThrowBottle = (RelativeLayout)mheaderView.findViewById(R.id.rl_tlime_throw_bottle); RelativeLayout mGainBottle = (RelativeLayout)mheaderView.findViewById(R.id.rl_tlime_gain_bottle); RelativeLayout mProfileInfo = (RelativeLayout)mheaderView.findViewById(R.id.rl_tlime_profile_bottle); if (bottlelist.getShowtips().getShow_sendbt_tips()==1) { mThrowBottle.setVisibility(View.VISIBLE); ImageView img_Throw = (ImageView) mheaderView.findViewById(R.id.iv_send_bottle); img_Throw.setOnClickListener(this); Button bt_throw = (Button)mheaderView.findViewById(R.id.bt_bottle_throw_try); bt_throw.setOnClickListener(this); }else { mThrowBottle.setVisibility(View.GONE); } if (bottlelist.getShowtips().getShow_gainbt_tips()==1) { mGainBottle.setVisibility(View.VISIBLE); ImageView img_Gain = (ImageView) mheaderView.findViewById(R.id.iv_gain_bottle); img_Gain.setOnClickListener(this); Button bt_gain = (Button)mheaderView.findViewById(R.id.bt_bottle_gain_try); bt_gain.setOnClickListener(this); }else { mGainBottle.setVisibility(View.GONE); } LoginUserInfoTable loginUserInfoTable = new LoginUserInfoTable(); LoginUserInfoEntry loginUserInfoEntry = loginUserInfoTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid()); if (loginUserInfoEntry.getBasicinfo_fullfill()==0) { mProfileInfo.setVisibility(View.VISIBLE); ImageView img_Profile = (ImageView) mheaderView.findViewById(R.id.iv_profile_info); img_Profile.setOnClickListener(this); TextView tvProfileTips = (TextView)mheaderView.findViewById(R.id.tv_bottle_profile_tips_2); tvProfileTips.setText(loginUserInfoEntry.getBasicinfo_tip()); }else { mProfileInfo.setVisibility(View.GONE); } listView.addHeaderView(mheaderView); // chatHistoryAdapter = new PublicActivityAdapter(this, bottlelist); listView.setAdapter(chatHistoryAdapter); } } @Override public boolean handleMessage(Message msg) { switch (msg.what) { case EXEU_GET_TIMELINE: setAdapterForThis(); break; default: break; } return false; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.topbar_back: finish(); break; case R.id.topbar_menu: Intent intent = new Intent(this, MoreActivity.class); startActivity(intent); break; case R.id.iv_send_bottle: Intent throwIntent = new Intent(HomeOldActivity.this, ChooseBottleActivity.class); throwIntent.putExtra("type", "throw"); startActivity(throwIntent); break; case R.id.iv_gain_bottle: Intent tryIntent = new Intent(HomeOldActivity.this, ChooseBottleActivity.class); tryIntent.putExtra("type", "try"); startActivity(tryIntent); break; case R.id.iv_profile_info: onToast("profile"); break; case R.id.iv_unlike: onToast("unlike"); break; case R.id.iv_like: onToast("like"); break; case R.id.bt_bottle_throw_try: Intent throwIntent2 = new Intent(HomeOldActivity.this, ChooseBottleActivity.class); throwIntent2.putExtra("type", "throw"); startActivity(throwIntent2); break; case R.id.bt_bottle_gain_try: Intent tryIntent2 = new Intent(HomeOldActivity.this, ChooseBottleActivity.class); tryIntent2.putExtra("type", "try"); startActivity(tryIntent2); break; default: break; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if ( keyCode == KeyEvent.KEYCODE_BACK) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getString(R.string.logout_home)); builder.setPositiveButton(getString(R.string.confirm_ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); Process.killProcess(Process.myPid()); System.exit(0); } }); builder.setNegativeButton(getString(R.string.confirm_cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.show(); return true; } else { return super.onKeyDown(keyCode, event); } } private View mLikeView = null; private PopupWindow mLikePopview = null; /**喜欢pop*/ private void initLikePopupWindow() { LayoutInflater mLayoutInflater = LayoutInflater.from(this); mLikeView = mLayoutInflater.inflate(R.layout.pop_bottle_like, null); ImageView iv_unlike = (ImageView)mLikeView.findViewById(R.id.iv_unlike); ImageView iv_like = (ImageView)mLikeView.findViewById(R.id.iv_like); iv_unlike.setOnClickListener(this); iv_like.setOnClickListener(this); mLikePopview = new PopupWindow(mLikeView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); mLikePopview.setBackgroundDrawable(getResources().getDrawable( R.drawable.ic_launcher)); mLikePopview.setOutsideTouchable(true); mLikePopview.update(); mLikePopview.setTouchable(true); mLikePopview.setFocusable(true); // modifyProfile(null); } public void showInfoPopupWindow(View achorView) { if (mLikePopview.isShowing()) { mLikePopview.dismiss(); } else { mLikePopview.showAtLocation(achorView, Gravity.RIGHT, 0, 0); // mLikePopview.showAsDropDown(achorView); } } @Override protected void onResume() { super.onResume(); boolean needRefresh = getIntent().getBooleanExtra("need_refresh", false); if (needRefresh) { //TODO 需要刷新 } } }
Java
package com.outsourcing.bottle.ui; import java.util.ArrayList; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.KeyEvent; import com.outsourcing.bottle.BasicActivity; import com.outsourcing.bottle.R; import com.outsourcing.bottle.ui.fragment.RegisterFragment; import com.viewpagerindicator.CirclePageIndicator; import com.viewpagerindicator.PageIndicator; /** * * @author 06peng * */ public class RegisterSuccessActivity extends BasicActivity { CirclePageFragmentAdapter mAdapter; ViewPager mPager; PageIndicator mIndicator; @Override protected void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); setContentView(R.layout.register_success); initViewpageFragment(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { return true; } else if (keyCode == KeyEvent.KEYCODE_HOME) { return true; } else { return super.onKeyDown(keyCode, event); } } private void initViewpageFragment() { mAdapter = new CirclePageFragmentAdapter(getSupportFragmentManager(), this); Bundle bundle = new Bundle(); bundle.putInt("logo", 1); mAdapter.addFragment("", RegisterFragment.class, bundle); Bundle bundle1 = new Bundle(); bundle1.putInt("logo", 2); mAdapter.addFragment("", RegisterFragment.class, bundle1); Bundle bundle2 = new Bundle(); bundle2.putInt("logo", 3); mAdapter.addFragment("", RegisterFragment.class, bundle2); Bundle bundle3 = new Bundle(); bundle3.putInt("logo", 4); mAdapter.addFragment("", RegisterFragment.class, bundle3); mPager = (ViewPager) findViewById(R.id.pager); mPager.setAdapter(mAdapter); mIndicator = (CirclePageIndicator) findViewById(R.id.indicator); mIndicator.setViewPager(mPager); } public static class CirclePageFragmentAdapter extends FragmentPagerAdapter { private Context mContext; private final ArrayList<FragmentInfo> fragments = new ArrayList<FragmentInfo>(); protected static final class FragmentInfo { @SuppressWarnings("unused") private final String tag; private final Class<?> clss; private final Bundle args; protected FragmentInfo(String _tag, Class<?> _class, Bundle _args) { tag = _tag; clss = _class; args = _args; } } public CirclePageFragmentAdapter(FragmentManager fm, Context context) { super(fm); this.mContext = context; } public void addFragment(String tag, Class<?> clss, Bundle args) { FragmentInfo fragmentInfo = new FragmentInfo(tag, clss, args); fragments.add(fragmentInfo); } @Override public Fragment getItem(int arg0) { FragmentInfo fragmentInfo = fragments.get(arg0); return Fragment.instantiate(mContext, fragmentInfo.clss.getName(), fragmentInfo.args); } @Override public int getCount() { return fragments.size(); } } }
Java
package com.outsourcing.bottle.ui; import java.util.HashMap; import java.util.List; import org.json.JSONObject; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.os.Handler; import android.os.Handler.Callback; import android.os.Message; import android.telephony.TelephonyManager; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.EditorInfo; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.RadioGroup; import android.widget.TextView; import com.google.gson.Gson; import com.outsourcing.bottle.BasicActivity; import com.outsourcing.bottle.R; import com.outsourcing.bottle.db.PlatformAccountTable; import com.outsourcing.bottle.db.StickersPackTable; import com.outsourcing.bottle.domain.LoginUserInfo; import com.outsourcing.bottle.domain.PasterDirConfigEntry; import com.outsourcing.bottle.domain.PlatformAccount; import com.outsourcing.bottle.domain.PlatformBindConfig; import com.outsourcing.bottle.domain.UrlConfig; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.BasicUIEvent; import com.outsourcing.bottle.util.HttpUtils; import com.outsourcing.bottle.util.ServiceUtils; import com.outsourcing.bottle.util.TextUtil; import com.outsourcing.bottle.util.UICore; /** * * @author 06peng * */ public class BindRegisterActivity extends BasicActivity implements BasicUIEvent, OnClickListener, Callback { private final int bind_success = 2; private final int bind_error = 3; private final int bind_register = 4; private ImageView platformView; private TextView nickNameTextView; private TextView platformTextView; private EditText accountView; private EditText emailView; private RadioGroup sexView; private EditText passwordView; private EditText repasswordView; private Button bindView; private Button hasAccountView; private ImageView close; private String platform; private String openuid; private PlatformAccount platformAccount; private String account; private String email; private String password; private String repassword; private int sex; private String deviceId; private Handler handler; @Override protected void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); handler = new Handler(this); setContentView(R.layout.bind_register); try { platform = getIntent().getStringExtra("platform"); openuid = getIntent().getStringExtra("openuid"); PlatformAccountTable pat = new PlatformAccountTable(); if (TextUtil.notEmpty(platform) && TextUtil.notEmpty(openuid)) { platformAccount = pat.getPlatformAccount(PlatformBindConfig.getOpenType(platform), openuid); } initWidget(); TelephonyManager tm = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE); deviceId = tm.getDeviceId(); // LocationThread lt = new LocationThread(basicHandler, locationManager); // lt.start(); //网络定位 networkLocat(); } catch (Exception e) { e.printStackTrace(); } } private void initWidget() { platformView = (ImageView) findViewById(R.id.bind_register_platform); nickNameTextView = (TextView) findViewById(R.id.bind_register_nickname); if (platformAccount != null) { nickNameTextView.setVisibility(View.VISIBLE); nickNameTextView.setText(getString(R.string.login_txt_hello) + "," + platformAccount.getNickName()); } platformTextView = (TextView) findViewById(R.id.bind_register_platform_text); accountView = (EditText) findViewById(R.id.bind_register_account); emailView = (EditText) findViewById(R.id.bind_register_email); bindView = (Button) findViewById(R.id.bind_register_bind); bindView.setOnClickListener(this); hasAccountView = (Button) findViewById(R.id.bind_register_havaaccount); hasAccountView.setOnClickListener(this); sexView = (RadioGroup) findViewById(R.id.bind_register_radioGroup); // maleView = (RadioButton) findViewById(R.id.bind_register_male); // femaleView = (RadioButton) findViewById(R.id.bind_register_female); passwordView = (EditText) findViewById(R.id.bind_register_password); repasswordView = (EditText) findViewById(R.id.bind_register_repassword); repasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) { checkRegister(); } return false; } }); close = (ImageView) findViewById(R.id.close); close.setOnClickListener(this); if (TextUtil.notEmpty(platform)) { hasAccountView.setVisibility(View.VISIBLE); bindView.setVisibility(View.VISIBLE); platformView.setVisibility(View.VISIBLE); nickNameTextView.setVisibility(View.VISIBLE); if (platform.equals(PlatformBindConfig.Sina)) { platformView.setBackgroundResource(R.drawable.ico_weibo); platformTextView.setText(getString(R.string.login_txt_bind_connect) + getString(R.string.login_txt_weibo)); } else if (platform.equals(PlatformBindConfig.Douban)) { platformView.setBackgroundResource(R.drawable.ico_douban); platformTextView.setText(getString(R.string.login_txt_bind_connect) + getString(R.string.login_txt_douban)); } else if (platform.equals(PlatformBindConfig.Tencent)) { platformView.setBackgroundResource(R.drawable.ico_tqq); platformTextView.setText(getString(R.string.login_txt_bind_connect) + getString(R.string.login_txt_tencent)); } else if (platform.equals(PlatformBindConfig.QQ)) { platformView.setBackgroundResource(R.drawable.ico_qq); platformTextView.setText(getString(R.string.login_txt_bind_connect) + getString(R.string.login_txt_qq)); } else if (platform.equals(PlatformBindConfig.Renren)) { platformView.setBackgroundResource(R.drawable.ico_renren); platformTextView.setText(getString(R.string.login_txt_bind_connect) + getString(R.string.login_txt_renren)); } else if (platform.equals(PlatformBindConfig.Twitter)) { platformView.setBackgroundResource(R.drawable.ico_twitter); platformTextView.setText(getString(R.string.login_txt_bind_connect) + getString(R.string.login_txt_twitter)); } else { platformView.setBackgroundResource(R.drawable.ico_facebook); platformTextView.setText(getString(R.string.login_txt_bind_connect) + getString(R.string.login_txt_facebook)); } } else { hasAccountView.setVisibility(View.GONE); bindView.setText(getString(R.string.login_txt_register)); platformView.setVisibility(View.GONE); nickNameTextView.setVisibility(View.GONE); } } @Override public void onClick(View v) { if (v == bindView) { checkRegister(); } else if (v == hasAccountView) { Intent register = new Intent(BindRegisterActivity.this, BindLoginActivity.class); register.putExtra("platform", platform); register.putExtra("openuid", openuid); startActivity(register); } else if (v == close) { finish(); } } @Override public void execute(int mes, Object obj) { switch (mes) { case bind_register: bindRegister(); break; default: break; } } private void checkRegister() { account = accountView.getText().toString().trim(); email = emailView.getText().toString().trim(); int buttonId = sexView.getCheckedRadioButtonId(); password = passwordView.getText().toString().trim(); repassword = repasswordView.getText().toString().trim(); if (account.equals("")) { onToast(getString(R.string.login_txt_register_error_account)); return; } if (email.equals("")) { onToast(getString(R.string.login_txt_reset_error)); return; } else if (!TextUtil.isValidEmail(email)) { onToast(getString(R.string.login_txt_register_error_email)); return; } if (buttonId == -1) { onToast(getString(R.string.login_txt_register_error_sex)); return; } if (password.equals("")) { onToast(getString(R.string.login_txt_error_pwd_tips)); return; } else if (password.length() < 6) { onToast(getString(R.string.login_txt_error_pwd_not_enough)); return; } if (!password.equals(repassword)) { onToast(getString(R.string.login_txt_error_pwd_not_same)); return; } if (sexView.getCheckedRadioButtonId() == R.id.bind_register_male) { sex = 1; } else if (sexView.getCheckedRadioButtonId() == R.id.bind_register_female) { sex = 2; } else { sex = 0; } UICore.eventTask(this, this, bind_register, getString(R.string.init_data), null); } private void bindRegister() { try { String url = UrlConfig.bind_register; HashMap<String, String> paramMaps = new HashMap<String, String>(); paramMaps.put("username", account); paramMaps.put("password", password); paramMaps.put("email", email); paramMaps.put("sex", String.valueOf(sex)); if (platformAccount != null) { paramMaps.put("open_type", String.valueOf(platformAccount.getOpenType())); paramMaps.put("access_token", platformAccount.getAccessToken()); paramMaps.put("token_secret", platformAccount.getTokenSecret()); paramMaps.put("nickname", platformAccount.getNickName()); paramMaps.put("open_uid", platformAccount.getOpenUid()); paramMaps.put("open_sex", String.valueOf(platformAccount.getOpenSex())); paramMaps.put("open_expire", platformAccount.getOpenExpire()); paramMaps.put("open_avatar", platformAccount.getOpenAvatar()); } paramMaps.put("device_token", deviceId); paramMaps.put("device_type", android.os.Build.MODEL); paramMaps.put("device_provider", android.os.Build.PRODUCT); paramMaps.put("device_version", android.os.Build.VERSION.RELEASE); paramMaps.put("lat", String.valueOf(AppContext.getInstance().getLatitude())); paramMaps.put("lng", String.valueOf(AppContext.getInstance().getLongitude())); if (countryIso != null && countryIso.equalsIgnoreCase("cn")) { paramMaps.put("location_mode", "1"); } else { paramMaps.put("location_mode", "0"); } String result = HttpUtils.doPost(this, url, paramMaps); if (result != null) { JSONObject obj = new JSONObject(result); JSONObject resultObj = obj.getJSONObject("results"); int login_uid = resultObj.getInt("login_uid"); if (login_uid != 0) { String login_token = resultObj.getString("login_token"); AppContext.getInstance().setLogin_uid(login_uid); AppContext.getInstance().setLogin_token(login_token); SharedPreferences preferences = getSharedPreferences("Preferences_userinfo", Activity.MODE_APPEND); Editor editor = preferences.edit(); editor.putInt("login_uid", login_uid); editor.putString("login_token", login_token); editor.commit(); try { getLoginUserStickers(); } catch (Exception e) { e.printStackTrace(); } handler.sendEmptyMessage(bind_success); } else { String errmsg = resultObj.getString("errmsg"); Message message = Message.obtain(handler, bind_error, errmsg); handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); } } @Override public boolean handleMessage(Message msg) { switch (msg.what) { case bind_success: // Intent intent = new Intent(BindRegisterActivity.this, HomeActivity.class); // startActivity(intent); Intent intent = new Intent(BindRegisterActivity.this, RegisterSuccessActivity.class); startActivity(intent); BindRegisterActivity.this.finish(); break; case bind_error: onToast((String) msg.obj); break; default: break; } return false; } /** * 获取贴纸目录 */ private void getLoginUserStickers() { StickersPackTable stickPackTable = new StickersPackTable(); StringBuffer url = new StringBuffer(UrlConfig.get_loginuser_info); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); ServiceUtils.dout("login url:" + url.toString()); try { String result = HttpUtils.doGet(url.toString()); Gson gson = new Gson(); LoginUserInfo loginUserInfo = gson.fromJson(result, LoginUserInfo.class); /*********** 保存贴纸目录路径 *********/ List<PasterDirConfigEntry> pasterdir_config = loginUserInfo .getPasterdir_privs_list(); stickPackTable.clearTalbe(); for (PasterDirConfigEntry mPasterDirEntry : pasterdir_config) { stickPackTable.saveStickDir(mPasterDirEntry); } } catch (Exception e) { e.printStackTrace(); } } }
Java
package com.outsourcing.bottle.ui; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import com.outsourcing.bottle.BasicActivity; import com.outsourcing.bottle.R; /** * * @author 06peng * */ public class EditActivity extends BasicActivity implements OnClickListener { private ImageView backView; private TextView titleView; private ImageButton confirmView; private EditText editView; private String tags; @Override protected void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.edit); tags = getIntent().getStringExtra("tags"); backView = (ImageView) findViewById(R.id.topbar_back); backView.setOnClickListener(this); titleView = (TextView) findViewById(R.id.topbar_title); titleView.setText(getString(R.string.bottle_tags)); confirmView = (ImageButton) findViewById(R.id.topbar_confirm); confirmView.setOnClickListener(this); editView = (EditText) findViewById(R.id.edit); editView.setText(tags); } @Override public void onClick(View v) { if (v == backView) { setResult(ThrowBottleSettingActivity.activity_for_result_bottle_tag); finish(); } else if (v == confirmView) { Intent intent = new Intent(this, ThrowBottleSettingActivity.class); intent.putExtra("tags", editView.getText().toString().trim()); setResult(RESULT_OK, intent); finish(); } } }
Java
package com.outsourcing.bottle.ui; import java.util.ArrayList; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Handler.Callback; import android.os.Message; import android.view.LayoutInflater; import android.view.View; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.outsourcing.bottle.R; import com.outsourcing.bottle.adapter.TestCustomAdapter; import com.outsourcing.bottle.util.Utility; import com.outsourcing.bottle.widget.ElasticScrollView; import com.outsourcing.bottle.widget.ElasticScrollView.OnRefreshListener; public class JavaTestActivity extends Activity implements Callback { ListView listView = null; View myWorkPopview = null; ElasticScrollView elasticScrollView = null; Handler handler = null; TestCustomAdapter adapter = null; ArrayList<ArrayList<String>> arrayList = null; private LinearLayout layout; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_test); handler = new Handler(this); // LinearLayout layout = (LinearLayout)findViewById(R.id.layout); elasticScrollView = (ElasticScrollView)findViewById(R.id.flow_refresh_view); // listView = (ListView)findViewById(R.id.list_contact); layout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.list, null); listView = (ListView) layout.findViewById(R.id.list_view); arrayList = new ArrayList<ArrayList<String>>(); for(int i = 0;i<10;i++){ ArrayList<String> arrList = new ArrayList<String>(); for (int j=0;j<5;j++) { arrList.add("子item"+j); } arrayList.add(arrList); } TextView textView = new TextView(this); textView.setText("header"); listView.addHeaderView(textView); adapter = new TestCustomAdapter(this, arrayList); listView.setAdapter(adapter); Utility.setListViewHeightBasedOnChildren(listView); // elasticScrollView.addChild(listView); // elasticScrollView.setonRefreshListener(new OnRefreshListener() { @Override public void onRefresh() { Thread thread = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(3000); Message msg = handler.obtainMessage(0); handler.sendMessage(msg); } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); } }); elasticScrollView.addChild(layout); } int position; public void refreshItem(int position){ this.position = position; // arrayList.remove(position); arrayList.get(position).add("新增"); adapter.notifyDataSetChanged(); } @Override public boolean handleMessage(Message msg) { // TODO Auto-generated method stub switch (msg.what) { case 0: elasticScrollView.onRefreshComplete(); break; default: break; } return false; } }
Java
package com.outsourcing.bottle.ui; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.List; import org.json.JSONObject; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Handler.Callback; import android.os.Message; import android.text.Html; import android.text.TextUtils; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.view.ext.SatelliteMenu; import android.view.ext.SatelliteMenu.SateliteClickedListener; import android.view.ext.SatelliteMenuItem; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import com.google.gson.Gson; import com.outsourcing.bottle.BasicActivity; import com.outsourcing.bottle.R; import com.outsourcing.bottle.adapter.GridLikeAdapter; import com.outsourcing.bottle.db.BottleTypeTable; import com.outsourcing.bottle.db.LoginUserInfoTable; import com.outsourcing.bottle.domain.BottleEntry; import com.outsourcing.bottle.domain.BottleFeedEntry; import com.outsourcing.bottle.domain.BottleInfo; import com.outsourcing.bottle.domain.BottleLikeEntry; import com.outsourcing.bottle.domain.BottleTimelineInfo; import com.outsourcing.bottle.domain.BottleTypeEntry; import com.outsourcing.bottle.domain.LocationEntry; import com.outsourcing.bottle.domain.LoginUserInfoEntry; import com.outsourcing.bottle.domain.UrlConfig; import com.outsourcing.bottle.remoteimage.RemoteImageView; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.BasicUIEvent; import com.outsourcing.bottle.util.HttpUtils; import com.outsourcing.bottle.util.ImageLoader; import com.outsourcing.bottle.util.ServiceUtils; import com.outsourcing.bottle.util.TextUtil; import com.outsourcing.bottle.util.UICore; import com.outsourcing.bottle.widget.CustomGridView; import com.outsourcing.bottle.widget.CustomPopupWindow; import com.outsourcing.bottle.widget.ElasticScrollView; import com.outsourcing.bottle.widget.TryRefreshableView; public class BottleSingleActivity extends BasicActivity implements BasicUIEvent, OnClickListener, Callback { private static final int EXEU_REFRESH_CONTENT = 7; private static final int EXEU_GET_BOTTLE_PRIV_OPERATION = 8; private static final int EXEU_SEND_BOTTLE_PRIV_SUCCESS = 9; private static final int EXEU_SEND_BOTTLE_PRIV_SUCCESS_NOT_ENABLE = 10; private static final int EXEU_SEND_BOTTLE_PRIV_FAILED = 11; private static final int EXEU_LIKE_OPERATION = 12; private static final int EXEU_UNLIKE_OPERATION = 13; private static final int EXEU_LIKE_OPERATION_FAILED = 14; private static final int EXEU_GET_DATA_NOTHING = 17; private static final int EXEU_GET_TIMELINE = 18; private static final int EXEU_GET_TIMELINE_FAILED = 19; private static final int EXEU_OPEN_BOTTLE_OPERATION = 20; private static final int EXEU_OPEN_BOTTLE_SUCCESS = 21; private static final int EXEU_OPEN_BOTTLE_FAILED = 22; private static final int EXEU_GET_DATA_FAILED = 23; private static final int EXEU_DROP_BOTTLE_SUCCESS =24; private static final int EXEU_DROP_BOTTLE_FAILED = 25; private static final int EXEU_DROP_BOTTLE_OPERATION = 26; private final int throw_bottle_init_location = 27; private static final int EXEU_SET_BTPIC_PAINT = 28; View mContentView = null; ElasticScrollView elasticScrollView = null; private ImageLoader imageLoader = null; private TryRefreshableView rv; private LinearLayout ll_content; private ScrollView sv; private Handler handler; private ImageView iv_back; private int btId; private BottleTimelineInfo bottlelist; private List<BottleEntry> mBottleList; private int page = 1; private ImageView iv_menu; private CustomPopupWindow mLikePopview; private BottleTypeEntry entry; private int btTypeId; private boolean isRefresh; private final int menu_uploadphoto = 105; private final int menu_exprofile = 104; private final int menu_exphoto = 103; private final int menu_gainbt = 102; private final int menu_sendbt = 101; private final int user_baseinfo_notfull = 100; // private ImageView messageView; private ImageLoader btConfigLoader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.bottle_single); btId = getIntent().getIntExtra("btid", 0); handler = new Handler(this); imageLoader = new ImageLoader(this, AppContext.BottleTimelineIcon); btConfigLoader = new ImageLoader(this, AppContext.BOTTLE_CONFIG); initLayout(); initLikePopup(); initSateMenu(); UICore.eventTask(this, BottleSingleActivity.this, EXEU_GET_TIMELINE, "", null); } @Override public void execute(int mes, Object obj) { switch (mes) { case EXEU_GET_TIMELINE: getTimeLine(4, btId); break; case EXEU_REFRESH_CONTENT: isRefresh = true; getTimeLine(4, btId); break; case EXEU_GET_BOTTLE_PRIV_OPERATION: getSendSingleBtPriv(btTypeId, btId); break; case EXEU_LIKE_OPERATION: likeOperation(btId, 1); break; case EXEU_UNLIKE_OPERATION: likeOperation(btId, 2); break; case EXEU_OPEN_BOTTLE_OPERATION: openBottle(btId); break; case EXEU_DROP_BOTTLE_OPERATION: dropBottle(btId); break; case throw_bottle_init_location: Object idObj = obj; networkLocat(); Message msg = Message.obtain(handler, throw_bottle_init_location, idObj); handler.sendMessage(msg); break; case EXEU_SET_BTPIC_PAINT: int optype = (Integer)obj; setBtpicPaint(btId, optype); break; default: break; } } /** * 设置瓶子照片涂鸦权限接口 * @param btid 瓶子ID * @param optype 设置是否允许涂鸦。选择项:不允许(0)、允许(1) */ private void setBtpicPaint(int btid,int optype) { this.btId = btid; StringBuffer url = new StringBuffer(UrlConfig.set_btpic_paint); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&btid=" + btid); url.append("&optype=" + optype); ServiceUtils.dout("setBtpicPaint url:" + url.toString()); try { String result = HttpUtils.doGet(url.toString()); ServiceUtils.dout("setBtpicPaint result:" + result); if (result != null) { JSONObject object = new JSONObject(result); JSONObject resultObj = object.getJSONObject("results"); int authok = resultObj.getInt("success"); if (authok == 0) { String errmsg = resultObj.getString("errmsg"); Message msg = Message.obtain(handler, EXEU_GET_TIMELINE_FAILED, errmsg); handler.sendMessage(msg); } else { String successmsg = resultObj.getString("successmsg"); Message msg = Message.obtain(handler, EXEU_SET_BTPIC_PAINT, successmsg); handler.sendMessage(msg); } } } catch (Exception e) { e.printStackTrace(); } } private void initSateMenu() { SatelliteMenu menu = (SatelliteMenu) findViewById(R.id.menu); menu.setVisibility(View.VISIBLE); List<SatelliteMenuItem> items = new ArrayList<SatelliteMenuItem>(); items.add(new SatelliteMenuItem(menu_exprofile, R.drawable.menu_exprofile)); items.add(new SatelliteMenuItem(menu_exphoto, R.drawable.menu_exphoto)); items.add(new SatelliteMenuItem(menu_gainbt, R.drawable.menu_gainbt)); items.add(new SatelliteMenuItem(menu_sendbt, R.drawable.menu_sendbt)); items.add(new SatelliteMenuItem(menu_uploadphoto, R.drawable.menu_uploadphoto)); menu.addItems(items); menu.setOnItemClickedListener(new SateliteClickedListener() { public void eventOccured(int id) { switch (id) { case menu_sendbt: // 扔瓶子 new Thread() { public void run() { try { Thread.sleep(500); Intent throwIntent = new Intent( BottleSingleActivity.this, ChooseBottleActivity.class); throwIntent.putExtra("type", "throw"); startActivity(throwIntent); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; case menu_gainbt: // 捞瓶子 new Thread() { public void run() { try { Thread.sleep(500); Intent tryIntent = new Intent( BottleSingleActivity.this, ChooseBottleActivity.class); tryIntent.putExtra("type", "try"); startActivity(tryIntent); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; case menu_exphoto: // 交换照片 new Thread() { public void run() { try { Thread.sleep(500); Intent exchangeInfoIntent = new Intent( BottleSingleActivity.this, ChooseFriendActivity.class); exchangeInfoIntent .putExtra( "choose_friend_type", AppContext.CHOOSE_FRIEND_EXCHANGE_PHOTO_TYPE); startActivity(exchangeInfoIntent); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; case menu_exprofile: // 交换资料 new Thread() { public void run() { try { Thread.sleep(500); LoginUserInfoTable userTable = new LoginUserInfoTable(); LoginUserInfoEntry userEntry = userTable .getLoginUserInfo(AppContext .getInstance().getLogin_uid()); if (userEntry.getBasicinfo_fullfill() == 0) { handler.sendEmptyMessage(user_baseinfo_notfull); } else { Intent exchangeFileIntent = new Intent( BottleSingleActivity.this, ChooseFriendActivity.class); exchangeFileIntent .putExtra( "choose_friend_type", AppContext.CHOOSE_FRIEND_EXCHANGE_INFO_TYPE); startActivity(exchangeFileIntent); } } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; case menu_uploadphoto: new Thread() { public void run() { try { Thread.sleep(500); Intent intent = new Intent(BottleSingleActivity.this, ExpandEditActivity.class); Bundle extras = new Bundle(); extras.putString("from_type", AppContext.UPLOAD_PHOTO); extras.putInt("albumid", 0); extras.putInt("ouid", AppContext.getInstance().getLogin_uid()); intent.putExtras(extras); startActivity(intent); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; default: break; } } }); } private void dropBottle(int btId) { StringBuffer url = new StringBuffer(UrlConfig.discard_bt); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&btid=" + btId); ServiceUtils.dout("dropBottle url:" + url.toString()); try { String results = HttpUtils.doGet(url.toString()); ServiceUtils.dout("dropBottle result:" + results); if (null != results) { JSONObject obj = new JSONObject(results); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); String errmsg = resultObj.getString("errmsg"); String successmsg = resultObj.getString("successmsg"); if (success == 1) { Message message = handler.obtainMessage( EXEU_DROP_BOTTLE_SUCCESS, successmsg); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_DROP_BOTTLE_FAILED, errmsg); handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); } } private void openBottle(int btId) { StringBuffer url = new StringBuffer(UrlConfig.open_bt); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&btid=" + btId); ServiceUtils.dout("openBottle url:" + url.toString()); try { String results = HttpUtils.doGet(url.toString()); ServiceUtils.dout("openBottle result:" + results); if (null != results) { JSONObject obj = new JSONObject(results); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); String errmsg = resultObj.getString("errmsg"); String successmsg = resultObj.getString("successmsg"); if (success == 1) { StringBuffer mSingleBottleUrl = new StringBuffer( UrlConfig.get_bt_timeline); mSingleBottleUrl.append("?clitype=2"); mSingleBottleUrl.append("&language=" + AppContext.language); mSingleBottleUrl.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); mSingleBottleUrl.append("&login_token=" + AppContext.getInstance().getLogin_token()); mSingleBottleUrl.append("&mode=4&btid=" + btId); ServiceUtils.dout("get open bottle url:" + mSingleBottleUrl.toString()); String singleResult = HttpUtils.doGet(mSingleBottleUrl .toString()); ServiceUtils.dout("get open bottle results :" + singleResult.toString()); Gson gson = new Gson(); BottleTimelineInfo singleBottleInfo = gson.fromJson( singleResult, BottleTimelineInfo.class); mBottleList = singleBottleInfo.getBts_list(); Message message = handler.obtainMessage( EXEU_OPEN_BOTTLE_SUCCESS, successmsg); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_OPEN_BOTTLE_FAILED, errmsg); handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); Message message = handler.obtainMessage( EXEU_GET_DATA_FAILED); handler.sendMessage(message); } } private void getTimeLine(int mode, int btId) { if (AppContext.getInstance().getLogin_uid() == 0 || AppContext.getInstance().getLogin_token() == null) { initConfig(); } StringBuffer url = new StringBuffer(UrlConfig.get_bt_timeline); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&mode=" + mode); url.append("&btid=" + btId); url.append("&count=10"); url.append("&page=" + page); url.append("&likescount=10"); url.append("&feedscount=5"); ServiceUtils.dout("timeline url:" + url.toString()); try { String result = HttpUtils.doGet(url.toString()); if (result == null) { return; } System.out.println("result:" + result); Gson gson = new Gson(); bottlelist = gson.fromJson(result, BottleTimelineInfo.class); if (bottlelist.getResults().getAuthok() == 1) { mBottleList = bottlelist.getBts_list(); Message message = Message.obtain(handler); message.what = EXEU_GET_TIMELINE; handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_GET_TIMELINE_FAILED, bottlelist.getResults() .getErrmsg()); handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } /** 获取扔瓶子的权限 */ public void getSendSingleBtPriv(int btTypeId, int btId) { StringBuffer url = new StringBuffer(UrlConfig.get_sendsinglebt_priv); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&bttypeid=" + btTypeId); ServiceUtils.dout("sendsingleBT private url:" + url.toString()); try { String results = HttpUtils.doGet(url.toString()); ServiceUtils.dout("getsendsinglebt_priv result:" + results); if (null != results) { JSONObject obj = new JSONObject(results); JSONObject resultObj = obj.getJSONObject("results"); int authok = resultObj.getInt("authok"); String errmsg = resultObj.getString("errmsg"); if (authok == 1) { JSONObject privObj = obj.getJSONObject("sendsinglebt_priv"); int enable = privObj.getInt("enable"); String reason = privObj.getString("reason"); if (enable == 1) { Bundle bundle = new Bundle(); bundle.putInt("type", btTypeId); bundle.putInt("btid", btId); bundle.putString("reason", reason); Message message = handler .obtainMessage(EXEU_SEND_BOTTLE_PRIV_SUCCESS); message.setData(bundle); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_SEND_BOTTLE_PRIV_SUCCESS_NOT_ENABLE, reason); handler.sendMessage(message); } } else { Message message = handler.obtainMessage( EXEU_SEND_BOTTLE_PRIV_FAILED, errmsg); handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); } } private void initLayout() { iv_back = (ImageView) findViewById(R.id.topbar_back); iv_back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); iv_menu = (ImageView) findViewById(R.id.topbar_menu); iv_menu.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(BottleSingleActivity.this, HomeActivity.class); intent.putExtra("currentItem", 1); startActivity(intent); finish(); } }); // messageView = (ImageView) findViewById(R.id.notice_message_count); // messageView.setOnClickListener(this); sv = (ScrollView) findViewById(R.id.trymySv); rv = (TryRefreshableView) findViewById(R.id.trymyRV); rv.mfooterView = (View) findViewById(R.id.tryrefresh_footer); rv.sv = sv; ll_content = (LinearLayout) findViewById(R.id.ll_content); // 隐藏mfooterView rv.mfooterViewText = (TextView) findViewById(R.id.tryrefresh_footer_text); rv.mfooterViewText.setVisibility(View.GONE); // 监听是否加载刷新 rv.setRefreshListener(new TryRefreshableView.RefreshListener() { @Override public void onRefresh() { if (rv.mRefreshState == 4) { page = 1; UICore.eventTask(BottleSingleActivity.this, BottleSingleActivity.this, EXEU_REFRESH_CONTENT, null, null); } if (rv.mfooterRefreshState == 4) { rv.finishRefresh(); } } }); } private void setViewVlaue(final BottleEntry message) { ll_content.removeAllViews(); // Item layout View convertView = LayoutInflater.from(this).inflate( R.layout.bottle_list_avatar_item, null); // author img RemoteImageView mAuthorView = (RemoteImageView) convertView .findViewById(R.id.iv_author_photo); // bottle img ImageView mBottleType = (ImageView) convertView .findViewById(R.id.iv_bottle_type); // content layout LinearLayout contentLayout = (LinearLayout) convertView .findViewById(R.id.feed_post_body); View view = LayoutInflater.from(this).inflate( R.layout.bottle_list_detail_item, null); TextView mNickname = (TextView) view.findViewById(R.id.tv_nickname); TextView mLocation = (TextView) view.findViewById(R.id.tv_location); TextView mTag = (TextView) view.findViewById(R.id.tv_tag); TextView mCopyTips = (TextView) view.findViewById(R.id.tv_copy_info); TextView mood = (TextView) view.findViewById(R.id.tv_mood); RelativeLayout mBottleContent = (RelativeLayout) view .findViewById(R.id.rl_bottle_content); TextView mMessage = (TextView) view.findViewById(R.id.tv_doing); // photo LinearLayout mPhotoWrapper = (LinearLayout) view.findViewById(R.id.rl_bottle_content_photo); ImageView mPhotoView = (ImageView) view.findViewById(R.id.photo); Button bt_drawing = (Button)view.findViewById(R.id.bt_drawing); Button bt_allow_draw = (Button)view.findViewById(R.id.bt_allow_draw); LinearLayout mLockedPhotoLayout = (LinearLayout) view .findViewById(R.id.ll_bottle_photo_locked); ImageView mLockedPhoto = (ImageView) view .findViewById(R.id.iv_locked_photo); Button mLockedPhotoTip = (Button) view .findViewById(R.id.bt_locked_photo_tips); // 喜欢popup RelativeLayout mLikeLayout = (RelativeLayout) view .findViewById(R.id.comment_button_like); ImageView mLikeIcon = (ImageView) view .findViewById(R.id.comment_button_like_icon); TextView mLikeText = (TextView) view .findViewById(R.id.comment_button_like_text); // 瓶子没打开的区域 LinearLayout mUnopened_content = (LinearLayout) view .findViewById(R.id.ll_bottle_unopened_content); TextView mOpen_tips = (TextView) view .findViewById(R.id.tv_bottle_open_tips); Button mOpen = (Button) view.findViewById(R.id.bt_bottle_open); Button mDrop = (Button) view.findViewById(R.id.bt_bottle_drop); RelativeLayout mFeedComment = (RelativeLayout) view .findViewById(R.id.feed_comments); Button mComment = (Button) view.findViewById(R.id.bt_bottle_comment); Button mCopy = (Button) view.findViewById(R.id.bt_bottle_copy); Button mForward = (Button) view.findViewById(R.id.bt_bottle_forward); CustomGridView mLikeGrid = (CustomGridView) view .findViewById(R.id.ll_comment_like_grid); View line_grid = (View) view.findViewById(R.id.line_like_grid); View line_bt_comment = (View) view.findViewById(R.id.line_bt_comment); RelativeLayout mfeed_item_comment_more = (RelativeLayout) view .findViewById(R.id.feed_comments_more); TextView comments_ellipsis_text = (TextView) view .findViewById(R.id.comments_ellipsis_text); LinearLayout mfeed_comment_layout = (LinearLayout) view .findViewById(R.id.ll_feed_comment_layout); LinearLayout mOp_layout = (LinearLayout) view .findViewById(R.id.ll_botle_op); LinearLayout mOp_location = (LinearLayout) view .findViewById(R.id.ll_botle_op_location); RemoteImageView mOpAvatar = (RemoteImageView)view.findViewById(R.id.bt_opavatar); TextView mFeedContent = (TextView) view .findViewById(R.id.tv_feed_content); TextView mOplocation = (TextView) view.findViewById(R.id.tv_oplocation); TextView mOpDistance = (TextView) view.findViewById(R.id.tv_distance); contentLayout.addView(view); try { mAuthorView.setDefaultImage(R.drawable.avatar_default_big); mAuthorView.setImageUrl(message.getBt_avatar()); BottleTypeTable btt = new BottleTypeTable(); entry = btt.getBottleType(message.getBttypeid()); btConfigLoader.DisplayImage(entry.getBttype_sjdicon(), mBottleType, R.drawable.bottle_type_1); } catch (Exception e) { e.printStackTrace(); mAuthorView.setImageResource(R.drawable.avatar_default_big); } mAuthorView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int ouid = message.getBt_uid(); Intent spaceIntent = new Intent(BottleSingleActivity.this, UserSpaceActivity.class); spaceIntent.putExtra("ouid", ouid); startActivity(spaceIntent); } }); mBottleType.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { doSendSingleBtPri(message.getBttypeid(), message.getBtid()); } }); String nickName = (message.getBt_nickname() != null && message .getBt_nickname().length() > 0) ? ("<font color='#3F99D8'>" + message.getBt_nickname() + "</font>") : ""; String feed = (message.getBt_feed() != null && message.getBt_feed() .length() > 0) ? ("<font color='#000000'>" + message.getBt_feed() + "</font>") : ""; mNickname.setText(Html.fromHtml(nickName + feed)); if (!TextUtils.isEmpty(message.getBt_location()) && message.getBt_open_drop_show() != 1) { mLocation.setVisibility(View.VISIBLE); String time = (!TextUtils.isEmpty(message.getBt_time())) ? ("<font color='#666666'>"+ "#"+message.getBt_time() + "</font>") : ""; mLocation.setText(Html.fromHtml(time+message.getBt_location())); if (message.getBt_showaddress() == 1) { mLocation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent bottleDetailIntent = new Intent(BottleSingleActivity.this, BottleDetailActivity.class); bottleDetailIntent.putExtra("btid", message.getBtid()); bottleDetailIntent.putExtra("type", 2);// 1,LikeList2,location startActivity(bottleDetailIntent); } }); } } else { mLocation.setVisibility(View.GONE); } if (!TextUtils.isEmpty(message.getBt_tag())) { mTag.setVisibility(View.VISIBLE); String locationTips = "<font color='#DA4A37'>" + TextUtil.R("bottle_txt_location_tips") + "</font>"; mTag.setText(Html.fromHtml(locationTips + TextUtil.htmlEncode(message.getBt_tag()))); } else { mTag.setVisibility(View.GONE); } if (!TextUtils.isEmpty(message.getBt_copy_info())) { mCopyTips.setVisibility(View.VISIBLE); String commentTips = "<font color='#DA4A37'>" + TextUtil.R("bottle_txt_forward_tips") + "</font>"; mCopyTips.setText(Html.fromHtml(commentTips + message.getBt_copy_info())); } else { mCopyTips.setVisibility(View.GONE); } if (!TextUtils.isEmpty(message.getBt_doing())) { mood.setVisibility(View.VISIBLE); String moodTips = "<font color='#DA4A37'>" + TextUtil.R("bottle_txt_mood_tips") + "</font>"; mood.setText(Html.fromHtml(moodTips + TextUtil.htmlEncode(message.getBt_doing()))); } else { mood.setVisibility(View.GONE); } if (!TextUtils.isEmpty(message.getBt_content())) { String messageTips = "<font color='#DA4A37'>" + TextUtil.R("bottle_txt_copy_tips") + "</font>"; mMessage.setVisibility(View.VISIBLE); mMessage.setText(Html.fromHtml(messageTips + TextUtil.htmlEncode(message.getBt_content()))); } else { mMessage.setVisibility(View.GONE); } if (!TextUtils.isEmpty(message.getBt_opfeed())) { mOp_layout.setVisibility(View.VISIBLE); if (message.getBt_open_drop_show() != 1) { mOp_layout .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent bottleDetailIntent = new Intent(BottleSingleActivity.this, BottleDetailActivity.class); bottleDetailIntent.putExtra("btid", message.getBtid()); bottleDetailIntent.putExtra("type", 2);// 1,LikeList2,location startActivity(bottleDetailIntent); } }); } try { mOpAvatar.setDefaultImage(R.drawable.avatar_default_small); mOpAvatar.setImageUrl(message.getBt_opavatar()); mOpAvatar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent spaceIntent = new Intent(BottleSingleActivity.this, UserSpaceActivity.class); spaceIntent.putExtra("ouid", message.getBt_opuid()); startActivity(spaceIntent); } }); } catch (Exception e) { e.printStackTrace(); mOpAvatar.setImageResource(R.drawable.avatar_default_small); } String onickName = (!TextUtils.isEmpty(message.getBt_opnickname())) ? ("<font color='#3F99D8'>" + message.getBt_opnickname() + "</font>") : ""; String otime = (!TextUtils.isEmpty(message.getBt_optime())) ? ( "#" + message.getBt_optime()) : ""; mFeedContent.setText(Html.fromHtml(onickName + TextUtil.htmlEncode(message.getBt_opfeed()))); if (!TextUtils.isEmpty(message.getBt_oplocation())) { mOp_location.setVisibility(View.VISIBLE); mOplocation.setText(otime + message.getBt_oplocation()); mOpDistance.setText(TextUtil.R("bottle_txt_comment_distance")+" "+message.getBt_opdistance()); } else { mOp_location.setVisibility(View.GONE); } } else { mOp_layout.setVisibility(View.GONE); } if (message.getBt_open_drop_show() == 1) { mood.setVisibility(View.GONE); mMessage.setVisibility(View.GONE); mLikeLayout.setVisibility(View.GONE); mBottleContent.setVisibility(View.GONE); mUnopened_content.setVisibility(View.VISIBLE); mOpen_tips.setText(TextUtil.R("bottle_txt_open_tips") + " " + message.getBt_nickname()); mOpen.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { doOpenBottle(message.getBtid()); } }); mDrop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { doDropBottle(message.getBtid()); } }); } else { if (message.getBt_showaddress() == 1) { mTag.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent bottleDetailIntent = new Intent(BottleSingleActivity.this, BottleDetailActivity.class); bottleDetailIntent.putExtra("btid", message.getBtid()); bottleDetailIntent.putExtra("type", 2);// 1,LikeList2,location startActivity(bottleDetailIntent); } }); } mood.setVisibility(View.VISIBLE); mMessage.setVisibility(View.VISIBLE); mLikeLayout.setVisibility(View.VISIBLE); mUnopened_content.setVisibility(View.GONE); mBottleContent.setVisibility(View.VISIBLE); if (!TextUtils.isEmpty(message.getBt_smallpic())) { if (message.getBt_pic_locked() == 0) { mPhotoWrapper.setVisibility(View.VISIBLE); mPhotoView.setVisibility(View.VISIBLE); mLockedPhotoLayout.setVisibility(View.GONE); try { imageLoader.DisplayImage(message.getBt_smallpic(), mPhotoView, R.drawable.album_nophoto); } catch (Exception e) { e.printStackTrace(); mPhotoView.setImageResource(R.drawable.album_nophoto); } mPhotoView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { byte[] tempBytes = null; try { String filename = ServiceUtils.convertUrlToFileName(message.getBt_smallpic()); tempBytes = ServiceUtils.readStream(new FileInputStream(new File( android.os.Environment.getExternalStorageDirectory() + "/" + AppContext.BottleTimelineIcon + "/" + filename))); } catch (Exception e) { e.printStackTrace(); } Intent bigPicIntent = new Intent(BottleSingleActivity.this, PhotoDetailActivity.class); bigPicIntent.putExtra("pic_big", message.getBt_bigpic()); bigPicIntent.putExtra("thumbnail", tempBytes); startActivity(bigPicIntent); } }); if (message.getBt_allow_tuya() == 1) { bt_drawing.setVisibility(View.VISIBLE); bt_drawing.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int btId = message.getBtid(); byte[] tempBytes = null; try { String filename = ServiceUtils.convertUrlToFileName(message.getBt_smallpic()); tempBytes = ServiceUtils.readStream(new FileInputStream(new File( android.os.Environment.getExternalStorageDirectory() + "/" + AppContext.BottleTimelineIcon + "/" + filename))); } catch (Exception e) { e.printStackTrace(); } Intent bigPicIntent = new Intent(BottleSingleActivity.this, PhotoDetailActivity.class); bigPicIntent.putExtra("pic_big", message.getBt_bigpic()); bigPicIntent.putExtra("thumbnail", tempBytes); bigPicIntent.putExtra("paintType", AppContext.PAINT_BT); bigPicIntent.putExtra("btid", message.getBtid()); bigPicIntent.putExtra("return_type",BottleSingleActivity.class.getSimpleName()); bigPicIntent.putExtra("isToDraw", true); startActivity(bigPicIntent); } }); }else { bt_drawing.setVisibility(View.GONE); } if (message.getBt_enable_tuya()== 0) { bt_allow_draw.setVisibility(View.GONE); }else { bt_allow_draw.setVisibility(View.VISIBLE); if (message.getBt_enable_tuya()== 1) { bt_allow_draw.setBackgroundResource(R.drawable.btn_red_try); bt_allow_draw.setText(TextUtil.R("bottle_txt_allow_draw")); bt_allow_draw.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { doPicPaint(message.getBtid(), 1); } }); }else { bt_allow_draw.setBackgroundResource(R.drawable.btn_gray_try); bt_allow_draw.setText(TextUtil.R("bottle_txt_not_allow_draw")); bt_allow_draw.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { doPicPaint(message.getBtid(), 0); } }); } } } else { mLockedPhotoLayout.setVisibility(View.VISIBLE); mPhotoWrapper.setVisibility(View.GONE); mPhotoView.setVisibility(View.GONE); mLockedPhotoTip .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent unLockPhotoIntent = new Intent(BottleSingleActivity.this, ExpandEditActivity.class); Bundle unLockBundle = new Bundle(); unLockBundle.putString("from_type", AppContext.REPLY_BT); unLockBundle.putString("return_type", BottleSingleActivity.class.getSimpleName()); unLockBundle.putInt("bttype_id", message.getBtid()); unLockPhotoIntent.putExtras(unLockBundle); startActivityForResult(unLockPhotoIntent, 0); } }); } } else { mPhotoWrapper.setVisibility(View.GONE); mPhotoView.setVisibility(View.GONE); mLockedPhotoLayout.setVisibility(View.GONE); } if (null != message.getBtlikes_list()) { mLikeLayout.setVisibility(View.VISIBLE); if (message.getBt_liked() == 0) { mLikeText.setTextColor(BottleSingleActivity.this.getResources().getColor(R.color.gray)); mLikeLayout.setBackgroundDrawable(BottleSingleActivity.this.getResources().getDrawable(R.drawable.photo_pill)); mLikeIcon.setBackgroundDrawable(BottleSingleActivity.this.getResources().getDrawable(R.drawable.like_gray2)); // .setBackgroundResource(R.drawable.like_gray2); } else if (message.getBt_liked() == 1) { mLikeText.setTextColor(BottleSingleActivity.this.getResources().getColor(R.color.gray)); mLikeLayout.setBackgroundDrawable(BottleSingleActivity.this.getResources().getDrawable(R.drawable.photo_pill)); mLikeIcon.setBackgroundDrawable(BottleSingleActivity.this.getResources().getDrawable(R.drawable.like_red2)); // .setBackgroundResource(R.drawable.like_red2); } else if (message.getBt_liked() == 2) { mLikeText.setTextColor(BottleSingleActivity.this.getResources().getColor(R.color.gray)); mLikeLayout.setBackgroundDrawable(BottleSingleActivity.this.getResources().getDrawable(R.drawable.photo_pill)); mLikeIcon.setBackgroundDrawable(BottleSingleActivity.this.getResources().getDrawable(R.drawable.like_black2)); // .setBackgroundResource(R.drawable.like_black2); } if (message.getBt_like_enable() == 1) { mLikeText.setTextColor(BottleSingleActivity.this.getResources().getColor(R.color.gray)); mLikeLayout.setBackgroundDrawable(BottleSingleActivity.this.getResources().getDrawable(R.drawable.photo_pill)); mLikeLayout .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showInfoPopupWindow(v, message.getBtid()); } }); } else { mLikeText.setTextColor(BottleSingleActivity.this.getResources().getColor(R.color.white)); mLikeLayout.setBackgroundDrawable(BottleSingleActivity.this.getResources().getDrawable(R.drawable.photo_pill_dark)); } if (message.getBtlikes_count() == 0) { mLikeText.setVisibility(View.GONE); } else { mLikeText.setVisibility(View.VISIBLE); mLikeText.setText(message.getBtlikes_count() + ""); } } else { mLikeLayout.setVisibility(View.GONE); } mComment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent commentIntent = new Intent(BottleSingleActivity.this, ExpandEditActivity.class); Bundle commentBundle = new Bundle(); commentBundle.putString("from_type", AppContext.REPLY_BT); commentBundle.putString("return_type", BottleSingleActivity.class.getSimpleName()); commentBundle.putInt("bttype_id", message.getBtid()); commentIntent.putExtras(commentBundle); startActivityForResult(commentIntent, 0); } }); if (message.getBt_copy_enable() == 1) { mCopy.setVisibility(View.VISIBLE); mCopy.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent copyIntent = new Intent(BottleSingleActivity.this, ExpandEditActivity.class); Bundle copyBundle = new Bundle(); copyBundle.putString("from_type", AppContext.COPYMANUAL_BT); copyBundle.putInt("bttype_id", message.getBtid()); copyBundle.putString("return_type", BottleSingleActivity.class.getSimpleName()); copyIntent.putExtras(copyBundle); startActivityForResult(copyIntent, 0); } }); } else { mCopy.setVisibility(View.INVISIBLE); } if (message.getBt_allow_spread() == 1) { mForward.setVisibility(View.VISIBLE); mForward.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final Context dialogContext = new ContextThemeWrapper(BottleSingleActivity.this, android.R.style.Theme_Light); int btId = message.getBtid(); String[] choices = new String[2]; choices[0] = BottleSingleActivity.this.getString(R.string.bottle_txt_forward_to_friend); choices[1] = BottleSingleActivity.this.getString(R.string.bottle_txt_forward_to_platform); final ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (which == 0) { Intent forwardIntent = new Intent(BottleSingleActivity.this, ChooseFriendActivity.class); Bundle forwardBundle = new Bundle(); forwardBundle.putInt("choose_friend_type", AppContext.CHOOSE_FRIEND_FORWARD_BOTTLE_TYPE); forwardBundle.putInt("bttype_id", message.getBtid()); forwardBundle.putString("return_type", BottleSingleActivity.class.getSimpleName()); forwardIntent.putExtras(forwardBundle); startActivity(forwardIntent); } else { Intent forwardIntent = new Intent(BottleSingleActivity.this, ExpandEditActivity.class); Bundle forwardBundle = new Bundle(); forwardBundle.putString("from_type", AppContext.TRANSMIT_BT); forwardBundle.putString("return_type", BottleSingleActivity.class.getSimpleName()); forwardBundle.putInt("bttype_id", message.getBtid()); forwardIntent.putExtras(forwardBundle); startActivityForResult(forwardIntent, 0); } } }); builder.create().show(); } }); } else { mForward.setVisibility(View.INVISIBLE); } if (null != message.getBtlikes_list() && message.getBtlikes_list().size() > 0) { mLikeGrid.setVisibility(View.VISIBLE); line_grid.setVisibility(View.VISIBLE); final GridLikeAdapter gridAdapter = new GridLikeAdapter( BottleSingleActivity.this, message.getBtlikes_list(), mLikeGrid); mLikeGrid.setAdapter(gridAdapter); mLikeGrid .setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { BottleLikeEntry btLike = (BottleLikeEntry) gridAdapter.getItem(position); Intent spaceIntent = new Intent(BottleSingleActivity.this, UserSpaceActivity.class); spaceIntent.putExtra("ouid", btLike.getLike_uid()); startActivity(spaceIntent); } }); } else { mLikeGrid.setVisibility(View.GONE); line_grid.setVisibility(View.GONE); } if (message.getBtfeeds_count() > 0) { line_bt_comment.setVisibility(View.VISIBLE); mfeed_item_comment_more.setVisibility(View.VISIBLE); mfeed_item_comment_more .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent bottleDetailIntent = new Intent(BottleSingleActivity.this, BottleDetailActivity.class); bottleDetailIntent.putExtra("btid", message.getBtid()); bottleDetailIntent.putExtra("type", 1);// 2,location startActivity(bottleDetailIntent); } }); comments_ellipsis_text.setText(message .getBtfeeds_count()+" " + TextUtil.R("bottle_txt_comment_more")); } else { mfeed_item_comment_more.setVisibility(View.GONE); line_bt_comment.setVisibility(View.INVISIBLE); } if (message.getBtfeeds_count() > 0) { mfeed_comment_layout.setVisibility(View.VISIBLE); mfeed_comment_layout.removeAllViews(); for (int i = 0; i < message.getBtfeeds_list().size(); i++) { final BottleFeedEntry btFeedEntry = message.getBtfeeds_list().get(i); View mCommentView = LayoutInflater.from(BottleSingleActivity.this).inflate( R.layout.feed_comments_item, null); if (i == (message.getBtfeeds_list().size()-1)) { View feed_avatar = (View) mCommentView .findViewById(R.id.line_bttimeline_feed); feed_avatar.setVisibility(View.INVISIBLE); } mCommentView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent bottleDetailIntent = new Intent(BottleSingleActivity.this, BottleDetailActivity.class); bottleDetailIntent.putExtra("btid", message.getBtid()); bottleDetailIntent.putExtra("type", 1);// 1,LikeList2,location startActivity(bottleDetailIntent); } }); RemoteImageView feed_avatar = (RemoteImageView) mCommentView .findViewById(R.id.comment_profile_photo); if (!TextUtils.isEmpty(btFeedEntry.getFeed_avatar())) { try { feed_avatar.setDefaultImage(R.drawable.avatar_default_small); feed_avatar.setImageUrl(btFeedEntry.getFeed_avatar()); feed_avatar .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent spaceIntent = new Intent(BottleSingleActivity.this, UserSpaceActivity.class); spaceIntent.putExtra("ouid", btFeedEntry.getFeed_uid()); startActivity(spaceIntent); } }); } catch (Exception e) { e.printStackTrace(); feed_avatar.setImageResource(R.drawable.avatar_default_small); } } // ImageView comment_link = (ImageView) mCommentView // .findViewById(R.id.iv_feed_comment_white); // if (btFeedEntry.getFeed_type() == 0) { // comment_link.setVisibility(View.VISIBLE); // } else { // comment_link.setVisibility(View.GONE); // } TextView comment_nickname = (TextView) mCommentView .findViewById(R.id.tv_feed_comment_nickname); String feed_name = null; if ((!TextUtils.isEmpty(btFeedEntry.getFeed_nickname()))|| (!TextUtils.isEmpty(btFeedEntry.getFeed_content()))) { if (btFeedEntry.getFeed_uid() != AppContext.getInstance() .getLogin_uid()) { feed_name = "<font color='#DA4A37'>" + btFeedEntry.getFeed_nickname() + "</font>"; } else { feed_name = "<font color='#3F99D8'>" + btFeedEntry.getFeed_nickname() + "</font>"; } String feed_content = btFeedEntry.getFeed_isnew()==1?("<font color='#DA4A37'>" + TextUtil.htmlEncode(btFeedEntry.getFeed_content()) + "</font>"):TextUtil.htmlEncode(btFeedEntry.getFeed_content()); try { comment_nickname.setText(Html.fromHtml(feed_name + " " + feed_content)); } catch (Exception e) { e.printStackTrace(); } } TextView comment_time = (TextView) mCommentView .findViewById(R.id.tv_feed_comment_time); if ((!TextUtils.isEmpty(btFeedEntry.getFeed_time())) || (!TextUtils.isEmpty(btFeedEntry.getFeed_location()))) { String timeComent = (!TextUtils.isEmpty(btFeedEntry.getFeed_time())) ? ("#" + btFeedEntry.getFeed_time()): ""; String location = (!TextUtils.isEmpty(btFeedEntry.getFeed_location().trim())) ? ("@" + btFeedEntry.getFeed_location()): ""; comment_time.setText(timeComent+" "+location); if (!TextUtils.isEmpty(location)) { comment_time.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final Context dialogContext = new ContextThemeWrapper(BottleSingleActivity.this, android.R.style.Theme_Light); String[] choices = new String[1]; choices[0] = BottleSingleActivity.this.getString(R.string.bottle_txt_check_location); final ListAdapter adapter = new ArrayAdapter<String>( dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems( adapter, -1, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { dialog.dismiss(); if (which == 0) { Intent intent = new Intent(BottleSingleActivity.this,MapViewActivity.class); intent.putExtra( "longitude",btFeedEntry.getFeed_lng()); intent.putExtra( "latidute",btFeedEntry.getFeed_lat()); intent.putExtra( "location",btFeedEntry.getFeed_location()); startActivity(intent); } } }); builder.create().show(); } }); } } RelativeLayout rl_bottle_comment_photo = (RelativeLayout)mCommentView.findViewById(R.id.rl_bottle_comment_photo); if (!TextUtils.isEmpty(btFeedEntry.getFeed_commentpic())) { rl_bottle_comment_photo.setVisibility(View.VISIBLE); ImageView feed_commentpic = (ImageView)mCommentView.findViewById(R.id.feed_comment_pic); try { imageLoader.DisplayImage(btFeedEntry.getFeed_commentpic(),feed_commentpic, R.drawable.album_nophoto); feed_commentpic .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!TextUtils.isEmpty(btFeedEntry .getFeed_commentpic_tuya())) { showCommentPicFeedDialog(btFeedEntry); } else { byte[] tempBytes = null; try { String filename = ServiceUtils .convertUrlToFileName(btFeedEntry .getFeed_commentpic()); tempBytes = ServiceUtils .readStream(new FileInputStream( new File( android.os.Environment .getExternalStorageDirectory() + "/" + AppContext.BottleTimelineIcon + "/" + filename))); } catch (Exception e) { e.printStackTrace(); } Intent bigPicIntent = new Intent(BottleSingleActivity.this, PhotoDetailActivity.class); bigPicIntent.putExtra("pic_big",btFeedEntry.getFeed_commentpic_big()); bigPicIntent.putExtra("thumbnail", tempBytes); startActivity(bigPicIntent); } } }); } catch (Exception e) { e.printStackTrace(); feed_commentpic.setImageResource(R.drawable.album_nophoto); } }else { rl_bottle_comment_photo.setVisibility(View.GONE); } TextView tv_feed_replycomment = (TextView)mCommentView.findViewById(R.id.tv_feed_replycomment); if (!TextUtils.isEmpty(btFeedEntry.getFeed_replycomment())) { tv_feed_replycomment.setVisibility(View.VISIBLE); tv_feed_replycomment.setText(btFeedEntry.getFeed_replycomment()); } else { tv_feed_replycomment.setVisibility(View.GONE); } mfeed_comment_layout.addView(mCommentView); } } else { mfeed_comment_layout.setVisibility(View.GONE); } } ll_content.addView(convertView); } public void doDropBottle(int btId) { this.btId = btId; UICore.eventTask(this, this, EXEU_DROP_BOTTLE_OPERATION, "", null); } public void doSendSingleBtPri(int btTypeId, int btId) { this.btId = btId; this.btTypeId = btTypeId; UICore.eventTask(this, this, EXEU_GET_BOTTLE_PRIV_OPERATION, "", null); } private void initLikePopup() { LayoutInflater mLayoutInflater = LayoutInflater.from(this); View mLikeView = mLayoutInflater.inflate(R.layout.pop_bottle_like, null); ImageView iv_unlike = (ImageView) mLikeView .findViewById(R.id.iv_unlike); ImageView iv_like = (ImageView) mLikeView.findViewById(R.id.iv_like); iv_unlike.setOnClickListener(this); iv_like.setOnClickListener(this); mLikePopview = new CustomPopupWindow(mLikeView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); mLikePopview.setBackgroundDrawable(getResources().getDrawable( R.drawable.ic_launcher)); mLikePopview.setOutsideTouchable(true); mLikePopview.update(); mLikePopview.setTouchable(true); mLikePopview.setFocusable(true); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.iv_unlike:// 不喜欢 mLikePopview.dismiss(); UICore.eventTask(this, this, EXEU_UNLIKE_OPERATION, "", null); break; case R.id.iv_like:// 喜欢 mLikePopview.dismiss(); UICore.eventTask(this, this, EXEU_LIKE_OPERATION, "", null); break; case R.id.topbar_back: finish(); break; case R.id.rl_button_like: mLikePopview.showAsDropDown(v, 50, -40); break; case R.id.bt_bottle_comment: Intent commentIntent = new Intent(this, ExpandEditActivity.class); Bundle commentBundle = new Bundle(); commentBundle.putString("from_type", AppContext.REPLY_BT); commentBundle.putInt("bttype_id", btId); commentIntent.putExtras(commentBundle); startActivityForResult(commentIntent, 0); break; case R.id.bt_bottle_copy: Intent copyIntent = new Intent(this, ExpandEditActivity.class); Bundle copyBundle = new Bundle(); copyBundle.putString("from_type", AppContext.COPYMANUAL_BT); copyBundle.putInt("bttype_id", btId); copyIntent.putExtras(copyBundle); startActivityForResult(copyIntent, 0); break; case R.id.bt_bottle_forward: Intent forwardIntent = new Intent(this, ExpandEditActivity.class); Bundle forwardBundle = new Bundle(); forwardBundle.putString("from_type", AppContext.TRANSMIT_BT); forwardBundle.putInt("bttype_id", btId); forwardIntent.putExtras(forwardBundle); startActivityForResult(forwardIntent, 0); break; // case R.id.notice_message_count: // doMessageAction(); // break; default: break; } } public void doMessageAction() { final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light); String[] choices = new String[2]; choices[0] = getString(R.string.bottle_txt_notice_list); choices[1] = getString(R.string.bottle_txt_message_list); final ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (which == 0) { Intent intent = new Intent(BottleSingleActivity.this, NoticeListActivity.class); startActivity(intent); } else { Intent intent = new Intent(BottleSingleActivity.this, MessageListActivity.class); startActivity(intent); } } }); builder.create().show(); } /** * 喜欢瓶子的操作 * * @param btId * 瓶子ID * @param likeType * 喜欢or不喜欢 <---> 1 or 2 */ private void likeOperation(int btId, int likeType) { StringBuffer url = new StringBuffer(UrlConfig.likeop_bt); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&btid=" + btId); url.append("&liketype=" + likeType); ServiceUtils.dout("likeOperation url:" + url.toString()); try { String results = HttpUtils.doGet(url.toString()); ServiceUtils.dout("likeOperation result:" + results); if (null != results) { JSONObject obj = new JSONObject(results); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); String errmsg = resultObj.getString("errmsg"); String successmsg = resultObj.getString("successmsg"); Message message = null; if (success == 1) { switch (likeType) { case 1: message = handler.obtainMessage(EXEU_LIKE_OPERATION, successmsg); handler.sendMessage(message); break; case 2: message = handler.obtainMessage(EXEU_UNLIKE_OPERATION, successmsg); handler.sendMessage(message); break; default: break; } } else { message = handler.obtainMessage(EXEU_LIKE_OPERATION_FAILED, errmsg); handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); } } public void doPicPaint(int btid,int optype){ this.btId = btid; UICore.eventTask(this, this, EXEU_SET_BTPIC_PAINT, "", optype); } private void getBottleInfo(int btId) { StringBuffer url = new StringBuffer(UrlConfig.get_btinfo); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&btid=" + btId); ServiceUtils.dout("getBottleInfo url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); if (results == null) { return; } ServiceUtils.dout("getBottleInfo results:" + results.toString()); Gson gson = new Gson(); BottleInfo bottleInfo = gson.fromJson(results, BottleInfo.class); if (bottleInfo.getResults().getAuthok() == 1) { // bottleInfoEntry = bottleInfo.getBtinfo(); // Message message = // handler.obtainMessage(EXEU_GET_BOTTLE_INFO,bottleInfoEntry); // handler.sendMessage(message); } else { // Message message = handler.obtainMessage(EXEU_GET_DATA_ERROR, // bottleInfo.getResults().getErrmsg()); // handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } protected void onResume() { super.onResume(); if (AppContext.getInstance().isFromBottleSingle()) { AppContext.getInstance().setFromBottleSingle(false); page = 1; UICore.eventTask(this, BottleSingleActivity.this, EXEU_GET_TIMELINE, "", null); } }; @Override protected void onActivityResult(int arg0, int arg1, Intent intent) { super.onActivityResult(arg0, arg1, intent); if (null != intent) { if (intent.getBooleanExtra("need_refresh", false)) { page = 1; UICore.eventTask(this, BottleSingleActivity.this, EXEU_GET_TIMELINE, "", null); } } } private void showCommentPicFeedDialog(final BottleFeedEntry message) { String[] choices = new String[]{TextUtil.R("bottle_txt_feed_comment_pic"),TextUtil.R("bottle_txt_feed_comment_tuya")}; final Context dialogContext = new ContextThemeWrapper(BottleSingleActivity.this, android.R.style.Theme_Light); final ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (which == 0) { byte[] tempBytes = null; try { String filename = ServiceUtils.convertUrlToFileName(message.getFeed_commentpic()); tempBytes = ServiceUtils.readStream(new FileInputStream(new File( android.os.Environment.getExternalStorageDirectory() + "/" + AppContext.BottleTimelineIcon + "/" + filename))); } catch (Exception e) { e.printStackTrace(); } Intent bigPicIntent = new Intent(BottleSingleActivity.this, PhotoDetailActivity.class); bigPicIntent.putExtra("pic_big", message.getFeed_commentpic_big()); bigPicIntent.putExtra("thumbnail", tempBytes); startActivity(bigPicIntent); } else { Intent bigPicIntent = new Intent(BottleSingleActivity.this, PhotoDetailActivity.class); bigPicIntent.putExtra("pic_big", message.getFeed_commentpic_tuya()); startActivity(bigPicIntent); } } }); builder.create().show(); } public void doOpenBottle(int btId) { this.btId = btId; UICore.eventTask(this, this, EXEU_OPEN_BOTTLE_OPERATION, "", null); } @Override public boolean handleMessage(Message msg) { switch (msg.what) { case EXEU_GET_TIMELINE: setViewVlaue(mBottleList.get(0)); if (isRefresh) { rv.finishRefresh(); } break; case EXEU_GET_TIMELINE_FAILED: onToast((String) msg.obj); break; case EXEU_OPEN_BOTTLE_FAILED: onToast((String) msg.obj); break; case EXEU_GET_DATA_FAILED: onToast(TextUtil.R("no_more_data")); break; case EXEU_OPEN_BOTTLE_SUCCESS: setViewVlaue(mBottleList.get(0)); break; case EXEU_DROP_BOTTLE_SUCCESS: ll_content.removeAllViews(); onToast((String) msg.obj); break; case EXEU_DROP_BOTTLE_FAILED: onToast((String) msg.obj); break; case EXEU_SEND_BOTTLE_PRIV_SUCCESS: final Bundle bundle = msg.getData(); try { BottleTypeTable table = new BottleTypeTable(); BottleTypeEntry bottleEntry = table.getBottleType(bundle.getInt("type")); int locationSelect = bottleEntry.getBttype_location_select(); String[] choices = new String[2]; if (locationSelect > 1) { choices[0] = getString(R.string.choose_location_here_throw); choices[1] = getString(R.string.choose_location_search_throw); } else { choices = new String[1]; choices[0] = getString(R.string.choose_location_here_throw); } chooseAction(choices, locationSelect , bundle.getInt("type")); } catch (Exception e) { e.printStackTrace(); } break; case EXEU_SEND_BOTTLE_PRIV_SUCCESS_NOT_ENABLE: onToast((String) msg.obj); break; case EXEU_SEND_BOTTLE_PRIV_FAILED: onToast((String) msg.obj); break; case EXEU_LIKE_OPERATION_FAILED: onToast((String) msg.obj); break; case EXEU_LIKE_OPERATION: UICore.eventTask(this, BottleSingleActivity.this, EXEU_REFRESH_CONTENT, "", null); break; case EXEU_UNLIKE_OPERATION: UICore.eventTask(this, BottleSingleActivity.this, EXEU_REFRESH_CONTENT, "", null); break; case EXEU_GET_DATA_NOTHING: rv.mfooterViewText.setVisibility(View.INVISIBLE); onToast(TextUtil.R("no_more_data")); rv.finishRefresh(); break; case throw_bottle_init_location: try { Object[] objs = (Object[]) msg.obj; int bottleid = Integer.parseInt(objs[0].toString()); LocationEntry location = (LocationEntry) objs[1]; Intent intent2 = new Intent(this, ThrowBottleSettingActivity.class); intent2.putExtra("bttype_id", bottleid); intent2.putExtra("bt_geo_lng", location.getLongitude()); intent2.putExtra("bt_geo_lat", location.getLatitude()); startActivity(intent2); } catch (Exception e) { e.printStackTrace(); } break; case EXEU_SET_BTPIC_PAINT: onToast((String) msg.obj); UICore.eventTask(this, BottleSingleActivity.this, EXEU_REFRESH_CONTENT, "", null); break; default: break; } return false; } public void showInfoPopupWindow(View achorView, int btId) { this.btId = btId; if (mLikePopview.isShowing()) { mLikePopview.dismiss(); } else { // mLikePopview.showAtLocation(achorView, Gravity.RIGHT, 0, 0); mLikePopview.showAsDropDown(achorView, -150, -50); } } private void chooseAction(String[] choices, final int locationSelected, final int bottleId) { final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light); final ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (which == 0) { Intent intent2 = new Intent(BottleSingleActivity.this, ThrowBottleSettingActivity.class); intent2.putExtra("bttype_id", bottleId); intent2.putExtra("bt_geo_lng", AppContext.getInstance().getLongitude()); intent2.putExtra("bt_geo_lat", AppContext.getInstance().getLatitude()); startActivity(intent2); } else { Intent intent = new Intent(BottleSingleActivity.this, ChooseLocationTabsActivity.class); intent.putExtra("type", "throw"); intent.putExtra("bottleId", bottleId); intent.putExtra("locationSelect", locationSelected); startActivity(intent); } } }); builder.create().show(); } }
Java
package com.outsourcing.bottle.ui; import java.util.ArrayList; import android.content.Context; import android.location.Location; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import android.widget.ImageView; import com.outsourcing.bottle.BasicActivity; import com.outsourcing.bottle.R; import com.outsourcing.bottle.ui.fragment.CityFragment; import com.outsourcing.bottle.ui.fragment.CountryFragment; import com.outsourcing.bottle.ui.fragment.GlobalFragment; import com.outsourcing.bottle.ui.fragment.NearByFragment; import com.viewpagerindicator.PageIndicator; import com.viewpagerindicator.TabPageIndicator; import com.viewpagerindicator.TitleProvider; /** * * @author 06peng * */ public class ChooseLocationTabsActivity extends BasicActivity { LoactionTabsAdapter mAdapter; ViewPager mPager; PageIndicator mIndicator; private ImageView back; public String[] choices; public Location location; public String reference; public String type; public LoactionTabsAdapter adapter; public int currentItem; public int bottleId; private int locationSelect; @Override protected void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); setContentView(R.layout.choose_location_tabs); networkLocat(); type = getIntent().getStringExtra("type"); bottleId = getIntent().getIntExtra("bottleId", 0); locationSelect = getIntent().getIntExtra("locationSelect", 1); initTabsFragment(); } private void initTabsFragment() { mAdapter = new LoactionTabsAdapter(getSupportFragmentManager(), this); Bundle bundle = new Bundle(); if (locationSelect == 1) { choices = new String[1]; choices[0] = getString(R.string.choose_location_nearby); bundle.putInt("currentItem", 0); mAdapter.addFragment(choices[0], NearByFragment.class, bundle); } else if (locationSelect == 2) { choices = new String[2]; choices[0] = getString(R.string.choose_location_nearby); choices[1] = getString(R.string.choose_location_city); bundle.putInt("currentItem", 0); mAdapter.addFragment(choices[0], NearByFragment.class, bundle); Bundle bundle1 = new Bundle(); bundle1.putInt("currentItem", 1); mAdapter.addFragment(choices[1], CityFragment.class, bundle1); } else if (locationSelect == 3) { choices = new String[3]; choices[0] = getString(R.string.choose_location_nearby); choices[1] = getString(R.string.choose_location_city); choices[2] = getString(R.string.choose_location_country); bundle.putInt("currentItem", 0); mAdapter.addFragment(choices[0], NearByFragment.class, bundle); Bundle bundle1 = new Bundle(); bundle1.putInt("currentItem", 1); mAdapter.addFragment(choices[1], CityFragment.class, bundle1); Bundle bundle2 = new Bundle(); bundle2.putInt("currentItem", 2); mAdapter.addFragment(choices[2], CountryFragment.class, bundle2); } else if (locationSelect == 4) { choices = new String[4]; choices[0] = getString(R.string.choose_location_nearby); choices[1] = getString(R.string.choose_location_city); choices[2] = getString(R.string.choose_location_country); choices[3] = getString(R.string.choose_location_global); bundle.putInt("currentItem", 0); mAdapter.addFragment(choices[0], NearByFragment.class, bundle); Bundle bundle1 = new Bundle(); bundle1.putInt("currentItem", 1); mAdapter.addFragment(choices[1], CityFragment.class, bundle1); Bundle bundle2 = new Bundle(); bundle2.putInt("currentItem", 2); mAdapter.addFragment(choices[2], CountryFragment.class, bundle2); Bundle bundle3 = new Bundle(); bundle3.putInt("currentItem", 3); mAdapter.addFragment(choices[3], GlobalFragment.class, bundle3); } mPager = (ViewPager) findViewById(R.id.pager); mPager.setAdapter(mAdapter); mIndicator = (TabPageIndicator) findViewById(R.id.indicator); mIndicator.setViewPager(mPager); back = (ImageView) findViewById(R.id.topbar_back); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } public static class LoactionTabsAdapter extends FragmentPagerAdapter implements TitleProvider { private Context mContext; private final ArrayList<FragmentInfo> fragments = new ArrayList<FragmentInfo>(); protected static final class FragmentInfo { private final String tag; private final Class<?> clss; private final Bundle args; protected FragmentInfo(String _tag, Class<?> _class, Bundle _args) { tag = _tag; clss = _class; args = _args; } } public LoactionTabsAdapter(FragmentManager fm, Context context) { super(fm); this.mContext = context; } public void addFragment(String tag, Class<?> clss, Bundle args) { FragmentInfo fragmentInfo = new FragmentInfo(tag, clss, args); fragments.add(fragmentInfo); } @Override public Fragment getItem(int arg0) { FragmentInfo fragmentInfo = fragments.get(arg0); return Fragment.instantiate(mContext, fragmentInfo.clss.getName(), fragmentInfo.args); } @Override public int getCount() { return fragments.size(); } @Override public String getTitle(int position) { return fragments.get(position).tag; } } }
Java
package com.outsourcing.bottle.ui; import java.util.ArrayList; import java.util.List; import org.json.JSONObject; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Handler; import android.os.Handler.Callback; import android.os.Message; import android.text.Html; import android.text.TextUtils; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ext.SatelliteMenu; import android.view.ext.SatelliteMenu.SateliteClickedListener; import android.view.ext.SatelliteMenuItem; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import com.google.gson.Gson; import com.outsourcing.bottle.BasicActivity; import com.outsourcing.bottle.R; import com.outsourcing.bottle.db.LoginUserInfoTable; import com.outsourcing.bottle.db.PushNoticeInfoTable; import com.outsourcing.bottle.domain.ExFeedInfoEntry; import com.outsourcing.bottle.domain.ExInfoSessionEntry; import com.outsourcing.bottle.domain.ExPicOuidInfoEntry; import com.outsourcing.bottle.domain.ExchangeInformationInfo; import com.outsourcing.bottle.domain.LoginUserInfoEntry; import com.outsourcing.bottle.domain.PushNoticeInfo; import com.outsourcing.bottle.domain.UrlConfig; import com.outsourcing.bottle.remoteimage.RemoteImageView; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.BasicUIEvent; import com.outsourcing.bottle.util.HttpUtils; import com.outsourcing.bottle.util.ServiceUtils; import com.outsourcing.bottle.util.TextUtil; import com.outsourcing.bottle.util.UICore; import com.outsourcing.bottle.widget.TryRefreshableView; public class ExchangeInfoDetailActivity extends BasicActivity implements BasicUIEvent, Callback, OnClickListener { private final int complete_info = 1; private final int menu_uploadphoto = 105; private final int menu_exprofile = 104; private final int menu_exphoto = 103; private final int menu_gainbt = 102; private final int menu_sendbt = 101; private final int user_baseinfo_notfull = 100; private static final int EXEU_EXCHANGE_INFO_INFO = 0; private static final int EXEU_EXCHANGE_INFO_FAILED = 1; private static final int EXEU_REJECT_EX_SUCCESS = 2; private static final int EXEU_REJECT_EX_FAILED = 3; private static final int EXEU_ACCEPT_EX_SUCCESS = 4; private static final int EXEU_ACCEPT_EX_FAILED = 5; private static final int EXEU_VISIBLE_INFOEX_SUCCESS = 6; private static final int EXEU_VISIBLE_INFOEX_FAILED = 7; private static final int EXEU_INVISIBLE_INFOEX_SUCCESS = 8; private static final int EXEU_INVISIBLE_INFOEX_FAILED = 9; private static final int EXEU_REFRESH_PROFILE_INFO = 10; private static final int EXEU_GET_MORE_INFO_INFO = 11; private static final int INIT_HAS_EXS_ERROR = 12; private static final int EXEU_GOTO_PHOTO = 13; private static final int INIT_HAS_EXS_PHOTO = 14; private static final int EXEU_GOTO_EXCHANGE = 15; private static final int EXEU_DELETE_LOCATION_FEED = 16; private static final int EXEU_DELETE_LOCATION_SUCCESS = 17; private static final int EXEU_DELETE_LOCATION_FAILED = 18; Handler handler; private ImageView topbar_back; private ImageView topbar_menu; int page = 1, ouid; // private ImageLoader imageLoader = null; private ExchangeInformationInfo mexchangeInfo = null; public int exsid; private TryRefreshableView rv; private LinearLayout feed_comment;// 资料回复的item private LinearLayout ll_content; private ScrollView sv; // private ImageView messageView; private LinearLayout bottomLayout; private RemoteImageView avatarView; private TextView contentView; private TextView btnCount; private int newNoticeCount; private int newMessageCount; private int newBottleFeedCount; private int newExchangeFeedCount; private int newMaybeKownCount; private String message_content; private String message_avatar; private PushBroadcastReceiver receiver; private PushNoticeInfo pushInfo; @Override protected void onCreate(Bundle paramBundle) { super.onCreate(paramBundle); setContentView(R.layout.exchange_pic_root); page = getIntent().getIntExtra("page", 1); ouid = getIntent().getIntExtra("ouid", 0); handler = new Handler(this); initLayout(); initSateMenu(); UICore.eventTask(this, this, EXEU_EXCHANGE_INFO_INFO, "", null); } private void initLayout() { topbar_back = (ImageView) findViewById(R.id.topbar_back); topbar_back.setOnClickListener(this); topbar_menu = (ImageView) findViewById(R.id.topbar_menu); topbar_menu.setVisibility(View.VISIBLE); topbar_menu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ExchangeInfoDetailActivity.this, HomeActivity.class); intent.putExtra("currentItem", 0); startActivity(intent); finish(); } }); // messageView = (ImageView) findViewById(R.id.notice_message_count); // messageView.setOnClickListener(this); bottomLayout = (LinearLayout) findViewById(R.id.notice_bottom_layout); bottomLayout.setOnClickListener(this); avatarView = (RemoteImageView) findViewById(R.id.notice_avatar); contentView = (TextView) findViewById(R.id.notice_text); btnCount = (TextView) findViewById(R.id.notice_number); // messageView.setVisibility(View.VISIBLE); // refresh_view = (ElasticScrollView) findViewById(R.id.refresh_view); // refresh_view // .setonRefreshListener(new ElasticScrollView.OnRefreshListener() { // // // // @Override // public void onRefresh() { // page = 1; // UICore.eventTask(ExchangeInfoDetailActivity.this, // ExchangeInfoDetailActivity.this, EXEU_REFRESH_PROFILE_INFO, null, // null); // // } // }); sv = (ScrollView) findViewById(R.id.trymySv); rv = (TryRefreshableView) findViewById(R.id.trymyRV); rv.mfooterView = (View) findViewById(R.id.tryrefresh_footer); rv.sv = sv; ll_content = (LinearLayout) findViewById(R.id.ll_content); // 隐藏mfooterView rv.mfooterViewText = (TextView) findViewById(R.id.tryrefresh_footer_text); rv.mfooterViewText.setVisibility(View.INVISIBLE); // 监听是否加载刷新 rv.setRefreshListener(new TryRefreshableView.RefreshListener() { @Override public void onRefresh() { if (rv.mRefreshState == 4) { page = 1; UICore.eventTask(ExchangeInfoDetailActivity.this, ExchangeInfoDetailActivity.this, EXEU_REFRESH_PROFILE_INFO, null, null); } else if (rv.mfooterRefreshState == 4) { page++; UICore.eventTask(ExchangeInfoDetailActivity.this, ExchangeInfoDetailActivity.this, EXEU_GET_MORE_INFO_INFO, null, null); } } }); } private void initSateMenu() { SatelliteMenu menu = (SatelliteMenu) findViewById(R.id.menu); menu.setVisibility(View.VISIBLE); if (CanvasWidth >= 480) { menu.setSatelliteDistance(200); } else { menu.setSatelliteDistance(100); } List<SatelliteMenuItem> items = new ArrayList<SatelliteMenuItem>(); items.add(new SatelliteMenuItem(menu_exprofile, R.drawable.menu_exprofile)); items.add(new SatelliteMenuItem(menu_exphoto, R.drawable.menu_exphoto)); items.add(new SatelliteMenuItem(menu_gainbt, R.drawable.menu_gainbt)); items.add(new SatelliteMenuItem(menu_sendbt, R.drawable.menu_sendbt)); items.add(new SatelliteMenuItem(menu_uploadphoto, R.drawable.menu_uploadphoto)); menu.addItems(items); menu.setOnItemClickedListener(new SateliteClickedListener() { public void eventOccured(int id) { switch (id) { case menu_sendbt: // 扔瓶子 new Thread() { public void run() { try { Thread.sleep(500); Intent throwIntent = new Intent( ExchangeInfoDetailActivity.this, ChooseBottleActivity.class); throwIntent.putExtra("type", "throw"); startActivity(throwIntent); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; case menu_gainbt: // 捞瓶子 new Thread() { public void run() { try { Thread.sleep(500); Intent tryIntent = new Intent( ExchangeInfoDetailActivity.this, ChooseBottleActivity.class); tryIntent.putExtra("type", "try"); startActivity(tryIntent); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; case menu_exphoto: // 交换照片 new Thread() { public void run() { try { Thread.sleep(500); Intent exchangeInfoIntent = new Intent( ExchangeInfoDetailActivity.this, ChooseFriendActivity.class); exchangeInfoIntent .putExtra( "choose_friend_type", AppContext.CHOOSE_FRIEND_EXCHANGE_PHOTO_TYPE); startActivity(exchangeInfoIntent); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; case menu_exprofile: // 交换资料 new Thread() { public void run() { try { Thread.sleep(500); LoginUserInfoTable userTable = new LoginUserInfoTable(); LoginUserInfoEntry userEntry = userTable .getLoginUserInfo(AppContext .getInstance().getLogin_uid()); if (userEntry.getBasicinfo_fullfill() == 0) { handler.sendEmptyMessage(user_baseinfo_notfull); } else { Intent exchangeFileIntent = new Intent( ExchangeInfoDetailActivity.this, ChooseFriendActivity.class); exchangeFileIntent .putExtra( "choose_friend_type", AppContext.CHOOSE_FRIEND_EXCHANGE_INFO_TYPE); startActivity(exchangeFileIntent); } } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; case menu_uploadphoto: new Thread() { public void run() { try { Thread.sleep(500); Intent intent = new Intent(ExchangeInfoDetailActivity.this, ExpandEditActivity.class); Bundle extras = new Bundle(); extras.putString("from_type", AppContext.UPLOAD_PHOTO); extras.putInt("albumid", 0); extras.putInt("ouid", AppContext.getInstance().getLogin_uid()); intent.putExtras(extras); startActivity(intent); } catch (InterruptedException e) { e.printStackTrace(); } }; }.start(); break; default: break; } } }); } @Override public void sysMesPositiveButtonEvent(int what) { if (what == complete_info) { Intent intent = new Intent(this, SettingActivity.class); startActivity(intent); } } private void getHasExs(int ouid) { StringBuffer url = new StringBuffer(UrlConfig.get_has_exs); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); try { String result = HttpUtils.doGet(url.toString()); if (result != null) { JSONObject object = new JSONObject(result); JSONObject resultObj = object.getJSONObject("results"); int authok = resultObj.getInt("authok"); if (authok == 0) { String errmsg = resultObj.getString("errmsg"); Message msg = Message.obtain(handler, INIT_HAS_EXS_ERROR, errmsg); handler.sendMessage(msg); } else { JSONObject hasExsObj = object.getJSONObject("has_exs"); int has_picexs = hasExsObj.getInt("has_picexs"); if (has_picexs == 1) { handler.sendEmptyMessage(EXEU_GOTO_PHOTO); } else { handler.sendEmptyMessage(INIT_HAS_EXS_PHOTO); } } } } catch (Exception e) { e.printStackTrace(); } } public void doExchange(int ouid) { this.ouid = ouid; UICore.eventTask(this, this, EXEU_GOTO_EXCHANGE, "has_exs", null); } View view = null; private void setViewValue() { view = LayoutInflater.from(this).inflate(R.layout.exchange_pic_content, null); RemoteImageView iv_ovatar = (RemoteImageView) view.findViewById(R.id.iv_author_photo); TextView tv_onickname = (TextView) view.findViewById(R.id.tv_onickname); ImageView bt_sex = (ImageView) view.findViewById(R.id.bt_sex); TextView tv_oDoing = (TextView) view.findViewById(R.id.tv_odoing); TextView tv_oLocation = (TextView) view.findViewById(R.id.tv_olocation); Button bt_profile = (Button) view.findViewById(R.id.bt_profile); Button bt_album = (Button) view.findViewById(R.id.bt_ex_photo); Button bt_ExProfile = (Button) view.findViewById(R.id.bt_ex_profile); bt_ExProfile.setText(TextUtil.R("exchange_bt_ex_photo")); RemoteImageView iv_ovatar_2 = (RemoteImageView) view.findViewById(R.id.iv_ex_pic_ovatar_2); ImageView iv_ex_type = (ImageView) view.findViewById(R.id.iv_ex_type); TextView tv_ex_feed = (TextView) view.findViewById(R.id.tv_ex_feed); TextView tv_feed_time = (TextView) view.findViewById(R.id.tv_feed_time); RemoteImageView iv_ovatar_right = (RemoteImageView) view.findViewById(R.id.iv_ex_pic_ovatar_3); Button bt_ex_comment = (Button) view .findViewById(R.id.bt_exchange_comment); Button bt_ex_reject = (Button) view .findViewById(R.id.bt_exchange_reject); Button bt_ex_accept = (Button) view .findViewById(R.id.bt_exchange_accept); Button bt_ex_visible = (Button) view .findViewById(R.id.bt_exchange_visible); Button bt_ex_invisible = (Button) view .findViewById(R.id.bt_exchange_invisible); TextView tv_feed_num = (TextView) view .findViewById(R.id.comments_ellipsis_text); View line_comments_ellipsis = (View) view .findViewById(R.id.line_comments_ellipsis); View line_exchange_comment = (View) view .findViewById(R.id.line_exchange_comment); RelativeLayout feed_comments_more = (RelativeLayout) view .findViewById(R.id.feed_comments_more); feed_comment = (LinearLayout) view .findViewById(R.id.ll_feed_comment_layout); final ExPicOuidInfoEntry exPicOuidEntry = mexchangeInfo.getOuid_info(); iv_ovatar.setDefaultImage(R.drawable.avatar_default_small); iv_ovatar.setImageUrl(exPicOuidEntry.getOavatar()); iv_ovatar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent spaceIntent = new Intent(ExchangeInfoDetailActivity.this, UserSpaceActivity.class); spaceIntent.putExtra("ouid", ouid); startActivity(spaceIntent); } }); String onickname = null; if (ouid!= AppContext.getInstance() .getLogin_uid()) { onickname ="<font color='#DA4A37'>" + exPicOuidEntry.getOnickname() + "</font>"; } else { onickname = "<font color='#3F99D8'>" + exPicOuidEntry.getOnickname() + "</font>"; } // String sex = exPicOuidEntry.getOsex() == 1 ? ("(" // + TextUtil.R("login_txt_register_male") + ")") : ("(" // + TextUtil.R("login_txt_register_female") + ")"); String memo = (null != exPicOuidEntry.getOmemo() && exPicOuidEntry .getOmemo().length() > 0) ? exPicOuidEntry.getOmemo() : ""; tv_onickname.setText(Html.fromHtml(onickname + memo)); int sex_res = exPicOuidEntry.getOsex() == 1 ? R.drawable.male : R.drawable.female; bt_sex.setImageResource(sex_res); if (null != exPicOuidEntry.getOdoing() && exPicOuidEntry.getOdoing().length() > 0) { tv_oDoing.setVisibility(View.VISIBLE); String commentMood = "<font color='#000000'>" + TextUtil.R("ex_comment_mood") + "</font>"; tv_oDoing.setText(TextUtil.R("ex_comment_mood") + exPicOuidEntry.getOdoing()); } else { tv_oDoing.setVisibility(View.GONE); } if ((null != exPicOuidEntry.getOcountry() && exPicOuidEntry .getOcountry().length() > 0) || (null != exPicOuidEntry.getOcity() && exPicOuidEntry .getOcity().length() > 0)) { tv_oLocation.setVisibility(View.VISIBLE); tv_oLocation.setText(exPicOuidEntry.getOcountry() + exPicOuidEntry.getOcity()); } else { tv_oLocation.setVisibility(View.GONE); } switch (exPicOuidEntry.getOprofile_visible()) { case 0://灰色 bt_profile.setBackgroundResource(R.drawable.btn_gray_try); break; case 1://蓝色 bt_profile.setBackgroundResource(R.drawable.btn_blue_try); break; default: break; } bt_profile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ExchangeInfoDetailActivity.this, UserSpaceActivity.class); intent.putExtra("ouid", ouid); startActivity(intent); } }); bt_ExProfile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { doExchange(ouid); } }); if (exPicOuidEntry.getOalbum_visible() == 1) { bt_album.setBackgroundResource(R.drawable.btn_blue_try); bt_album.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ExchangeInfoDetailActivity.this, AlbumsActivity.class); intent.putExtra("ouid", ouid); startActivity(intent); } }); } else { bt_album.setBackgroundResource(R.drawable.btn_gray_try); bt_album.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ExchangeInfoDetailActivity.this.onToast(TextUtil .R("exchange_feed_invisible_tips")); } }); } final ExInfoSessionEntry exSessionEntry = mexchangeInfo.getExs_info(); iv_ovatar_2.setDefaultImage(R.drawable.avatar_default_small); iv_ovatar_2.setImageUrl(exSessionEntry.getExs_avatar()); iv_ovatar_right.setDefaultImage(R.drawable.avatar_default_small); iv_ovatar_right.setImageUrl(exSessionEntry.getExs_oavatar()); iv_ovatar_2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent spaceIntent = new Intent(ExchangeInfoDetailActivity.this, UserSpaceActivity.class); spaceIntent.putExtra("ouid", exSessionEntry.getExs_uid()); startActivity(spaceIntent); } }); iv_ovatar_right.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent spaceIntent = new Intent(ExchangeInfoDetailActivity.this, UserSpaceActivity.class); spaceIntent.putExtra("ouid", exSessionEntry.getExs_ouid()); startActivity(spaceIntent); } }); iv_ex_type.setImageResource(R.drawable.btn_exprofile); String nickName = null; if (ouid!= AppContext.getInstance() .getLogin_uid()) { nickName ="<font color='#DA4A37'>" + exPicOuidEntry.getOnickname() + "</font>"; } else { nickName = "<font color='#3F99D8'>" + exPicOuidEntry.getOnickname() + "</font>"; } String mSuccess = (exSessionEntry.getExs_success() == 1) ? ("<font color='#FF3333'>" + TextUtil.R("exchange_success") + "</font>") : ("<font color='#FF3333'>" + TextUtil.R("exchange_failed") + "</font>"); tv_ex_feed.setText(Html.fromHtml(nickName + exSessionEntry.getExs_firstfeed() + " " + mSuccess)); if (null != tv_feed_time && tv_feed_time.length() > 0) { tv_feed_time.setVisibility(View.VISIBLE); String time = "<font color='#000000'>" + " #" + exSessionEntry.getExs_firstfeedtime() + "</font>"; tv_feed_time.setText(Html.fromHtml(time)); } else { tv_feed_time.setVisibility(View.GONE); } bt_ex_comment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent commentIntent = new Intent( ExchangeInfoDetailActivity.this, ExpandEditActivity.class); Bundle commentBundle = new Bundle(); commentBundle.putString("from_type", AppContext.REPLY_INFOEX); commentBundle.putString("reply_infoex_type", "replay"); commentBundle.putInt("ouid", ouid); commentIntent.putExtras(commentBundle); startActivity(commentIntent); finish(); } }); if (exSessionEntry.getExs_infoex_rejectshow() == 1) { bt_ex_reject.setVisibility(View.VISIBLE); bt_ex_reject.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { doRejectInfoex(ouid, exSessionEntry.getExsid()); } }); } else { bt_ex_reject.setVisibility(View.INVISIBLE); } if (exSessionEntry.getExs_infoex_acceptshow() == 1) { bt_ex_accept.setVisibility(View.VISIBLE); bt_ex_accept.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { doAcceptInfoex(ouid, exSessionEntry.getExsid()); } }); } else { bt_ex_accept.setVisibility(View.GONE); } if (exSessionEntry.getExs_infoex_visibleshow() == 1) { bt_ex_visible.setVisibility(View.VISIBLE); bt_ex_visible.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { doVisibleInfoex(ouid, exSessionEntry.getExsid()); } }); } else { bt_ex_visible.setVisibility(View.GONE); } if (exSessionEntry.getExs_infoex_invisibleshow() == 1) { bt_ex_invisible.setVisibility(View.VISIBLE); bt_ex_invisible.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { doInvisibleInfoex(ouid, exSessionEntry.getExsid()); } }); } else { bt_ex_invisible.setVisibility(View.GONE); } List<ExFeedInfoEntry> mExFeedPicEntries = mexchangeInfo .getExfeeds_list(); if (null != mExFeedPicEntries && mExFeedPicEntries.size() > 0) { line_exchange_comment.setVisibility(View.VISIBLE); line_comments_ellipsis.setVisibility(View.VISIBLE); feed_comments_more.setVisibility(View.VISIBLE); tv_feed_num.setText(mexchangeInfo.getRscount() + " " + TextUtil.R("bottle_txt_comment_more")); for (int i = 0; i < mExFeedPicEntries.size(); i++) { final ExFeedInfoEntry mExFeedPicEntry = mExFeedPicEntries .get(i); View feed_child = LayoutInflater.from(this).inflate( R.layout.exchange_comments_item, null); if (i == (mExFeedPicEntries.size()-1)) { View feed_avatar = (View) feed_child .findViewById(R.id.line_exchange_feed); feed_avatar.setVisibility(View.INVISIBLE); } RelativeLayout mfeedPhoto = (RelativeLayout) feed_child .findViewById(R.id.rl_exchange_feed_type); mfeedPhoto.setVisibility(View.GONE); RemoteImageView comment_profile_photo = (RemoteImageView) feed_child .findViewById(R.id.comment_profile_photo); try { comment_profile_photo.setDefaultImage(R.drawable.avatar_default_small); comment_profile_photo.setImageUrl(mExFeedPicEntry.getExfeed_avatar()); } catch (Exception e) { e.printStackTrace(); comment_profile_photo .setImageResource(R.drawable.avatar_default_small); } comment_profile_photo .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent spaceIntent = new Intent(ExchangeInfoDetailActivity.this, UserSpaceActivity.class); spaceIntent.putExtra("ouid", mExFeedPicEntry.getExfeed_uid()); startActivity(spaceIntent); } }); TextView mFeedAvatar = (TextView) feed_child .findViewById(R.id.tv_feed_comment_nickname); String feed_nickname = null; if (mExFeedPicEntry.getExfeed_uid()!= AppContext.getInstance() .getLogin_uid()) { feed_nickname = (!TextUtils.isEmpty(mExFeedPicEntry.getExfeed_nickname())) ? ("<font color='#DA4A37'>" + mExFeedPicEntry.getExfeed_nickname()+ "</font>") : ""; } else { feed_nickname = (!TextUtils.isEmpty(mExFeedPicEntry.getExfeed_nickname())) ? ("<font color='#3F99D8'>" + mExFeedPicEntry.getExfeed_nickname() + "</font>") : ""; } mFeedAvatar.setText(Html.fromHtml(feed_nickname + " " + TextUtil.htmlEncode(mExFeedPicEntry .getExfeed_content()))); TextView mFeedComment = (TextView) feed_child .findViewById(R.id.tv_feed_comment_content); if (null != mExFeedPicEntry.getExfeed_comment() && mExFeedPicEntry.getExfeed_comment().length() > 0) { mFeedComment.setVisibility(View.VISIBLE); String commentTips = "<font color='#000000'>" + TextUtil.R("exchange_feed_comment_title") + "</font>"; String comment = mExFeedPicEntry.getExfeed_isnew() == 1 ? ("<font color='#DA4A37'>" + TextUtil.htmlEncode(mExFeedPicEntry.getExfeed_comment()) + "</font>") : TextUtil.htmlEncode(mExFeedPicEntry.getExfeed_comment()); mFeedComment.setText(Html.fromHtml(commentTips + comment)); } else { mFeedComment.setVisibility(View.GONE); } TextView mFeedTime = (TextView) feed_child .findViewById(R.id.tv_feed_comment_time); String time = (!TextUtils.isEmpty(mExFeedPicEntry .getExfeed_time())) ? (" #" + mExFeedPicEntry .getExfeed_time()) : ""; String location = (!TextUtils.isEmpty(mExFeedPicEntry .getExfeed_location())) ? (" @" + mExFeedPicEntry .getExfeed_location()) : ""; mFeedTime.setText(time + location); if (location.length() > 0) { mFeedTime.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mExFeedPicEntry.getLocation_delete_enable() == 1) { final Context dialogContext = new ContextThemeWrapper( ExchangeInfoDetailActivity.this, android.R.style.Theme_Light); String[] choices = new String[2]; choices[0] = getString(R.string.bottle_txt_check_location); choices[1] = getString(R.string.bottle_txt_clean_location); final ListAdapter adapter = new ArrayAdapter<String>( dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { dialog.dismiss(); if (which == 0) { dialog.dismiss(); Intent intent = new Intent( ExchangeInfoDetailActivity.this, MapViewActivity.class); intent.putExtra("longitude", mExFeedPicEntry .getExfeed_lng()); intent.putExtra("latidute", mExFeedPicEntry .getExfeed_lat()); intent.putExtra( "location", mExFeedPicEntry .getExfeed_location()); startActivity(intent); } else { UICore.eventTask( ExchangeInfoDetailActivity.this, ExchangeInfoDetailActivity.this, EXEU_DELETE_LOCATION_FEED,"",mExFeedPicEntry); } } }); builder.create().show(); } else { final Context dialogContext = new ContextThemeWrapper( ExchangeInfoDetailActivity.this, android.R.style.Theme_Light); String[] choices = new String[1]; choices[0] = getString(R.string.bottle_txt_check_location); final ListAdapter adapter = new ArrayAdapter<String>( dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { dialog.dismiss(); Intent intent = new Intent( ExchangeInfoDetailActivity.this, MapViewActivity.class); intent.putExtra("longitude", mExFeedPicEntry .getExfeed_lng()); intent.putExtra("latidute", mExFeedPicEntry .getExfeed_lat()); intent.putExtra( "location", mExFeedPicEntry .getExfeed_location()); startActivity(intent); } }); builder.create().show(); } } }); } feed_comment.addView(feed_child); } } else { line_exchange_comment.setVisibility(View.GONE); line_comments_ellipsis.setVisibility(View.GONE); feed_comments_more.setVisibility(View.GONE); } // refresh_view.addChild(view); ll_content.addView(view); rv.mfooterViewText.setVisibility(View.VISIBLE); ServiceUtils.dout("CanvasHeight:" + CanvasHeight); ServiceUtils.dout("ll_content.getHeight():" + ll_content.getHeight()); ServiceUtils.dout("ll_content.getLayoutParams().height:" + ll_content.getLayoutParams().height); } public void doInvisibleInfoex(int ouid, int exsid) { this.ouid = ouid; this.exsid = exsid; UICore.eventTask(this, this, EXEU_INVISIBLE_INFOEX_SUCCESS, "", null); } private void invisibleInfoex(int ouid) { StringBuffer url = new StringBuffer(UrlConfig.invisible_infoex); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); ServiceUtils.dout("invisibleInfoex url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); ServiceUtils.dout("invisibleInfoex result:" + results); if (null != results) { JSONObject obj = new JSONObject(results); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); String errmsg = resultObj.getString("errmsg"); String successmsg = resultObj.getString("successmsg"); if (success == 1) { Message message = handler.obtainMessage( EXEU_INVISIBLE_INFOEX_SUCCESS, successmsg); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_INVISIBLE_INFOEX_FAILED, errmsg); handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); } } public void doVisibleInfoex(int ouid, int exsid) { this.ouid = ouid; this.exsid = exsid; UICore.eventTask(this, this, EXEU_VISIBLE_INFOEX_SUCCESS, "", null); } private void visibleInfoex(int ouid) { StringBuffer url = new StringBuffer(UrlConfig.visible_infoex); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); ServiceUtils.dout("visibleInfoex url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); ServiceUtils.dout("visibleInfoex result:" + results); if (null != results) { JSONObject obj = new JSONObject(results); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); String errmsg = resultObj.getString("errmsg"); String successmsg = resultObj.getString("successmsg"); if (success == 1) { Message message = handler.obtainMessage( EXEU_VISIBLE_INFOEX_SUCCESS, successmsg); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_VISIBLE_INFOEX_FAILED, errmsg); handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); } } public void doAcceptInfoex(int ouid, int exsid) { this.ouid = ouid; this.exsid = exsid; LoginUserInfoTable loginUserInfoTable = new LoginUserInfoTable(); LoginUserInfoEntry loginUserInfoEntry = loginUserInfoTable .getLoginUserInfo(AppContext.getInstance().getLogin_uid()); if (null != loginUserInfoEntry && loginUserInfoEntry.getBasicinfo_fullfill() == 0) { String basicinfo_tip = loginUserInfoEntry.getBasicinfo_tip(); AlertDialog.Builder alertDialog = new AlertDialog.Builder( ExchangeInfoDetailActivity.this); alertDialog.setMessage(basicinfo_tip); alertDialog.setPositiveButton(TextUtil.R("confirm_ok"), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent( ExchangeInfoDetailActivity.this, SettingActivity.class); startActivity(intent); } }); alertDialog.setNegativeButton(TextUtil.R("confirm_cancel"), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); alertDialog.create().show(); } else { UICore.eventTask(this, this, EXEU_ACCEPT_EX_SUCCESS, "", null); } } private void acceptInfoex(int ouid) { StringBuffer url = new StringBuffer(UrlConfig.accept_infoex); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); ServiceUtils.dout("acceptInfoex url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); ServiceUtils.dout("acceptInfoex result:" + results); if (null != results) { JSONObject obj = new JSONObject(results); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); String errmsg = resultObj.getString("errmsg"); String successmsg = resultObj.getString("successmsg"); if (success == 1) { Message message = handler.obtainMessage( EXEU_ACCEPT_EX_SUCCESS, successmsg); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_ACCEPT_EX_FAILED, errmsg); handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); } } public void doRejectInfoex(int ouid, int exsid) { this.ouid = ouid; this.exsid = exsid; UICore.eventTask(this, this, EXEU_REJECT_EX_SUCCESS, "", null); } private void rejectInfoex(int ouid) { StringBuffer url = new StringBuffer(UrlConfig.reject_infoex); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); ServiceUtils.dout("rejectInfoex url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); ServiceUtils.dout("rejectInfoex result:" + results); if (null != results) { JSONObject obj = new JSONObject(results); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); String errmsg = resultObj.getString("errmsg"); String successmsg = resultObj.getString("successmsg"); if (success == 1) { Message message = handler.obtainMessage( EXEU_REJECT_EX_SUCCESS, successmsg); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_REJECT_EX_FAILED, errmsg); handler.sendMessage(message); } } } catch (Exception e) { e.printStackTrace(); } } @Override public void execute(int mes, Object obj) { switch (mes) { case EXEU_EXCHANGE_INFO_INFO: getExchangeInfo(ouid, page); break; case EXEU_REJECT_EX_SUCCESS: rejectInfoex(ouid); break; case EXEU_ACCEPT_EX_SUCCESS: acceptInfoex(ouid); break; case EXEU_VISIBLE_INFOEX_SUCCESS: visibleInfoex(ouid); break; case EXEU_INVISIBLE_INFOEX_SUCCESS: invisibleInfoex(ouid); break; case EXEU_REFRESH_PROFILE_INFO: refreshExchangeInfo(ouid, page); break; case EXEU_GET_MORE_INFO_INFO: getMoreExchangeInfo(ouid, page); break; case EXEU_GOTO_EXCHANGE: getHasExs(ouid); break; case EXEU_DELETE_LOCATION_FEED: ExFeedInfoEntry mExFeedPicEntry = (ExFeedInfoEntry)obj; deleteLocation(String.valueOf(mExFeedPicEntry.getLocation_objtype()),String.valueOf(mExFeedPicEntry.getLocation_objid())); break; default: break; } } @Override protected void onDestroy() { super.onDestroy(); try { if (receiver != null) { unregisterReceiver(receiver); } } catch (Exception e) { e.printStackTrace(); } } private void getExchangeInfo(int ouid, int page) { StringBuffer url = new StringBuffer(UrlConfig.get_infoex); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); url.append("&count=10"); url.append("&page=" + page); ServiceUtils.dout("getExchangeInfo url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); if (results == null) { return; } ServiceUtils.dout("getExchangeInfo results:" + results); Gson gson = new Gson(); mexchangeInfo = gson.fromJson(results, ExchangeInformationInfo.class); if (mexchangeInfo.getResults().getAuthok() == 1) { PushNoticeInfoTable table = new PushNoticeInfoTable(); pushInfo = table.getPushNoticeInfo(AppContext.getInstance() .getLogin_uid()); if (null != pushInfo) { newBottleFeedCount = pushInfo.getNew_btfeed_count(); newExchangeFeedCount = pushInfo.getNew_exfeed_count(); newMessageCount = pushInfo.getNew_message_count(); newNoticeCount = pushInfo.getNew_notice_count(); message_content = pushInfo.getMessage_content(); message_avatar = pushInfo.getMessage_avatar(); newMaybeKownCount = pushInfo.getNew_maybeknow_count(); } Message message = handler .obtainMessage(EXEU_EXCHANGE_INFO_INFO); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_EXCHANGE_INFO_FAILED, mexchangeInfo.getResults() .getErrmsg()); handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } private void getMoreExchangeInfo(int ouid, int page) { StringBuffer url = new StringBuffer(UrlConfig.get_infoex); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); url.append("&count=10"); url.append("&page=" + page); ServiceUtils.dout("getExchangeInfo url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); if (results == null) { return; } ServiceUtils.dout("getExchangeInfo results:" + results); Gson gson = new Gson(); mexchangeInfo = gson.fromJson(results, ExchangeInformationInfo.class); if (mexchangeInfo.getResults().getAuthok() == 1) { Message message = handler .obtainMessage(EXEU_GET_MORE_INFO_INFO); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_EXCHANGE_INFO_FAILED, mexchangeInfo.getResults() .getErrmsg()); handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } private void refreshExchangeInfo(int ouid, int page) { StringBuffer url = new StringBuffer(UrlConfig.get_infoex); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&ouid=" + ouid); url.append("&count=20"); url.append("&page=" + page); ServiceUtils.dout("getExchangeInfo url: " + url.toString()); try { String results = HttpUtils.doGet(url.toString()); if (results == null) { return; } ServiceUtils.dout("getExchangeInfo results:" + results); Gson gson = new Gson(); mexchangeInfo = gson.fromJson(results, ExchangeInformationInfo.class); if (mexchangeInfo.getResults().getAuthok() == 1) { Message message = handler .obtainMessage(EXEU_REFRESH_PROFILE_INFO); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_EXCHANGE_INFO_FAILED, mexchangeInfo.getResults() .getErrmsg()); handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } @Override public boolean handleMessage(Message msg) { switch (msg.what) { case EXEU_EXCHANGE_INFO_INFO: ll_content.removeAllViews(); setViewValue(); pushNoticeUpdateUI(); receiver = new PushBroadcastReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction("push"); registerReceiver(receiver, filter); break; case EXEU_REFRESH_PROFILE_INFO: // refresh_view.removeChild(view); ll_content.removeAllViews(); setViewValue(); rv.finishRefresh(); // refresh_view.onRefreshComplete(); break; case EXEU_EXCHANGE_INFO_FAILED: onToast((String) msg.obj); break; case EXEU_REJECT_EX_SUCCESS: page = 1; UICore.eventTask(this, this, EXEU_EXCHANGE_INFO_INFO, "", null); break; case EXEU_REJECT_EX_FAILED: onToast((String) msg.obj); break; case EXEU_ACCEPT_EX_SUCCESS: page = 1; UICore.eventTask(this, this, EXEU_EXCHANGE_INFO_INFO, "", null); break; case EXEU_ACCEPT_EX_FAILED: onToast((String) msg.obj); break; case EXEU_VISIBLE_INFOEX_SUCCESS: page = 1; UICore.eventTask(this, this, EXEU_EXCHANGE_INFO_INFO, "", null); break; case EXEU_VISIBLE_INFOEX_FAILED: onToast((String) msg.obj); break; case EXEU_INVISIBLE_INFOEX_SUCCESS: page = 1; UICore.eventTask(this, this, EXEU_EXCHANGE_INFO_INFO, "", null); break; case EXEU_INVISIBLE_INFOEX_FAILED: onToast((String) msg.obj); break; case EXEU_GET_MORE_INFO_INFO: List<ExFeedInfoEntry> mExFeedInfoEntries = mexchangeInfo .getExfeeds_list(); if (null != mExFeedInfoEntries && mExFeedInfoEntries.size() > 0) { setMoreFeed(mExFeedInfoEntries); } else { onToast(TextUtil.R("no_more_data")); } rv.finishRefresh(); break; case INIT_HAS_EXS_ERROR: onToast((String) msg.obj); break; case EXEU_GOTO_PHOTO: Intent intentExchangePic = new Intent(this, ExchangePicDetailActivity.class); intentExchangePic.putExtra("ouid", ouid); intentExchangePic.putExtra("page", 1); startActivity(intentExchangePic); break; case INIT_HAS_EXS_PHOTO: Intent intentPhoto = new Intent(this, ExpandEditActivity.class); Bundle bundlePhoto = new Bundle(); bundlePhoto.putString("from_type", AppContext.APPLY_PICEX); bundlePhoto.putInt("ouid", ouid); intentPhoto.putExtras(bundlePhoto); startActivity(intentPhoto); finish(); break; case user_baseinfo_notfull: LoginUserInfoTable userTable = new LoginUserInfoTable(); LoginUserInfoEntry userEntry = userTable.getLoginUserInfo(AppContext.getInstance().getLogin_uid()); showChoseMes(userEntry.getBasicinfo_tip(), complete_info); break; case EXEU_DELETE_LOCATION_SUCCESS: page = 1; UICore.eventTask(this, this, EXEU_EXCHANGE_INFO_INFO, "", null); break; case EXEU_DELETE_LOCATION_FAILED: onToast((String) msg.obj); break; default: break; } return false; } private void setMoreFeed(List<ExFeedInfoEntry> mExFeedInfoEntries) { for (int i = 0; i < mExFeedInfoEntries.size(); i++) { final ExFeedInfoEntry mExFeedPicEntry = mExFeedInfoEntries.get(i); View feed_child = LayoutInflater.from(this).inflate( R.layout.exchange_comments_item, null); RelativeLayout mfeedPhoto = (RelativeLayout) feed_child .findViewById(R.id.rl_exchange_feed_type); mfeedPhoto.setVisibility(View.GONE); RemoteImageView comment_profile_photo = (RemoteImageView) feed_child .findViewById(R.id.comment_profile_photo); try { comment_profile_photo.setDefaultImage(R.drawable.avatar_default_small); comment_profile_photo.setImageUrl(mExFeedPicEntry.getExfeed_avatar()); } catch (Exception e) { e.printStackTrace(); comment_profile_photo .setImageResource(R.drawable.avatar_default_small); } comment_profile_photo .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent spaceIntent = new Intent(ExchangeInfoDetailActivity.this, UserSpaceActivity.class); spaceIntent.putExtra("ouid", mExFeedPicEntry.getExfeed_uid()); startActivity(spaceIntent); } }); TextView mFeedAvatar = (TextView) feed_child .findViewById(R.id.tv_feed_comment_nickname); String feed_nickname = null; if (mExFeedPicEntry.getExfeed_uid()!= AppContext.getInstance() .getLogin_uid()) { feed_nickname = (!TextUtils.isEmpty(mExFeedPicEntry.getExfeed_nickname())) ? ("<font color='#DA4A37'>" + mExFeedPicEntry.getExfeed_nickname()+ "</font>") : ""; } else { feed_nickname = (!TextUtils.isEmpty(mExFeedPicEntry.getExfeed_nickname())) ? ("<font color='#3F99D8'>" + mExFeedPicEntry.getExfeed_nickname() + "</font>") : ""; } mFeedAvatar.setText(Html.fromHtml(feed_nickname + " " + TextUtil.htmlEncode(mExFeedPicEntry .getExfeed_content()))); TextView mFeedComment = (TextView) feed_child .findViewById(R.id.tv_feed_comment_content); if (null != mExFeedPicEntry.getExfeed_comment() && mExFeedPicEntry.getExfeed_comment().length() > 0) { mFeedComment.setVisibility(View.VISIBLE); String commentTips = "<font color='#000000'>" + TextUtil.R("exchange_feed_comment_title") + ":" + "</font>"; String comment = mExFeedPicEntry.getExfeed_isnew() == 1 ? ("<font color='#DA4A37'>" + TextUtil.htmlEncode(mExFeedPicEntry.getExfeed_comment()) + "</font>") : TextUtil.htmlEncode(mExFeedPicEntry.getExfeed_comment()); mFeedComment.setText(Html.fromHtml(commentTips + comment)); } else { mFeedComment.setVisibility(View.GONE); } TextView mFeedTime = (TextView) feed_child .findViewById(R.id.tv_feed_comment_time); String time = (mExFeedPicEntry.getExfeed_time() != null && mExFeedPicEntry .getExfeed_time().length() > 0) ? (" #" + mExFeedPicEntry .getExfeed_time()) : ""; String location = (null != mExFeedPicEntry.getExfeed_location() && mExFeedPicEntry .getExfeed_location().length() > 0) ? (" @" + mExFeedPicEntry .getExfeed_location()) : ""; mFeedTime.setText(time + location); if (location.length() > 0) { mFeedTime.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final Context dialogContext = new ContextThemeWrapper( ExchangeInfoDetailActivity.this, android.R.style.Theme_Light); String[] choices = new String[1]; choices[0] = getString(R.string.bottle_txt_check_location); final ListAdapter adapter = new ArrayAdapter<String>( dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); Intent intent = new Intent( ExchangeInfoDetailActivity.this, MapViewActivity.class); intent.putExtra("longitude", mExFeedPicEntry.getExfeed_lng()); intent.putExtra("latidute", mExFeedPicEntry.getExfeed_lat()); intent.putExtra("location", mExFeedPicEntry .getExfeed_location()); startActivity(intent); } }); builder.create().show(); } }); } feed_comment.addView(feed_child); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.topbar_back: finish(); break; // case R.id.notice_message_count: // doMessageAction(); // break; case R.id.notice_bottom_layout: doFeedsAction(); break; default: break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (null != data) { if (data.getBooleanExtra("need_refresh", false)) { page = 1; UICore.eventTask(this, this, EXEU_EXCHANGE_INFO_INFO, "", null); } } } public void doMessageAction() { final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light); String[] choices = new String[2]; if (newNoticeCount > 0) { choices[0] = newNoticeCount + getString(R.string.bottle_txt_notice_list); } else { choices[0] = getString(R.string.bottle_txt_notice_list); } if (newMessageCount > 0) { choices[1] = newMessageCount + getString(R.string.bottle_txt_message_list); } else { choices[1] = getString(R.string.bottle_txt_message_list); } final ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (which == 0) { Intent intent = new Intent( ExchangeInfoDetailActivity.this, NoticeListActivity.class); startActivity(intent); } else { Intent intent = new Intent( ExchangeInfoDetailActivity.this, MessageListActivity.class); startActivity(intent); } } }); builder.create().show(); } /** * * @param objtype 要清除的位置的类型:选择项:(1)瓶子动态的位置信息、(2)交换动态留言的位置信息、(3)照片评论的位置信息、(4)私信的位置信息、(5)照片的位置信息 * @param objid objid */ private void deleteLocation(String objtype,String objid) { StringBuffer url = new StringBuffer(UrlConfig.delete_location); url.append("?clitype=2"); url.append("&language=" + AppContext.language); url.append("&login_uid=" + AppContext.getInstance().getLogin_uid()); url.append("&login_token=" + AppContext.getInstance().getLogin_token()); url.append("&objtype=" + objtype); url.append("&objid=" + objid); ServiceUtils.dout("deleteLocation url:" + url.toString()); try { String result = HttpUtils.doGet(url.toString()); ServiceUtils.dout("deleteLocation result:" + result); JSONObject obj = new JSONObject(result); JSONObject resultObj = obj.getJSONObject("results"); int success = resultObj.getInt("success"); String errmsg = resultObj.getString("errmsg"); String successmsg = resultObj.getString("successmsg"); if (success == 1) { Message message = handler.obtainMessage( EXEU_DELETE_LOCATION_SUCCESS, successmsg); handler.sendMessage(message); } else { Message message = handler.obtainMessage( EXEU_DELETE_LOCATION_FAILED, errmsg); handler.sendMessage(message); } } catch (Exception e) { e.printStackTrace(); } } public void doFeedsAction() { final Context dialogContext = new ContextThemeWrapper(this, android.R.style.Theme_Light); final List<String> choices = new ArrayList<String>(); if (newBottleFeedCount > 0) { choices.add(newBottleFeedCount + getString(R.string.bottle_txt_new_bottle_feed)); } if (newExchangeFeedCount > 0) { choices.add(newExchangeFeedCount + getString(R.string.bottle_txt_new_exchange_feed)); } if (newNoticeCount > 0) { choices.add(newNoticeCount + getString(R.string.bottle_txt_notice_list)); } if (newMessageCount > 0) { choices.add(newMessageCount + getString(R.string.bottle_txt_message_list)); } if (newMaybeKownCount > 0) { choices.add(newMaybeKownCount + getString(R.string.bottle_txt_new_maybe_kown)); } final ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder(dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (choices.get(which).indexOf(getString(R.string.bottle_txt_new_bottle_feed)) != -1) { Intent intent = new Intent(ExchangeInfoDetailActivity.this, HomeActivity.class); AppContext.getInstance().setCurrentItem(1); startActivity(intent); } else if (choices.get(which).indexOf(getString(R.string.bottle_txt_new_exchange_feed)) != -1) { Intent intent = new Intent(ExchangeInfoDetailActivity.this, HomeActivity.class); AppContext.getInstance().setCurrentItem(0); startActivity(intent); } else if (choices.get(which).indexOf(getString(R.string.bottle_txt_notice_list)) != -1) { Intent intent = new Intent(ExchangeInfoDetailActivity.this, NoticeListActivity.class); startActivity(intent); } else if (choices.get(which).indexOf(getString(R.string.bottle_txt_message_list)) != -1) { Intent intent = new Intent(ExchangeInfoDetailActivity.this, MessageListActivity.class); startActivity(intent); } else if (choices.get(which).indexOf(getString(R.string.bottle_txt_new_maybe_kown)) != -1) { Intent intent = new Intent(ExchangeInfoDetailActivity.this, HomeActivity.class); AppContext.getInstance().setCurrentItem(2); AppContext.getInstance().setGotoMaybeKown(true); startActivity(intent); } } }); builder.create().show(); } public void pushNoticeUpdateUI() { if (newBottleFeedCount + newExchangeFeedCount + newMessageCount + newNoticeCount + newMaybeKownCount > 0) { bottomLayout.setVisibility(View.VISIBLE); contentView.setText(message_content); btnCount.setText(newBottleFeedCount + newExchangeFeedCount + newMessageCount + newNoticeCount + newMaybeKownCount + ""); avatarView.setDefaultImage(R.drawable.avatar_default_big); avatarView.setImageUrl(message_avatar); } else { bottomLayout.setVisibility(View.GONE); } } public class PushBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); if (bundle != null) { newBottleFeedCount = bundle.getInt("bottle_feed_count"); newExchangeFeedCount = bundle.getInt("exchange_feed_count"); newMessageCount = bundle.getInt("message_count"); newNoticeCount = bundle.getInt("notice_count"); message_content = bundle.getString("message_content"); message_avatar = bundle.getString("message_avatar"); newMaybeKownCount = bundle.getInt("maybe_kown_count"); pushNoticeUpdateUI(); } } } }
Java
package com.outsourcing.bottle; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.Process; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.telephony.TelephonyManager; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import com.google.gson.Gson; import com.outsourcing.bottle.db.BottleNetTypeTable; import com.outsourcing.bottle.db.BottleTypeTable; import com.outsourcing.bottle.db.LanguageConfigTable; import com.outsourcing.bottle.db.OtherConfigTable; import com.outsourcing.bottle.domain.BottleNetTypeEntry; import com.outsourcing.bottle.domain.BottleTypeEntry; import com.outsourcing.bottle.domain.InitBottleInfo; import com.outsourcing.bottle.domain.LanguageConfig; import com.outsourcing.bottle.domain.OtherConfigEntry; import com.outsourcing.bottle.domain.PlatformBindConfig; import com.outsourcing.bottle.domain.UrlConfig; import com.outsourcing.bottle.ui.HomeActivity; import com.outsourcing.bottle.ui.LoginActivity; import com.outsourcing.bottle.ui.LoginPlatformActivity; import com.outsourcing.bottle.ui.LogoFragment; import com.outsourcing.bottle.util.ActivityManager; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.BottlePushService; import com.outsourcing.bottle.util.HttpUtils; import com.outsourcing.bottle.util.ServiceUtils; import com.outsourcing.bottle.util.UICore; import com.viewpagerindicator.CirclePageIndicator; import com.viewpagerindicator.PageIndicator; /** * * @author 06peng * */ public class SplashActivity extends BasicActivity implements OnClickListener { private final int new_version = 1; private final int initData = 2; private final int login = 3; private boolean init; CirclePageFragmentAdapter mAdapter; ViewPager mPager; PageIndicator mIndicator; private Button btnHasAccount; private Button btnLoginWithOther; private Handler systemHandler; private BottleTypeTable btt; private BottleNetTypeTable bntt; private OtherConfigTable ot; private LanguageConfigTable languageTablet; private OtherConfigEntry ocEntry; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); AppContext.setContext(this); setContentView(R.layout.splash); btt = new BottleTypeTable(); bntt = new BottleNetTypeTable(); ot = new OtherConfigTable(); languageTablet = new LanguageConfigTable(); registerSystemHandler(); initViewpageFragment(); initWidget(); networkLocat(); TelephonyManager tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); AppContext.getInstance().setDeviceId(tm.getDeviceId()); UICore.getInstance(); init = getIntent().getBooleanExtra("init", false); SharedPreferences preferences = getSharedPreferences("Preferences_config", Activity.MODE_APPEND); int notice = preferences.getInt("notice", 1); if (notice == 1) { Editor editor = getSharedPreferences(BottlePushService.TAG, MODE_PRIVATE).edit(); editor.putString(BottlePushService.PREF_DEVICE_ID, AppContext.getInstance().getDeviceId()); editor.commit(); BottlePushService.actionStart(getApplicationContext()); } if (!init) { UICore.eventTask(this, this, initData, "", null); } } @Override public void execute(int mes, Object obj) { switch (mes) { case initData: initBottleData(); initedConfig(); break; default: break; } } /** * 初始化组件 */ private void initWidget() { btnHasAccount = (Button) findViewById(R.id.splash_has_account); btnHasAccount.setOnClickListener(this); btnLoginWithOther = (Button) findViewById(R.id.splash_login_with_other); btnLoginWithOther.setOnClickListener(this); } private void initViewpageFragment() { mAdapter = new CirclePageFragmentAdapter(getSupportFragmentManager(), this); Bundle bundle = new Bundle(); bundle.putInt("logo", 0); mAdapter.addFragment("", LogoFragment.class, bundle); Bundle bundle1 = new Bundle(); bundle1.putInt("logo", 1); mAdapter.addFragment("", LogoFragment.class, bundle1); Bundle bundle2 = new Bundle(); bundle2.putInt("logo", 2); mAdapter.addFragment("", LogoFragment.class, bundle2); Bundle bundle3 = new Bundle(); bundle3.putInt("logo", 3); mAdapter.addFragment("", LogoFragment.class, bundle3); Bundle bundle4 = new Bundle(); bundle4.putInt("logo", 4); mAdapter.addFragment("", LogoFragment.class, bundle4); mPager = (ViewPager)findViewById(R.id.pager); mPager.setAdapter(mAdapter); mIndicator = (CirclePageIndicator) findViewById(R.id.indicator); mIndicator.setViewPager(mPager); } private void initedConfig() { try { String country = getResources().getConfiguration().locale.getCountry(); if (country.equals("CN")) { AppContext.setLanguage(1); } else { AppContext.setLanguage(0); } SharedPreferences preferences = getSharedPreferences("Preferences_userinfo", Activity.MODE_APPEND); int login_uid = preferences.getInt("login_uid", 0); String login_token = preferences.getString("login_token", null); AppContext.getInstance().setLogin_uid(login_uid); AppContext.getInstance().setLogin_token(login_token); String lastVersion = ocEntry.getLast_android_version(); String localVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName; if (Double.parseDouble(lastVersion) > Double.parseDouble(localVersion)) { Message msg = Message.obtain(systemHandler, new_version, lastVersion); systemHandler.sendMessage(msg); } else { if (login_uid != 0 && login_token != null) { systemHandler.sendEmptyMessage(login); } } } catch (Exception e) { e.printStackTrace(); } } public static class CirclePageFragmentAdapter extends FragmentPagerAdapter { private Context mContext; private final ArrayList<FragmentInfo> fragments = new ArrayList<FragmentInfo>(); protected static final class FragmentInfo { @SuppressWarnings("unused") private final String tag; private final Class<?> clss; private final Bundle args; protected FragmentInfo(String _tag, Class<?> _class, Bundle _args) { tag = _tag; clss = _class; args = _args; } } public CirclePageFragmentAdapter(FragmentManager fm, Context context) { super(fm); this.mContext = context; } public void addFragment(String tag, Class<?> clss, Bundle args) { FragmentInfo fragmentInfo = new FragmentInfo(tag, clss, args); fragments.add(fragmentInfo); } @Override public Fragment getItem(int arg0) { FragmentInfo fragmentInfo = fragments.get(arg0); return Fragment.instantiate(mContext, fragmentInfo.clss.getName(), fragmentInfo.args); } @Override public int getCount() { return fragments.size(); } } private void registerSystemHandler() { systemHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case login: Intent intent = new Intent(SplashActivity.this, HomeActivity.class); startActivity(intent); finish(); break; case new_version: showChoseMes(getString(R.string.new_version_tips) + msg.obj.toString(), 0); break; default: break; } } }; } /** * 初始化瓶子配置信息保存到本地 */ private void initBottleData() { long time = System.currentTimeMillis(); System.out.println("begin>>>>>>>>>>>>>>>>" + 0); String url = UrlConfig.init_config; url += "?sitekey=" + PlatformBindConfig.Sitekey; url += "&clitype=2"; url += "&language=" + AppContext.language; try { String result = HttpUtils.doGet(url); long time1 = System.currentTimeMillis(); System.out.println("got data by http get>>>>>>>>>>>>>>>>" + (time1 - time)); ServiceUtils.dout(result); Gson gson = new Gson(); InitBottleInfo bottleInfo = gson.fromJson(result, InitBottleInfo.class); long time11 = System.currentTimeMillis(); System.out.println("parse json data>>>>>>>>>>>>>>>>" + (time11 - time1)); if (bottleInfo != null) { List<BottleTypeEntry> bottleTypes = bottleInfo.getBttypes_list(); btt.clearTable(); btt.saveBottleType(bottleTypes); long time2 = System.currentTimeMillis(); System.out.println("save bottle type>>>>>>>>>>>>>>>>" + (time2 - time1)); bntt.clearTalbe(); List<BottleNetTypeEntry> bottleNetTypes = bottleInfo.getNettypes_list(); for (BottleNetTypeEntry bottleNetType : bottleNetTypes) { bntt.saveBottleNetType(bottleNetType); } long time3 = System.currentTimeMillis(); System.out.println("save bottle net type>>>>>>>>>>>>>>>>" + (time3 - time2)); ocEntry = bottleInfo.getOther_config(); ot.clearTable(); ot.saveBottleOtherConfig(ocEntry); LanguageConfig languageConfig = bottleInfo.getLanguage_config(); languageTablet.clearTable(); languageTablet.saveBottleLanguageConfig(languageConfig); System.out.println("total time>>>>>>>>>>>>>>>>" + (System.currentTimeMillis() - time)); } } catch (Exception e) { e.printStackTrace(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { showExitTips(); return true; } else { return super.onKeyDown(keyCode, event); } } private void showExitTips() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getString(R.string.logout_home)); builder.setPositiveButton(getString(R.string.confirm_ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { ActivityManager.finishAll(); Process.killProcess(Process.myPid()); System.exit(0); } }); builder.setNegativeButton(getString(R.string.confirm_cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.show(); } @Override public void onClick(View v) { if (v == btnHasAccount) { Intent intent = new Intent(this, LoginActivity.class); startActivity(intent); } else if (v == btnLoginWithOther) { Intent intent = new Intent(this, LoginPlatformActivity.class); startActivity(intent); } } @Override public void sysMesPositiveButtonEvent(int what) { Uri uri = Uri.parse("http://www.mobibottle.com"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); startActivity(intent); } @Override public void sysMesNegativeButtonEvent(int what) { if (AppContext.getInstance().getLogin_uid() != 0 && AppContext.getInstance().getLogin_token() != null) { systemHandler.sendEmptyMessage(login); } } }
Java
package com.outsourcing.bottle.oauth; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; /** * * @author 06peng * */ public class SignatureUtil { public static final String ENCODING = "UTF-8"; /** * 产生签名值 * @param method * @param url * @param params * @param consumerSecret * @param tokenSecret * @return * @throws Exception */ public static String generateSignature(String method, String url, List<Parameter> params, String consumerSecret, String tokenSecret) throws Exception { // 获取源串 String signatureBase = generateSignatureBase(method, url, params); // 构造密钥 String oauthKey = ""; if (null == tokenSecret || tokenSecret.equals("")) { oauthKey = encode(consumerSecret) + "&"; } else { oauthKey = encode(consumerSecret) + "&" + encode(tokenSecret); } // 生成签名值 byte[] encryptBytes = HMAC_SHA1 .HmacSHA1Encrypt(signatureBase, oauthKey); return Base64.encode(encryptBytes); } /** * 构造源串:HTTP请求方式 & urlencode(url) & urlencode(a=x&b=y&...) * @param method * @param url * @param params * @return */ public static String generateSignatureBase(String method, String url, List<Parameter> params) { StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(method.toUpperCase() + "&"); url = encode(url.toLowerCase()); urlBuilder.append(url + "&"); // 所有参数按key进行字典升序排列 Collections.sort(params); for (Parameter param : params) { String name = encode(param.getName()); String value = encode(param.getValue()); urlBuilder.append(name); urlBuilder.append("%3D"); // 字符 = urlBuilder.append(value); urlBuilder.append("%26"); // 字符 & } // 删除末尾的%26 urlBuilder.delete(urlBuilder.length() - 3, urlBuilder.length()); return urlBuilder.toString(); } /** * 参数加密 * @param s * @return */ public static String encode(String s) { if (s == null) { return ""; } String encoded = ""; try { encoded = URLEncoder.encode(s, ENCODING); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(), e); } StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < encoded.length(); i++) { char c = encoded.charAt(i); if (c == '+') { sBuilder.append("%20"); } else if (c == '*') { sBuilder.append("%2A"); } // URLEncoder.encode()会把“~”使用“%7E”表示,因此在这里我们需要变成“~” else if ((c == '%') && ((i + 1) < encoded.length()) && ((i + 2) < encoded.length()) & (encoded.charAt(i + 1) == '7') && (encoded.charAt(i + 2) == 'E')) { sBuilder.append("~"); i += 2; } else { sBuilder.append(c); } } return sBuilder.toString(); } /** * 将加密后的参数拆分 * @param value * @return */ public static String decode(String value) { int nCount = 0; for (int i = 0; i < value.length(); i++) { if (value.charAt(i) == '%') { i += 2; } nCount++; } byte[] sb = new byte[nCount]; for (int i = 0, index = 0; i < value.length(); i++) { if (value.charAt(i) != '%') { sb[index++] = (byte) value.charAt(i); } else { StringBuilder sChar = new StringBuilder(); sChar.append(value.charAt(i + 1)); sChar.append(value.charAt(i + 2)); sb[index++] = Integer.valueOf(sChar.toString(), 16).byteValue(); i += 2; } } String decode = ""; try { decode = new String(sb, "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return decode; } /** * 产生时间戳 * @return */ public static String generateTimeStamp() { return String.valueOf(System.currentTimeMillis() / 1000); } /** * 产生单次值 * @param is32 产生字符串长度是否为32位 * @return */ public static String generateNonce(boolean is32) { Random random = new Random(); // 产生123400至9999999随机数 String result = String.valueOf(random.nextInt(9876599) + 123400); if (is32) { // 进行MD5加密 try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(result.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } result = buf.toString(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } } return result; } public static List<Parameter> getQueryParameters(String queryString) { if (queryString.startsWith("?")) { queryString = queryString.substring(1); } List<Parameter> result = new ArrayList<Parameter>(); if (queryString != null && !queryString.equals("")) { String[] p = queryString.split("&"); for (String s : p) { if (s != null && !s.equals("")) { if (s.indexOf('=') > -1) { String[] temp = s.split("="); result.add(new Parameter(temp[0], temp[1])); } } } } return result; } }
Java
package com.outsourcing.bottle.oauth; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.security.KeyStore; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import oauth.commons.http.CommonsHttpOAuthConsumer; import oauth.commons.http.CommonsHttpOAuthProvider; import oauth.signpost.OAuthConsumer; import oauth.signpost.OAuthProvider; import oauth.signpost.basic.DefaultOAuthConsumer; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import oauth.signpost.exception.OAuthNotAuthorizedException; import oauth.signpost.signature.SSLSocketFactoryEx; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.message.BasicNameValuePair; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.HTTP; import org.json.JSONException; import org.json.JSONObject; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserFactory; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.User; import twitter4j.auth.AccessToken; import twitter4j.auth.RequestToken; import android.annotation.SuppressLint; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import com.outsourcing.bottle.BasicActivity; import com.outsourcing.bottle.R; import com.outsourcing.bottle.db.PlatformAccountTable; import com.outsourcing.bottle.domain.PlatformAccount; import com.outsourcing.bottle.domain.PlatformBindConfig; import com.outsourcing.bottle.domain.UrlConfig; import com.outsourcing.bottle.ui.BindRegisterActivity; import com.outsourcing.bottle.ui.LoginPlatformActivity; import com.outsourcing.bottle.ui.WebViewActivity; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.HttpUtils; import com.outsourcing.bottle.util.ServiceUtils; import com.outsourcing.bottle.util.StringUtil; import com.outsourcing.bottle.util.TextUtil; /** * * @author 06peng * */ public class OAuth { public static final String TAG = OAuth.class.getCanonicalName(); public static final String SIGNATURE_METHOD = "HMAC-SHA1"; public static OAuthConsumer consumer; public static OAuthProvider provider; public String consumerKey; public String consumerSecret; public String oauthTokenSecretForDouban; public String verifier; private String platform; public static VerfierRecivier reciver; private Activity activity; private Handler handler; private PlatformAccount account = null; private Twitter twitter; private RequestToken requestToken; private AccessToken accessTokenTwitter; private String authUrl; private boolean isLoading = false; public OAuth(Activity activity, Handler handler, String platform) { this.activity = activity; this.handler = handler; this.platform = platform; } public OAuth(Activity activity, Handler handler, String platform, String consumerKey, String consumerSecret) { this.activity = activity; this.handler = handler; this.consumerKey = consumerKey; this.consumerSecret = consumerSecret; this.platform = platform; } public String requestAccessToken(String callbackurl, String requestToken, String accessToken, String authorization) { isLoading = true; if (platform.equals(PlatformBindConfig.Douban)) { consumer = new DoubanOAuthConsumer(consumerKey, consumerSecret); provider = new DoubanOAuthProvider(requestToken, accessToken, authorization); } else { consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret); provider = new CommonsHttpOAuthProvider(requestToken, accessToken, authorization); } try { if (platform.equals(PlatformBindConfig.Tencent)) { authUrl = provider.retrieveRequestTokenForTencent(consumer, callbackurl); } else if (platform.equals(PlatformBindConfig.Douban)){ authUrl = provider.retrieveRequestToken(consumer, PlatformBindConfig.Callback); } else { authUrl = provider.retrieveRequestToken(consumer, callbackurl); } } catch (Exception e) { e.printStackTrace(); ((BasicActivity) activity).onToast(activity.getString(R.string.connect_error)); } activity.runOnUiThread(new Runnable() { public void run() { Intent intent = new Intent(); Bundle extras = new Bundle(); extras.putString("url", authUrl); extras.putString("platform", platform); intent.setClass(activity.getApplicationContext(), WebViewActivity.class); intent.putExtras(extras); activity.startActivity(intent); ((BasicActivity) activity).destroyDialog(); IntentFilter filter = new IntentFilter(); filter.addAction("oauth_verifier"); reciver = new VerfierRecivier(); activity.registerReceiver(reciver, filter); } }); return authUrl; } public void requestAcccessTokenForTwitter() { try { isLoading = true; twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(consumerKey, consumerSecret); requestToken = twitter.getOAuthRequestToken(); authUrl = requestToken.getAuthorizationURL(); activity.runOnUiThread(new Runnable() { public void run() { Intent intent = new Intent(); Bundle extras = new Bundle(); extras.putString("url", authUrl); extras.putString("platform", platform); intent.setClass(activity.getApplicationContext(), WebViewActivity.class); intent.putExtras(extras); activity.startActivity(intent); ((BasicActivity) activity).destroyDialog(); IntentFilter filter = new IntentFilter(); filter.addAction("oauth_verifier"); reciver = new VerfierRecivier(); activity.registerReceiver(reciver, filter); } }); } catch (TwitterException e) { activity.runOnUiThread(new Runnable() { @Override public void run() { ((BasicActivity) activity).onToast(activity.getString(R.string.connect_error)); } }); e.printStackTrace(); } } public void requestAccessTokenForOAuth2(final String authUrl) { isLoading = true; activity.runOnUiThread(new Runnable() { public void run() { Intent intent = new Intent(); Bundle extras = new Bundle(); extras.putString("url", authUrl); extras.putString("platform", platform); intent.setClass(activity.getApplicationContext(), WebViewActivity.class); intent.putExtras(extras); activity.startActivity(intent); ((BasicActivity) activity).destroyDialog(); IntentFilter filter = new IntentFilter(); filter.addAction("oauth_verifier"); reciver = new VerfierRecivier(); activity.registerReceiver(reciver, filter); } }); } public void requestToken(String requestTokenUrl, String authorization) { List<Parameter> params = new ArrayList<Parameter>(); params.add(new Parameter("oauth_consumer_key", consumerKey)); params.add(new Parameter("oauth_signature_method", SIGNATURE_METHOD)); params.add(new Parameter("oauth_timestamp", SignatureUtil.generateTimeStamp())); params.add(new Parameter("oauth_nonce", SignatureUtil.generateNonce(false))); String signature; try { signature = SignatureUtil.generateSignature("GET", requestTokenUrl, params, consumerSecret, null); params.add(new Parameter("oauth_signature", signature)); } catch (Exception e) { e.printStackTrace(); } StringBuilder urlBuilder = new StringBuilder(); for (Parameter param : params) { urlBuilder.append(param.getName()); urlBuilder.append("="); urlBuilder.append(param.getValue()); urlBuilder.append("&"); } // 删除最后“&”字符 urlBuilder.deleteCharAt(urlBuilder.length() - 1); try { String url = httpGet(requestTokenUrl, urlBuilder.toString()); oauthTokenSecretForDouban = url.substring(19, url.indexOf("&oauth_token")); String oauthToken = url.substring(url.indexOf("&oauth_token") + 13, url.length()); String oauthUrl = authorization + "?oauth_token=" + oauthToken + "&oauth_callback=" + PlatformBindConfig.Callback; IntentFilter filter = new IntentFilter(); filter.addAction("oauth_verifier"); reciver = new VerfierRecivier(); activity.registerReceiver(reciver, filter); Intent intent = new Intent(); Bundle extras = new Bundle(); extras.putString("url", oauthUrl); intent.setClass(activity.getApplicationContext(), WebViewActivity.class); intent.putExtras(extras); activity.startActivity(intent); } catch (Exception e) { e.printStackTrace(); } } /** * 获取拼接的参数 * * @param httpMethod * @param url * @param token * @param tokenSecret * @param params * @return * @throws Exception */ public String getPostParameter(String httpMethod, String url, String token, String tokenSecret, List<Parameter> params) throws Exception { String urlParams = null; // 添加参数 params.add(new Parameter("oauth_consumer_key", consumerKey)); params.add(new Parameter("oauth_signature_method", SIGNATURE_METHOD)); params.add(new Parameter("oauth_timestamp", SignatureUtil.generateTimeStamp())); params.add(new Parameter("oauth_nonce", SignatureUtil.generateNonce(false))); params.add(new Parameter("oauth_version", "1.0")); if (token != null) { params.add(new Parameter("oauth_token", token)); } String signature = SignatureUtil.generateSignature(httpMethod, url, params, consumerSecret, tokenSecret); params.add(new Parameter("oauth_signature", signature)); // 构造请求参数字符串 StringBuilder urlBuilder = new StringBuilder(); for (Parameter param : params) { urlBuilder.append(param.getName()); urlBuilder.append("="); urlBuilder.append(param.getValue()); urlBuilder.append("&"); } // 删除最后“&”字符 urlBuilder.deleteCharAt(urlBuilder.length() - 1); urlParams = urlBuilder.toString(); return urlParams; } public HttpURLConnection signRequest(String token, String tokenSecret, HttpURLConnection conn) { consumer = new DefaultOAuthConsumer(consumerKey, consumerSecret); consumer.setTokenWithSecret(token, tokenSecret); try { consumer.sign(conn); } catch (OAuthMessageSignerException e1) { e1.printStackTrace(); } catch (OAuthExpectationFailedException e1) { e1.printStackTrace(); } catch (OAuthCommunicationException e1) { e1.printStackTrace(); } try { conn.connect(); } catch (IOException e) { e.printStackTrace(); } return conn; } public HttpResponse signRequest(String token, String tokenSecret, String url, ArrayList<BasicNameValuePair> params) { HttpPost post = new HttpPost(url); try { post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } // 关闭Expect:100-Continue握手 // 100-Continue握手需谨慎使用,因为遇到不支持HTTP/1.1协议的服务器或者代理时会引起问题 post.getParams().setBooleanParameter( CoreProtocolPNames.USE_EXPECT_CONTINUE, false); return signRequest(token, tokenSecret, post); } public HttpResponse signRequest(String token, String tokenSecret, HttpPost post) { consumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret); consumer.setTokenWithSecret(token, tokenSecret); HttpResponse response = null; try { try { consumer.sign(post); } catch (OAuthMessageSignerException e) { e.printStackTrace(); } catch (OAuthExpectationFailedException e) { e.printStackTrace(); } catch (OAuthCommunicationException e) { e.printStackTrace(); } response = (HttpResponse) new DefaultHttpClient().execute(post); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return response; } /** * 通过GET方式发送请求 * * @param url * @param params * @return * @throws Exception */ public String httpGet(String urlPath, String params) throws Exception { String result = null; // 返回信息 if (null != params && !params.equals("")) { urlPath += "?" + params; } Log.i(TAG, "url:" + urlPath); // 构造HttpClient的实例 URL url = new URL(urlPath); HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.setRequestMethod("GET"); request.connect(); System.out.println("response code:" + request.getResponseCode()); if (200 == request.getResponseCode()) { InputStream inputStream = request.getInputStream(); result = new String(ServiceUtils.readStream(inputStream)); } return result; } public String getPostParameterForDouban(String httpMethod, String url, String token, String oauthTokenSecret, List<Parameter> params) throws Exception { String urlParams = null; // 添加参数 params.add(new Parameter("oauth_consumer_key", consumerKey)); params.add(new Parameter("oauth_signature_method", SIGNATURE_METHOD)); params.add(new Parameter("oauth_timestamp", SignatureUtil.generateTimeStamp())); params.add(new Parameter("oauth_nonce", SignatureUtil.generateNonce(false))); if (token != null) { params.add(new Parameter("oauth_token", token)); } String signature = SignatureUtil.generateSignature(httpMethod, url, params, consumerSecret, oauthTokenSecret); params.add(new Parameter("oauth_signature", signature)); // 构造请求参数字符串 StringBuilder urlBuilder = new StringBuilder(); for (Parameter param : params) { urlBuilder.append(param.getName()); urlBuilder.append("="); urlBuilder.append(param.getValue()); urlBuilder.append("&"); } // 删除最后“&”字符 urlBuilder.deleteCharAt(urlBuilder.length() - 1); urlParams = urlBuilder.toString(); return urlParams; } public class VerfierRecivier extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); String accessToken = null; String tokenSecret = null; if (bundle != null && isLoading) { PlatformAccountTable paTable = new PlatformAccountTable(); if (platform.equals(PlatformBindConfig.Renren)) { String code = bundle.getString("code"); account = bindRenren(code); paTable.save(account); bind(); } else if (platform.equals(PlatformBindConfig.Tencent)) { String code = bundle.getString("code"); String openid = bundle.getString("openid"); String openkey = bundle.getString("openkey"); account = bindTencent2(code, openid, openkey); paTable.save(account); bind(); } else if (platform.equals(PlatformBindConfig.Sina)) { String code = bundle.getString("code"); account = bindSina(code); paTable.save(account); bind(); } else if (platform.equals(PlatformBindConfig.QQ)) { String expires = bundle.getString("expires"); String access_token = bundle.getString("accessToken"); account = bindQzone(access_token, expires); paTable.save(account); if (!StringUtil.isBlank(account.getOpenUid()) && !StringUtil.isBlank(account.getAccessToken())) { bind(); } } else if (platform.equals(PlatformBindConfig.Douban)) { provider.setOAuth10a(true); try { provider.retrieveAccessToken(consumer, null); } catch (OAuthMessageSignerException e) { e.printStackTrace(); } catch (OAuthNotAuthorizedException e) { e.printStackTrace(); } catch (OAuthExpectationFailedException e) { e.printStackTrace(); } catch (OAuthCommunicationException e) { e.printStackTrace(); } accessToken = consumer.getToken(); tokenSecret = consumer.getTokenSecret(); account = bindDouban(accessToken, tokenSecret); paTable.save(account); bind(); } else if (platform.equals(PlatformBindConfig.Twitter)) { String pin = bundle.getString("pin"); try { if (pin.length() > 0) { accessTokenTwitter = twitter.getOAuthAccessToken(requestToken, pin); } else { accessTokenTwitter = twitter.getOAuthAccessToken(); } accessToken = accessTokenTwitter.getToken(); tokenSecret = accessTokenTwitter.getTokenSecret(); account = bindTwitter(accessToken, tokenSecret, accessTokenTwitter.getScreenName()); paTable.save(account); bind(); } catch (TwitterException te) { if (401 == te.getStatusCode()) { System.out.println("Unable to get the access token."); } else { te.printStackTrace(); } } } else if (platform.equals(PlatformBindConfig.Facebook)) { String expires = bundle.getString("expires"); String access_token = bundle.getString("accessToken"); account = bindFacebook(access_token, expires); paTable.save(account); bind(); } } isLoading = false; } } @SuppressLint("ParserError") private void bind() { ((BasicActivity) activity).loading(activity.getString(R.string.load_data)); new Thread(){ public void run() { if (StringUtil.isBlank(account.getOpenUid()) || StringUtil.isBlank(account.getAccessToken())) { ((BasicActivity) activity).runOnUiThread(new Runnable() { public void run() { ((BasicActivity) activity).onToast(TextUtil.R("get_user_data_error")); } }); } else { if (StringUtil.isNotBlank(account.getOpenUid())) { checkBind(account); } } }; }.start(); } private void checkBind(PlatformAccount account) { String url = UrlConfig.check_bind; HashMap<String, String> paramsMap = new HashMap<String, String>(); paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid())); paramsMap.put("login_token", AppContext.getInstance().getLogin_token()); paramsMap.put("open_type", String.valueOf(account.getOpenType())); paramsMap.put("access_token", account.getAccessToken()); paramsMap.put("token_secret", account.getTokenSecret()); paramsMap.put("nickname", account.getNickName()); paramsMap.put("open_uid", account.getOpenUid()); paramsMap.put("open_sex", String.valueOf(account.getOpenSex())); paramsMap.put("open_expire", account.getOpenExpire()); paramsMap.put("open_avatar", account.getOpenAvatar()); paramsMap.put("device_token", AppContext.getInstance().getDeviceId()); try { String result = HttpUtils.doPost(activity, url, paramsMap); if (result != null) { JSONObject object = new JSONObject(result); if (object.has("results")) { final JSONObject resultObj = object.getJSONObject("results"); System.out.println(resultObj); int isbind = resultObj.getInt("isbind"); if (AppContext.getInstance().getLogin_uid() != 0 && AppContext.getInstance().getLogin_token() != null) { if (isbind == 1) { System.out.println("oauth open_type:" + account.getOpenType()); if (account.getOpenType() > 0) { AppContext.getInstance().setOAUTH_TYPE(account.getOpenType()); if (handler != null) { handler.sendEmptyMessage(AppContext.oauth_bind); } } else { AppContext.getInstance().setOAUTH_TYPE(-1); } activity.runOnUiThread(new Runnable() { @Override public void run() { ((BasicActivity) activity).destroyDialog(); try { String errmsg = resultObj.getString("errmsg"); if (errmsg != null && !errmsg.equals("")) { ((BasicActivity) activity).onToast(errmsg); } } catch (JSONException e) { e.printStackTrace(); } } }); } else { AppContext.getInstance().setOAUTH_TYPE(-1); Intent intent = new Intent(activity, BindRegisterActivity.class); intent.putExtra("platform", platform); intent.putExtra("openuid", account.getOpenUid()); activity.startActivity(intent); } } else { if (isbind == 0) { if (handler != null) { Message message = Message.obtain(handler, LoginPlatformActivity.NOT_BIND, account.getOpenUid()); handler.sendMessage(message); } } else { int login_uid = resultObj.getInt("login_uid"); String login_token = resultObj.getString("login_token"); SharedPreferences preferences = activity.getSharedPreferences("Preferences_userinfo", Activity.MODE_APPEND); Editor editor = preferences.edit(); editor.putInt("login_uid", login_uid); editor.putString("login_token", login_token); editor.commit(); AppContext.getInstance().setLogin_token(login_token); AppContext.getInstance().setLogin_uid(login_uid); if (handler != null) { handler.sendEmptyMessage(LoginPlatformActivity.HAS_BIND); } } } } } } catch (JSONException e) { e.printStackTrace(); } } private PlatformAccount bindSina(String code) { PlatformAccount account = new PlatformAccount(); String access_url = "https://api.weibo.com/oauth2/access_token"; HttpClient request = getNewHttpClient(); HttpPost httpPost; try { httpPost = new HttpPost(new URI(access_url)); ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(); params.add(new BasicNameValuePair("client_id", PlatformBindConfig.Sina_AppKey)); params.add(new BasicNameValuePair("client_secret", PlatformBindConfig.Sina_AppSecret)); params.add(new BasicNameValuePair("grant_type", "authorization_code")); params.add(new BasicNameValuePair("redirect_uri", PlatformBindConfig.Callback)); params.add(new BasicNameValuePair("code", code)); httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); HttpResponse resposne = request.execute(httpPost); if (200 == resposne.getStatusLine().getStatusCode()) { InputStream inputStream = resposne.getEntity().getContent(); String result = new String(ServiceUtils.readStream(inputStream)); JSONObject obj = new JSONObject(result); String accessToken = obj.getString("access_token"); String expires_in = obj.getString("expires_in"); String uid = obj.getString("uid"); String url = "https://api.weibo.com/2/users/show.json?access_token="+accessToken + "&uid="+uid; HttpGet httpGet = new HttpGet(new URI(url)); resposne = request.execute(httpGet); if (200 == resposne.getStatusLine().getStatusCode()) { inputStream = resposne.getEntity().getContent(); result = new String(ServiceUtils.readStream(inputStream)); JSONObject object = new JSONObject(result); account.setAccessToken(accessToken); account.setNickName(object.getString("screen_name")); account.setOpenAvatar(object.getString("profile_image_url")); String sexStr = object.getString("gender"); int sex = 0; if (sexStr != null) { if (sexStr.equals("m")) { sex = 1; } else if (sexStr.equals("f")) { sex = 2; } else { sex = 0; } } account.setOpenSex(sex); account.setOpenType(1); account.setOpenUid(object.getString("id")); account.setOpenExpire(expires_in); } } } catch (URISyntaxException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return account; } private PlatformAccount bindTencent2(String code, String openid, String openkey) { PlatformAccount account = new PlatformAccount(); String urlPath = PlatformBindConfig.Tencent_Access_Token_2 + code; try { System.out.println("urlpath:" + urlPath); HttpClient request = getNewHttpClient(); HttpGet httpGet = new HttpGet(new URI(urlPath)); HttpResponse resposne = request.execute(httpGet); if (200 == resposne.getStatusLine().getStatusCode()) { InputStream inputStream = resposne.getEntity().getContent(); String result = new String(ServiceUtils.readStream(inputStream)); String access_token = null; String[] results = result.split("&"); for (String str : results) { if (str.indexOf("access_token") != -1) { access_token = str.substring(13); account.setAccessToken(access_token); } else if (str.indexOf("expires_in") != -1) { String expires_in = str.substring(12); account.setOpenExpire(expires_in); } else if (str.indexOf("refresh_token") != -1) { account.setTokenSecret(str.substring(14)); } } account.setOpenType(2); String url = "https://open.t.qq.com/api/user/info?oauth_consumer_key="+PlatformBindConfig.Tencent_AppKey+"" + "&access_token="+access_token+"&openid="+openid+"&clientip=10.0.0.2&oauth_version=2.a&scope=all"; httpGet = new HttpGet(new URI(url)); resposne = request.execute(httpGet); if (200 == resposne.getStatusLine().getStatusCode()) { inputStream = resposne.getEntity().getContent(); result = new String(ServiceUtils.readStream(inputStream)); JSONObject object = new JSONObject(result); JSONObject resultObj = object.getJSONObject("data"); account.setNickName(resultObj.getString("nick")); account.setOpenAvatar(resultObj.getString("head")); account.setOpenSex(resultObj.getInt("sex")); account.setOpenUid(resultObj.getString("openid")); } } } catch (Exception e) { e.printStackTrace(); } return account; } private PlatformAccount bindRenren(String code) { PlatformAccount account = new PlatformAccount(); try { String urlPath = PlatformBindConfig.Renren_Token; URL url = new URL(urlPath); HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.setDoOutput(true); OutputStream out = request.getOutputStream(); String grant_type = "grant_type=authorization_code"; String client_id = "&client_id=" + PlatformBindConfig.Renren_AppKey; String client_secret = "&client_secret=" + PlatformBindConfig.Renren_AppSecret; String redirect_uri = "&redirect_uri=" + PlatformBindConfig.Renren_Callback; code = "&code=" + code; out.write((grant_type + code + client_id + client_secret + redirect_uri).getBytes()); out.flush(); request.connect(); if (200 == request.getResponseCode()) { InputStream inputStream = request.getInputStream(); String result = new String(ServiceUtils.readStream(inputStream)); System.out.println("---------renren--------" + result); JSONObject object = new JSONObject(result); String openExpire = object.getString("expires_in"); account.setOpenExpire(openExpire); String refresh_token = object.getString("refresh_token"); account.setTokenSecret(refresh_token); String access_token = object.getString("access_token"); account.setAccessToken(access_token); JSONObject userObject = object.getJSONObject("user"); account.setOpenUid(userObject.getString("id")); account.setNickName(userObject.getString("name")); account.setOpenType(3); if (userObject.has("avatar")) { JSONObject avatarObject = userObject.getJSONObject("avatar"); if (avatarObject.getString("type").equals("avatar")) { account.setOpenAvatar(avatarObject.getString("url")); } } } } catch (Exception e) { e.printStackTrace(); } return account; } private PlatformAccount bindQzone(String accessToken, String expires) { PlatformAccount account = new PlatformAccount(); String urlPath = "https://graph.qq.com/oauth2.0/me?access_token=" + accessToken; try { HttpClient request = getNewHttpClient(); HttpGet httpGet = new HttpGet(new URI(urlPath)); HttpResponse resposne = request.execute(httpGet); if (200 == resposne.getStatusLine().getStatusCode()) { InputStream inputStream = resposne.getEntity().getContent(); String result = new String(ServiceUtils.readStream(inputStream)); System.out.println(">>>>>>>>>>>>>>>>" + result); result = result.substring(result.indexOf("(") + 1, result.indexOf(")")); JSONObject object = new JSONObject(result); // String client_id = object.getString("client_id"); if (object.has("openid")) { String openid = object.getString("openid"); account.setOpenUid(openid); account.setAccessToken(accessToken); account.setOpenType(0); String userUrl = "https://graph.qq.com/user/get_user_info?access_token=" + accessToken + "&oauth_consumer_key=" + PlatformBindConfig.QQ_AppKey + "&openid=" + openid; httpGet = new HttpGet(new URI(userUrl)); resposne = request.execute(httpGet); if (200 == resposne.getStatusLine().getStatusCode()) { inputStream = resposne.getEntity().getContent(); result = new String(ServiceUtils.readStream(inputStream)); object = new JSONObject(result); account.setNickName(object.getString("nickname")); account.setOpenAvatar(object.getString("figureurl")); } } } } catch (Exception e) { e.printStackTrace(); } return account; } private PlatformAccount bindDouban(String accessToken, String tokenSecret) { PlatformAccount account = null; String urlPath = "http://api.douban.com/people/%40me"; consumer = new DoubanOAuthConsumer(consumerKey, consumerSecret); consumer.setTokenWithSecret(accessToken, tokenSecret); HttpURLConnection conn = null; try { URL url = new URL(urlPath); conn = (HttpURLConnection) url.openConnection(); consumer.sign(conn); account = parseXml(conn.getInputStream()); account.setOpenType(4); account.setAccessToken(accessToken); account.setTokenSecret(tokenSecret); } catch (OAuthMessageSignerException e1) { e1.printStackTrace(); } catch (OAuthExpectationFailedException e1) { e1.printStackTrace(); } catch (OAuthCommunicationException e1) { e1.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return account; } private PlatformAccount bindTwitter(String accessToken, String tokenSecret, String screenName) { PlatformAccount account = null; try { account = new PlatformAccount(); User user = twitter.showUser(screenName); account.setAccessToken(accessToken); account.setTokenSecret(tokenSecret); account.setNickName(user.getScreenName()); if (user.getProfileImageURL() != null) { account.setOpenAvatar(user.getProfileImageURL().toString().replace("_normal", "")); } account.setOpenUid(String.valueOf(user.getId())); account.setOpenType(5); } catch (TwitterException e) { e.printStackTrace(); } return account; } private PlatformAccount bindFacebook(String accessToken, String expires) { PlatformAccount account = new PlatformAccount(); String urlPath = "https://graph.facebook.com/me?fields=picture,id,name,username,gender&access_token=" + accessToken; try { HttpClient request = getNewHttpClient(); HttpGet httpGet = new HttpGet(new URI(urlPath)); HttpResponse resposne = request.execute(httpGet); System.out.println(resposne.getStatusLine().getStatusCode()); if (200 == resposne.getStatusLine().getStatusCode()) { InputStream inputStream = resposne.getEntity().getContent(); String result = new String(ServiceUtils.readStream(inputStream)); System.out.println(result); JSONObject resultObj = new JSONObject(result); account.setAccessToken(accessToken); account.setNickName(resultObj.getString("username")); account.setOpenAvatar(resultObj.getString("picture")); account.setOpenExpire(expires); account.setOpenType(6); account.setOpenUid(resultObj.getString("id")); } } catch (Exception e) { e.printStackTrace(); } return account; } public HttpClient getNewHttpClient() { try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sf, 443)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); return new DefaultHttpClient(ccm, params); } catch (Exception e) { return new DefaultHttpClient(); } } /** * 解析xml * * @param is */ private PlatformAccount parseXml(InputStream is) { PlatformAccount account = null; try { XmlPullParserFactory xmlPullParserFactory = XmlPullParserFactory.newInstance(); XmlPullParser parser = xmlPullParserFactory.newPullParser(); // 设置输入流以及编码方式 parser.setInput(is, "UTF-8"); // 获取当前的事件类型 int eventType = parser.getEventType(); while (XmlPullParser.END_DOCUMENT != eventType) { String nodeName = parser.getName(); switch (eventType) { case XmlPullParser.START_DOCUMENT: break; case XmlPullParser.START_TAG: if (nodeName.equalsIgnoreCase("entry")) { account = new PlatformAccount(); } if (nodeName.equalsIgnoreCase("title")) { account.setNickName(parser.nextText()); } if (nodeName.equalsIgnoreCase("db:uid")) { account.setOpenUid(parser.nextText()); } if (nodeName.equalsIgnoreCase("link")) { if (parser.getAttributeValue(1).equalsIgnoreCase("icon")) { account.setOpenAvatar(parser.getAttributeValue(0)); } } break; case XmlPullParser.END_TAG: break; default: break; } // 手动的触发下一个事件 eventType = parser.next(); Log.i("OAuth", eventType + ""); } } catch (Exception e) { e.printStackTrace(); } return account; } }
Java
package com.outsourcing.bottle.oauth; import java.io.UnsupportedEncodingException; /** * * @author 06peng * */ public class Base64 { private static char[] base64EncodeChars = new char[] { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; private static byte[] base64DecodeChars = new byte[] { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1 }; public static String encode(byte[] data) { StringBuffer sb = new StringBuffer(); int len = data.length; int i = 0; int b1, b2, b3; while (i < len) { b1 = data[i++] & 0xff; if (i == len) { sb.append(base64EncodeChars[b1 >>> 2]); sb.append(base64EncodeChars[(b1 & 0x3) << 4]); sb.append("=="); break; } b2 = data[i++] & 0xff; if (i == len) { sb.append(base64EncodeChars[b1 >>> 2]); sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]); sb.append(base64EncodeChars[(b2 & 0x0f) << 2]); sb.append("="); break; } b3 = data[i++] & 0xff; sb.append(base64EncodeChars[b1 >>> 2]); sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]); sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]); sb.append(base64EncodeChars[b3 & 0x3f]); } return sb.toString(); } public static byte[] decode(String str) throws UnsupportedEncodingException { StringBuffer sb = new StringBuffer(); byte[] data = str.getBytes("US-ASCII"); int len = data.length; int i = 0; int b1, b2, b3, b4; while (i < len) { /* b1 */ do { b1 = base64DecodeChars[data[i++]]; } while (i < len && b1 == -1); if (b1 == -1) break; /* b2 */ do { b2 = base64DecodeChars[data[i++]]; } while (i < len && b2 == -1); if (b2 == -1) break; sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4))); /* b3 */ do { b3 = data[i++]; if (b3 == 61) return sb.toString().getBytes("iso8859-1"); b3 = base64DecodeChars[b3]; } while (i < len && b3 == -1); if (b3 == -1) break; sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2))); /* b4 */ do { b4 = data[i++]; if (b4 == 61) return sb.toString().getBytes("iso8859-1"); b4 = base64DecodeChars[b4]; } while (i < len && b4 == -1); if (b4 == -1) break; sb.append((char) (((b3 & 0x03) << 6) | b4)); } return sb.toString().getBytes("iso8859-1"); } }
Java
package com.outsourcing.bottle.oauth; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import oauth.signpost.OAuthConsumer; import oauth.signpost.basic.DefaultOAuthProvider; import oauth.signpost.basic.HttpURLConnectionResponseAdapter; import oauth.signpost.exception.OAuthCommunicationException; import oauth.signpost.exception.OAuthExpectationFailedException; import oauth.signpost.exception.OAuthMessageSignerException; import oauth.signpost.exception.OAuthNotAuthorizedException; import oauth.signpost.http.HttpParameters; import oauth.signpost.http.HttpResponse; /** * * @author 06peng * */ public class DoubanOAuthProvider extends DefaultOAuthProvider { /** * */ private static final long serialVersionUID = 1L; private static final String MAC_NAME = "HmacSHA1"; public DoubanOAuthProvider(String requestTokenEndpointUrl, String accessTokenEndpointUrl, String authorizationWebsiteUrl) { super(requestTokenEndpointUrl, accessTokenEndpointUrl, authorizationWebsiteUrl); } @Override protected void retrieveToken(OAuthConsumer consumer, String endpointUrl, String... additionalParameters) throws OAuthMessageSignerException, OAuthCommunicationException, OAuthNotAuthorizedException, OAuthExpectationFailedException { if (consumer.getConsumerKey() == null || consumer.getConsumerSecret() == null) { throw new OAuthExpectationFailedException("Consumer key or secret not set"); } HttpURLConnection connection = null; HttpResponse response = null; String requestMethod = "GET"; try { String tokenSecet = consumer.getTokenSecret(); if(tokenSecet == null) { tokenSecet = ""; } HashMap<String, String> query = new HashMap<String, String>(); query.put(oauth.signpost.OAuth.OAUTH_CONSUMER_KEY, consumer.getConsumerKey()); query.put(oauth.signpost.OAuth.OAUTH_SIGNATURE_METHOD, "HMAC-SHA1"); query.put(oauth.signpost.OAuth.OAUTH_TIMESTAMP, Long.toString(System.currentTimeMillis() / 1000L)); query.put(oauth.signpost.OAuth.OAUTH_NONCE, Long.toString(new Random().nextLong())); if(additionalParameters != null && additionalParameters.length > 0 && additionalParameters[0].equals(oauth.signpost.OAuth.OAUTH_CALLBACK)) { // no-op } else { query.put(oauth.signpost.OAuth.OAUTH_TOKEN, consumer.getToken()); } query.put(oauth.signpost.OAuth.OAUTH_SIGNATURE, getSignature(consumer.getConsumerKey(), consumer.getConsumerSecret(), tokenSecet, requestMethod, endpointUrl, query )); StringBuilder sb = new StringBuilder(endpointUrl); sb.append("?"); boolean first = true; for(Entry<String, String> entry: query.entrySet()) { if(!first) { sb.append("&"); } first = false; sb.append(oauth.signpost.OAuth.percentEncode(entry.getKey())) .append("=").append(oauth.signpost.OAuth.percentEncode(entry.getValue())); } connection = (HttpURLConnection) new URL(sb.toString()).openConnection(); connection.setRequestMethod(requestMethod); connection.setAllowUserInteraction(false); //connection.setRequestProperty("Content-Length", "0"); connection.connect(); response = new HttpURLConnectionResponseAdapter(connection); int statusCode = response.getStatusCode(); boolean requestHandled = false; if (requestHandled) { return; } if (statusCode >= 300) { handleUnexpectedResponse(statusCode, response); } HttpParameters responseParams = oauth.signpost.OAuth.decodeForm(response.getContent()); String token = responseParams.getFirst(oauth.signpost.OAuth.OAUTH_TOKEN); String secret = responseParams.getFirst(oauth.signpost.OAuth.OAUTH_TOKEN_SECRET); responseParams.remove(oauth.signpost.OAuth.OAUTH_TOKEN); responseParams.remove(oauth.signpost.OAuth.OAUTH_TOKEN_SECRET); setResponseParameters(responseParams); if (token == null || secret == null) { throw new OAuthExpectationFailedException( "Request token or token secret not set in server reply. " + "The service provider you use is probably buggy."); } consumer.setTokenWithSecret(token, secret); } catch (OAuthNotAuthorizedException e) { throw e; } catch (OAuthExpectationFailedException e) { throw e; } catch (Exception e) { throw new OAuthCommunicationException(e); } finally { try { if(connection != null) { connection.disconnect(); } } catch (Exception e) { throw new OAuthCommunicationException(e); } } } private String getSignature(String consumerKey, String consumerSecret, String tokenSecret, String method, String url, Map<String, String> query) throws OAuthMessageSignerException { try { String keyString = oauth.signpost.OAuth.percentEncode(consumerSecret) + '&' + oauth.signpost.OAuth.percentEncode(tokenSecret); byte[] keyBytes = keyString.getBytes(oauth.signpost.OAuth.ENCODING); SecretKey key = new SecretKeySpec(keyBytes, MAC_NAME); Mac mac = Mac.getInstance(MAC_NAME); mac.init(key); String sbs = getSignatureBaseString(method, url, query); oauth.signpost.OAuth.debugOut("SBS", sbs); byte[] text = sbs.getBytes(oauth.signpost.OAuth.ENCODING); return new String(Base64.encode(mac.doFinal(text))); } catch (GeneralSecurityException e) { throw new OAuthMessageSignerException(e); } catch (UnsupportedEncodingException e) { throw new OAuthMessageSignerException(e); } } private String getSignatureBaseString(String method, String url, Map<String, String> query) throws OAuthMessageSignerException { try { String normalizedUrl = normalizeRequestUrl(url); String normalizedParams = normalizeRequestParameters(query); return method + '&' + oauth.signpost.OAuth.percentEncode(normalizedUrl) + '&' + oauth.signpost.OAuth.percentEncode(normalizedParams); } catch (Exception e) { throw new OAuthMessageSignerException(e); } } private String normalizeRequestParameters(Map<String, String> query) { if (query == null) { return ""; } StringBuilder sb = new StringBuilder(); List<String> keys = new ArrayList<String>(query.keySet()); Collections.sort(keys); boolean first = true; for (String key: keys) { if (oauth.signpost.OAuth.OAUTH_SIGNATURE.equals(key) || "realm".equals(key)) { continue; } if(!first) { sb.append("&"); } first = false; sb.append(oauth.signpost.OAuth.percentEncode(key)).append('=').append(oauth.signpost.OAuth.percentEncode(query.get(key))); } return sb.toString(); } private String normalizeRequestUrl(String url) throws URISyntaxException { URI uri = new URI(url); String scheme = uri.getScheme().toLowerCase(); String authority = uri.getAuthority().toLowerCase(); boolean dropPort = (scheme.equals("http") && uri.getPort() == 80) || (scheme.equals("https") && uri.getPort() == 443); if (dropPort) { // find the last : in the authority int index = authority.lastIndexOf(":"); if (index >= 0) { authority = authority.substring(0, index); } } String path = uri.getRawPath(); if (path == null || path.length() <= 0) { path = "/"; // conforms to RFC 2616 section 3.2.2 } // we know that there is no query and no fragment here. return scheme + "://" + authority + path; } }
Java
package com.outsourcing.bottle.oauth; import java.io.Serializable; /** * * @author 06peng * */ public class Parameter implements Serializable, Comparable<Parameter> { private static final long serialVersionUID = 1L; private String name; private String value; public Parameter() { super(); } public Parameter(String name, String value) { super(); this.name = name; this.value = value; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public String toString() { return "Parameter [name=" + name + ", value=" + value + "]"; } @Override public boolean equals(Object arg0) { if (null == arg0) { return false; } if (this == arg0) { return true; } if (arg0 instanceof Parameter) { Parameter param = (Parameter) arg0; return this.getName().equals(param.getName()) && this.getValue().equals(param.getValue()); } return false; } @Override public int compareTo(Parameter param) { int compared; compared = name.compareTo(param.getName()); if (0 == compared) { compared = value.compareTo(param.getValue()); } return compared; } }
Java
package com.outsourcing.bottle.oauth; import oauth.signpost.basic.DefaultOAuthConsumer; import oauth.signpost.http.HttpParameters; /** * * @author 06peng * */ public class DoubanOAuthConsumer extends DefaultOAuthConsumer { /** * */ private static final long serialVersionUID = 1L; public DoubanOAuthConsumer(String consumerKey, String consumerSecret) { super(consumerKey, consumerSecret); HttpParameters parameters = new HttpParameters(); parameters.put("realm", ""); setAdditionalParameters(parameters); } }
Java
package com.outsourcing.bottle.oauth; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; /** * * @author 06peng * */ public class HMAC_SHA1 { private static final String MAC_NAME = "HmacSHA1"; private static final String ENCODING = "US-ASCII"; /** * 使用 HMAC-SHA1 签名方法对对encryptText进行签名 * @param encryptText 被签名的字符串 * @param encryptKey 密钥 * @return * @throws NoSuchAlgorithmException * @throws UnsupportedEncodingException * @throws InvalidKeyException * @see <a href = * "http://tools.ietf.org/html/draft-hammer-oauth-10#section-3.4.2">HMAC-SHA1</a> */ public static byte[] HmacSHA1Encrypt(String encryptText, String encryptKey) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException { Mac mac = Mac.getInstance(MAC_NAME); SecretKeySpec spec = new SecretKeySpec(encryptKey.getBytes("US-ASCII"), MAC_NAME); mac.init(spec); byte[] text = encryptText.getBytes(ENCODING); return mac.doFinal(text); } }
Java
/* * Copyright (C) 2009 Teleca Poland Sp. z o.o. <android@teleca.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.outsourcing.bottle.remoteimage; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.util.AttributeSet; import android.widget.AbsListView; import android.widget.ImageView; import com.outsourcing.bottle.util.BottleApplication; /** * ImageView extended class allowing easy downloading of remote images * * @author Lukasz Wisniewski */ public class RemoteImageView extends ImageView { /** * Maximum number of unsuccesful tries of downloading an image */ private static int MAX_FAILURES = 3; public RemoteImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public RemoteImageView(Context context, AttributeSet attrs) { super(context, attrs); } public RemoteImageView(Context context) { super(context); } /** * Remote image location */ private String mUrl; /** * Currently successfully grabbed url */ private String mCurrentlyGrabbedUrl; /** * Remote image download failure counter */ private int mFailure; /** * Position of the image in the mListView */ private int mPosition; /** * ListView containg this image */ private AbsListView mListView; /** * Default image shown while loading or on url not found */ private Integer mDefaultImage; public void setImagePath(String url) { setImageUrl(url); } /** * Loads image from remote location * * @param url * eg. http://random.com/abz.jpg */ public void setImageUrl(String url) { if (mUrl != null && mUrl.equals(url) && (mCurrentlyGrabbedUrl == null || (mCurrentlyGrabbedUrl != null && !mCurrentlyGrabbedUrl.equals(url)))) { mFailure++; if (mFailure > MAX_FAILURES) { loadDefaultImage(); return; } } else { mUrl = url; mFailure = 0; } new DownloadTask().execute(url); } /** * Sets default local image shown when remote one is unavailable * * @param resid */ public void setDefaultImage(Integer resid) { mDefaultImage = resid; } /** * Loads default image */ private void loadDefaultImage() { if (mDefaultImage != null) setImageResource(mDefaultImage); } /** * Loads image from remote location in the ListView * * @param url * eg. http://random.com/abz.jpg * @param position * ListView position where the image is nested * @param listView * ListView to which this image belongs */ public void setImageUrl(String url, int position, AbsListView listView) { mPosition = position; mListView = listView; setImageUrl(url); } /** * Asynchronous image download task * * @author Lukasz Wisniewski */ class DownloadTask extends AsyncTask<String, Void, String> { private String mTaskUrl; @Override public void onPreExecute() { loadDefaultImage(); super.onPreExecute(); } @Override public String doInBackground(String... params) { mTaskUrl = params[0]; InputStream stream = null; URL imageUrl; Bitmap bmp = null; try { imageUrl = new URL(mTaskUrl); try { stream = imageUrl.openStream(); bmp = BitmapFactory.decodeStream(stream); try { if (bmp != null) { BottleApplication.getInstance().getImageCache().put(mTaskUrl, bmp); } } catch (NullPointerException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (stream != null) { stream.close(); } } catch (IOException e) { e.printStackTrace(); } } } catch (MalformedURLException e) { e.printStackTrace(); } return mTaskUrl; } @Override public void onPostExecute(String url) { super.onPostExecute(url); Bitmap bmp = BottleApplication.getInstance().getImageCache().get(url); if (bmp == null) { RemoteImageView.this.setImageUrl(url); } else { // if image belongs to a list update it only if it's visible if (mListView != null) if (mPosition < mListView.getFirstVisiblePosition() || mPosition > mListView.getLastVisiblePosition()) return; RemoteImageView.this.setImageBitmap(bmp); mCurrentlyGrabbedUrl = url; } } }; }
Java
/* * Copyright (C) 2009 Teleca Poland Sp. z o.o. <android@teleca.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.outsourcing.bottle.remoteimage; import java.util.ArrayList; import android.app.Activity; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.BaseAdapter; /** * Nice wrapper-abstraction around ArrayList * * @author Lukasz Wisniewski * * @param <T> */ public abstract class ArrayListAdapter<T> extends BaseAdapter{ protected ArrayList<T> mList; protected Activity mContext; protected AbsListView mListView; public ArrayListAdapter(Activity context){ this.mContext = context; } @Override public int getCount() { if(mList != null) return mList.size(); else return 0; } @Override public Object getItem(int position) { return mList == null ? null : mList.get(position); } @Override public long getItemId(int position) { return position; } @Override abstract public View getView(int position, View convertView, ViewGroup parent); public void setList(ArrayList<T> list){ this.mList = list; notifyDataSetChanged(); } public ArrayList<T> getList(){ return mList; } public void setList(T[] list){ ArrayList<T> arrayList = new ArrayList<T>(list.length); for (T t : list) { arrayList.add(t); } setList(arrayList); } public AbsListView getListView(){ return mListView; } public void setListView(AbsListView listView){ mListView = listView; } }
Java
/* * Copyright (C) 2009 Teleca Poland Sp. z o.o. <android@teleca.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.outsourcing.bottle.remoteimage; import java.util.WeakHashMap; import android.graphics.Bitmap; /** * Caches downloaded images, saves bandwidth and user's * packets * * @author Lukasz Wisniewski */ public class ImageCache extends WeakHashMap<String, Bitmap> { public boolean isCached(String url){ return containsKey(url) && get(url) != null; } }
Java
package com.outsourcing.bottle; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.outsourcing.bottle.util.BottlePushService; /** * * @author 06peng * */ public class BootBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_BOOT_COMPLETED) || action.equals("android.intent.action.QUICKBOOT_POWERON")) { try { BottlePushService.actionStart(context); } catch (Exception e) { e.printStackTrace(); } } } }
Java
package com.outsourcing.bottle.widget; import android.content.Context; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.MotionEvent; import android.widget.Gallery; public class CustomGallery extends Gallery { public CustomGallery(Context context, AttributeSet attrSet) { super(context, attrSet); } private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2) { return e2.getX() > e1.getX(); } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { int kEvent; if (isScrollingLeft(e1, e2)) { // Check if scrolling left kEvent = KeyEvent.KEYCODE_DPAD_LEFT; } else { // Otherwise scrolling right kEvent = KeyEvent.KEYCODE_DPAD_RIGHT; } onKeyDown(kEvent, null); return true; } }
Java
package com.outsourcing.bottle.widget; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.ScrollView; import android.widget.Scroller; import android.widget.TextView; import com.outsourcing.bottle.R; import com.outsourcing.bottle.util.ServiceUtils; /** * */ public class TryRefreshableView extends LinearLayout { private static final int TAP_TO_REFRESH = 1; // 初始状态 private static final int PULL_TO_REFRESH = 2; // 拉动刷新 private static final int RELEASE_TO_REFRESH = 3; // 释放刷新 private static final int REFRESHING = 4; // 正在刷新 public int mRefreshState;// 记录头当前状态 public int mfooterRefreshState;//记录尾当前状态 public Scroller scroller; public ScrollView sv; private View refreshView;//头部视图 public View mfooterView;// 尾部视图 public TextView mfooterViewText; private ImageView refreshIndicatorView; private int refreshTargetTop = -70; public int refreshFooter; private ProgressBar bar; private TextView downTextView; private TextView timeTextView; private RefreshListener refreshListener; private int lastY; // 动画效果 // 变为向下的箭头 private RotateAnimation mFlipAnimation; // 变为逆向的箭头 private RotateAnimation mReverseFlipAnimation; public int nowpull = -1;// 0为头部下拉,1为尾部上拉 private boolean isRecord; private Context mContext; public TryRefreshableView(Context context) { super(context); mContext = context; } public TryRefreshableView(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; init(); } private void init() { // 初始化动画 // mFlipAnimation = new RotateAnimation(0, -180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); mFlipAnimation.setInterpolator(new LinearInterpolator()); mFlipAnimation.setDuration(250); mFlipAnimation.setFillAfter(true); mReverseFlipAnimation = new RotateAnimation(-180, 0, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); mReverseFlipAnimation.setInterpolator(new LinearInterpolator()); mReverseFlipAnimation.setDuration(250); mReverseFlipAnimation.setFillAfter(true); // 滑动对象, scroller = new Scroller(mContext); // 刷新视图顶端的的view refreshView = LayoutInflater.from(mContext).inflate( R.layout.pull_to_refresh_header_scroll, null); //箭头图标 refreshIndicatorView = (ImageView) refreshView .findViewById(R.id.pull_to_refresh_image); // 刷新bar bar = (ProgressBar) refreshView .findViewById(R.id.pull_to_refresh_progress); // 下拉显示text downTextView = (TextView) refreshView .findViewById(R.id.pull_to_refresh_text); // 下来显示时间 timeTextView = (TextView) refreshView .findViewById(R.id.pull_to_refresh_updated_at); //添加头部view refreshView.setMinimumHeight(50); LayoutParams lp = new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT, -refreshTargetTop); lp.topMargin = refreshTargetTop; lp.gravity = Gravity.CENTER; addView(refreshView, lp); isRecord = false; mRefreshState = TAP_TO_REFRESH; mfooterRefreshState = TAP_TO_REFRESH; } public boolean onTouchEvent(MotionEvent event) { int y = (int) event.getRawY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // 记录下y坐标 if (isRecord == false) { Log.i("moveY", "lastY:" + y); lastY = y; isRecord = true; } break; case MotionEvent.ACTION_MOVE: Log.i("TAG", "ACTION_MOVE"); // y移动坐标 Log.i("moveY", "lastY:" + lastY); Log.i("moveY", "y:" + y); int m = y - lastY; doMovement(m); // 记录下此刻y坐标 lastY = y; break; case MotionEvent.ACTION_UP: Log.i("TAG", "ACTION_UP"); fling(); isRecord = false; break; } return true; } /** * up事件处理 */ private void fling() { // TODO Auto-generated method stub if (nowpull == 0 && mRefreshState != REFRESHING) { LinearLayout.LayoutParams lp = (LayoutParams) refreshView .getLayoutParams(); Log.i("TAG", "fling()" + lp.topMargin); if (lp.topMargin > 0) {// 拉到了触发可刷新事件 refresh(); } else { returnInitState(); } } else if (nowpull == 1 && mfooterRefreshState != REFRESHING) { if (refreshFooter >= 20 && mfooterRefreshState == RELEASE_TO_REFRESH) { mfooterRefreshState = REFRESHING; FooterPrepareForRefresh(); // 准备刷新 onRefresh(); // 刷新 } else { if (refreshFooter>=0) resetFooterPadding(); else { resetFooterPadding(); mfooterRefreshState = TAP_TO_REFRESH; Log.i("other","i::"+refreshFooter); TryPullToRefreshScrollView.ScrollToPoint(sv, sv.getChildAt(0),-refreshFooter); } } } } // 刷新 public void onRefresh() { Log.d("TAG", "执行刷新"); if (refreshListener != null) { refreshListener.onRefresh(); } } private void returnInitState() { mRefreshState = TAP_TO_REFRESH; LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) this.refreshView .getLayoutParams(); int i = lp.topMargin; scroller.startScroll(0, i, 0, refreshTargetTop); invalidate(); } private void refresh() { mRefreshState = REFRESHING; LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) this.refreshView .getLayoutParams(); int i = lp.topMargin; refreshIndicatorView.setVisibility(View.GONE); refreshIndicatorView.setImageDrawable(null); bar.setVisibility(View.VISIBLE); timeTextView.setVisibility(View.GONE); downTextView.setText(R.string.pull_to_refresh_refreshing_label); scroller.startScroll(0, i, 0, 0 - i); invalidate(); if (refreshListener != null) { refreshListener.onRefresh(); } } private void resetFooterPadding() { LayoutParams svlp = (LayoutParams) sv.getLayoutParams(); svlp.bottomMargin=0; sv.setLayoutParams(svlp); TryPullToRefreshScrollView.ScrollToPoint(sv, sv.getChildAt(0),0); } public void FooterPrepareForRefresh() { resetFooterPadding(); mfooterViewText .setText(R.string.pull_to_refresh_footer_refreshing_label); mfooterRefreshState = REFRESHING; } /** * */ @Override public void computeScroll() { if (scroller.computeScrollOffset()) { int i = this.scroller.getCurrY(); LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) this.refreshView .getLayoutParams(); int k = Math.max(i, refreshTargetTop); lp.topMargin = k; this.refreshView.setLayoutParams(lp); this.refreshView.invalidate(); invalidate(); } } /** * 下拉move事件处理 * * @param moveY */ public void doMovement(int moveY) { LinearLayout.LayoutParams lp = (LayoutParams) refreshView .getLayoutParams(); if(sv.getScrollY() == 0 && moveY > 0&&refreshFooter<=0) { nowpull=0; } if(sv.getChildAt(0).getMeasuredHeight() <= sv.getScrollY() + getHeight() && moveY < 0&&lp.topMargin<=refreshTargetTop) { nowpull=1; } if (nowpull == 0 && mRefreshState != REFRESHING) { // 获取view的上边距 float f1 = lp.topMargin; float f2 = f1 + moveY * 0.3F; int i = (int) f2; // 修改上边距 lp.topMargin = i; // 修改后刷新 refreshView.setLayoutParams(lp); refreshView.invalidate(); invalidate(); downTextView.setVisibility(View.VISIBLE); refreshIndicatorView.setVisibility(View.VISIBLE); bar.setVisibility(View.GONE); if (lp.topMargin > 0 && mRefreshState != RELEASE_TO_REFRESH) { downTextView.setText(R.string.refresh_release_text); // refreshIndicatorView.setImageResource(R.drawable.goicon); refreshIndicatorView.clearAnimation(); refreshIndicatorView.startAnimation(mFlipAnimation); mRefreshState = RELEASE_TO_REFRESH; Log.i("TAG", "现在处于下拉状态"); } else if (lp.topMargin <= 0 && mRefreshState != PULL_TO_REFRESH) { downTextView.setText(R.string.refresh_down_text); // refreshIndicatorView.setImageResource(R.drawable.goicon); if (mRefreshState != TAP_TO_REFRESH) { refreshIndicatorView.clearAnimation(); refreshIndicatorView.startAnimation(mReverseFlipAnimation); Log.i("TAG", "现在处于回弹状态"); } mRefreshState = PULL_TO_REFRESH; } } else if (nowpull == 1 && mfooterRefreshState != REFRESHING) { LayoutParams svlp = (LayoutParams) sv.getLayoutParams(); svlp.bottomMargin=svlp.bottomMargin-moveY; Log.i("other","svlp.bottomMargin::"+svlp.bottomMargin); refreshFooter=svlp.bottomMargin; sv.setLayoutParams(svlp); TryPullToRefreshScrollView.ScrollToPoint(sv, sv.getChildAt(0),0); if (svlp.bottomMargin >= 20 && mfooterRefreshState != RELEASE_TO_REFRESH) { mfooterViewText.setText(R.string.pull_to_refresh_footer_label); mfooterRefreshState = RELEASE_TO_REFRESH; } else if (svlp.bottomMargin < 20 && mfooterRefreshState != PULL_TO_REFRESH) { mfooterViewText .setText(R.string.pull_to_refresh_footer_pull_label); mfooterRefreshState = PULL_TO_REFRESH; } } } public void setRefreshListener(RefreshListener listener) { this.refreshListener = listener; } /** * 结束刷新事件 */ public void finishRefresh() { Log.i("TAG", "执行了=====finishRefresh"); if (mRefreshState != TAP_TO_REFRESH) { mRefreshState = TAP_TO_REFRESH; // 初始刷新状态 LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) this.refreshView .getLayoutParams(); int i = lp.topMargin; refreshIndicatorView.setImageResource(R.drawable.goicon); refreshIndicatorView.clearAnimation(); bar.setVisibility(View.GONE); refreshIndicatorView.setVisibility(View.GONE); downTextView.setText(R.string.pull_to_refresh_tap_label); scroller.startScroll(0, i, 0, refreshTargetTop); invalidate(); } if (mfooterRefreshState != TAP_TO_REFRESH) { resetFooter(); } } public void resetFooter() { mfooterRefreshState = TAP_TO_REFRESH; // 初始刷新状态 // 使头部视图的 toppadding 恢复到初始值 resetFooterPadding(); // Set refresh view text to the pull label // 将文字初始化 mfooterViewText.setText(R.string.pull_to_refresh_footer_pull_label); } public void HideFooter() { LayoutParams mfvlp = new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); mfvlp.bottomMargin = refreshFooter; mfooterView.setLayoutParams(mfvlp); mfooterRefreshState = TAP_TO_REFRESH; } /* * 该方法一般和ontouchEvent 一起用 * * @see * android.view.ViewGroup#onInterceptTouchEvent(android.view.MotionEvent) */ @Override public boolean onInterceptTouchEvent(MotionEvent e) { // TODO Auto-generated method stub int action = e.getAction(); int y = (int) e.getRawY(); switch (action) { case MotionEvent.ACTION_DOWN: // lastY = y; if (isRecord == false) { Log.i("moveY", "lastY:" + y); lastY = y; isRecord = true; } break; case MotionEvent.ACTION_MOVE: // y移动坐标 int m = y - lastY; if (canScroll(m)) { return true; } break; case MotionEvent.ACTION_UP: isRecord = false; break; case MotionEvent.ACTION_CANCEL: break; } return false; } private boolean canScroll(int diff) { View childView; Log.i("other", "mRefreshState:" + mRefreshState); if (mRefreshState == REFRESHING || mfooterRefreshState == REFRESHING) { return true; } if (getChildCount() > 1) { childView = this.getChildAt(1); if (childView instanceof ListView) { int top = ((ListView) childView).getChildAt(0).getTop(); int pad = ((ListView) childView).getListPaddingTop(); if ((Math.abs(top - pad)) < 3 && ((ListView) childView).getFirstVisiblePosition() == 0) { return true; } else { return false; } } else if (childView instanceof ScrollView) { // 头部下拉 if (((ScrollView) childView).getScrollY() == 0 && diff > 0) { nowpull = 0; ServiceUtils.dout("other", "外框处理"); return true; } else if ((((ScrollView) childView).getChildAt(0) .getMeasuredHeight() <= ((ScrollView) childView) .getScrollY() + getHeight() && diff < 0)) {// 底部上拉 ServiceUtils.dout("other", "外框处理2"); nowpull = 1; return true; } else { ServiceUtils.dout("other", "ScrollView处理"); return false; } } } return false; } /** * 刷新监听接口 * * @author Nono * */ public interface RefreshListener { public void onRefresh(); } }
Java
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.outsourcing.bottle.widget.crop; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.os.Handler; import android.util.AttributeSet; import android.view.KeyEvent; import android.widget.ImageView; public abstract class ImageViewTouchBase extends ImageView { @SuppressWarnings("unused") private static final String TAG = "ImageViewTouchBase"; // This is the base transformation which is used to show the image // initially. The current computation for this shows the image in // it's entirety, letterboxing as needed. One could choose to // show the image as cropped instead. // // This matrix is recomputed when we go from the thumbnail image to // the full size image. protected Matrix mBaseMatrix = new Matrix(); // This is the supplementary transformation which reflects what // the user has done in terms of zooming and panning. // // This matrix remains the same when we go from the thumbnail image // to the full size image. protected Matrix mSuppMatrix = new Matrix(); // This is the final matrix which is computed as the concatentation // of the base matrix and the supplementary matrix. private final Matrix mDisplayMatrix = new Matrix(); // Temporary buffer used for getting the values out of a matrix. private final float[] mMatrixValues = new float[9]; // The current bitmap being displayed. final protected RotateBitmap mBitmapDisplayed = new RotateBitmap(null); int mThisWidth = -1, mThisHeight = -1; float mMaxZoom; /** * ����״̬ */ public static final int STATE_HIGHLIGHT = 0x0; /** * Ϳѻ״̬ */ public static final int STATE_DOODLE = STATE_HIGHLIGHT + 1; /** * û���κβ��� */ public static final int STATE_NONE = STATE_HIGHLIGHT + 2; protected int mState = STATE_HIGHLIGHT; // ImageViewTouchBase will pass a Bitmap to the Recycler if it has finished // its use of that Bitmap. public interface Recycler { public void recycle(Bitmap b); } public void setRecycler(Recycler r) { mRecycler = r; } private Recycler mRecycler; @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); mThisWidth = right - left; mThisHeight = bottom - top; Runnable r = mOnLayoutRunnable; if (r != null) { mOnLayoutRunnable = null; r.run(); } if (mBitmapDisplayed.getBitmap() != null) { getProperBaseMatrix(mBitmapDisplayed, mBaseMatrix); setImageMatrix(getImageViewMatrix()); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && getScale() > 1.0f) { // If we're zoomed in, pressing Back jumps out to show the entire // image, otherwise Back returns the user to the gallery. zoomTo(1.0f); return true; } return super.onKeyDown(keyCode, event); } protected Handler mHandler = new Handler(); protected int mLastXTouchPos; protected int mLastYTouchPos; @Override public void setImageBitmap(Bitmap bitmap) { setImageBitmap(bitmap, 0); } private void setImageBitmap(Bitmap bitmap, int rotation) { super.setImageBitmap(bitmap); Drawable d = getDrawable(); if (d != null) { d.setDither(true); } Bitmap old = mBitmapDisplayed.getBitmap(); mBitmapDisplayed.setBitmap(bitmap); mBitmapDisplayed.setRotation(rotation); if (old != null && old != bitmap && mRecycler != null) { mRecycler.recycle(old); } } public void clear() { setImageBitmapResetBase(null, true); } private Runnable mOnLayoutRunnable = null; // This function changes bitmap, reset base matrix according to the size // of the bitmap, and optionally reset the supplementary matrix. public void setImageBitmapResetBase(final Bitmap bitmap, final boolean resetSupp) { setImageRotateBitmapResetBase(new RotateBitmap(bitmap), resetSupp); } public void setImageRotateBitmapResetBase(final RotateBitmap bitmap, final boolean resetSupp) { final int viewWidth = getWidth(); if (viewWidth <= 0) { mOnLayoutRunnable = new Runnable() { public void run() { setImageRotateBitmapResetBase(bitmap, resetSupp); } }; return; } if (bitmap.getBitmap() != null) { getProperBaseMatrix(bitmap, mBaseMatrix); setImageBitmap(bitmap.getBitmap(), bitmap.getRotation()); } else { mBaseMatrix.reset(); setImageBitmap(null); } if (resetSupp) { mSuppMatrix.reset(); } setImageMatrix(getImageViewMatrix()); mMaxZoom = maxZoom(); } // Center as much as possible in one or both axis. Centering is // defined as follows: if the image is scaled down below the // view's dimensions then center it (literally). If the image // is scaled larger than the view and is translated out of view // then translate it back into view (i.e. eliminate black bars). public void center(boolean horizontal, boolean vertical) { if (mBitmapDisplayed.getBitmap() == null) { return; } Matrix m = getImageViewMatrix(); RectF rect = new RectF(0, 0, mBitmapDisplayed.getBitmap().getWidth(), mBitmapDisplayed.getBitmap().getHeight()); m.mapRect(rect); float height = rect.height(); float width = rect.width(); float deltaX = 0, deltaY = 0; if (vertical) { int viewHeight = getHeight(); if (height < viewHeight) { deltaY = (viewHeight - height) / 2 - rect.top; } else if (rect.top > 0) { deltaY = -rect.top; } else if (rect.bottom < viewHeight) { deltaY = getHeight() - rect.bottom; } } if (horizontal) { int viewWidth = getWidth(); if (width < viewWidth) { deltaX = (viewWidth - width) / 2 - rect.left; } else if (rect.left > 0) { deltaX = -rect.left; } else if (rect.right < viewWidth) { deltaX = viewWidth - rect.right; } } postTranslate(deltaX, deltaY); setImageMatrix(getImageViewMatrix()); } public ImageViewTouchBase(Context context) { super(context); init(); } public ImageViewTouchBase(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { setScaleType(ImageView.ScaleType.MATRIX); } protected float getValue(Matrix matrix, int whichValue) { matrix.getValues(mMatrixValues); return mMatrixValues[whichValue]; } // Get the scale factor out of the matrix. protected float getScale(Matrix matrix) { return getValue(matrix, Matrix.MSCALE_X); } public float getScale() { return getScale(mSuppMatrix); } // Setup the base matrix so that the image is centered and scaled properly. private void getProperBaseMatrix(RotateBitmap bitmap, Matrix matrix) { float viewWidth = getWidth(); float viewHeight = getHeight(); float w = bitmap.getWidth(); float h = bitmap.getHeight(); matrix.reset(); // We limit up-scaling to 2x otherwise the result may look bad if it's // a small icon. float widthScale = Math.min(viewWidth / w, 2.0f); float heightScale = Math.min(viewHeight / h, 2.0f); float scale = Math.min(widthScale, heightScale); matrix.postConcat(bitmap.getRotateMatrix()); matrix.postScale(scale, scale); matrix.postTranslate((viewWidth - w * scale) / 2F, (viewHeight - h * scale) / 2F); } // Combine the base matrix and the supp matrix to make the final matrix. protected Matrix getImageViewMatrix() { // The final matrix is computed as the concatentation of the base matrix // and the supplementary matrix. mDisplayMatrix.set(mBaseMatrix); mDisplayMatrix.postConcat(mSuppMatrix); return mDisplayMatrix; } static final float SCALE_RATE = 1.25F; // Sets the maximum zoom, which is a scale relative to the base matrix. It // is calculated to show the image at 400% zoom regardless of screen or // image orientation. If in the future we decode the full 3 megapixel image, // rather than the current 1024x768, this should be changed down to 200%. protected float maxZoom() { if (mBitmapDisplayed.getBitmap() == null) { return 1F; } float fw = (float) mBitmapDisplayed.getWidth() / (float) mThisWidth; float fh = (float) mBitmapDisplayed.getHeight() / (float) mThisHeight; float max = Math.max(fw, fh) * 4; return max; } protected void zoomTo(float scale, float centerX, float centerY) { if (scale > mMaxZoom) { scale = mMaxZoom; } float oldScale = getScale(); float deltaScale = scale / oldScale; mSuppMatrix.postScale(deltaScale, deltaScale, centerX, centerY); setImageMatrix(getImageViewMatrix()); center(true, true); } protected void zoomTo(final float scale, final float centerX, final float centerY, final float durationMs) { final float incrementPerMs = (scale - getScale()) / durationMs; final float oldScale = getScale(); final long startTime = System.currentTimeMillis(); mHandler.post(new Runnable() { public void run() { long now = System.currentTimeMillis(); float currentMs = Math.min(durationMs, now - startTime); float target = oldScale + (incrementPerMs * currentMs); zoomTo(target, centerX, centerY); if (currentMs < durationMs) { mHandler.post(this); } } }); } protected void zoomTo(float scale) { float cx = getWidth() / 2F; float cy = getHeight() / 2F; zoomTo(scale, cx, cy); } protected void zoomIn() { zoomIn(SCALE_RATE); } protected void zoomOut() { zoomOut(SCALE_RATE); } protected void zoomIn(float rate) { if (getScale() >= mMaxZoom) { return; // Don't let the user zoom into the molecular level. } if (mBitmapDisplayed.getBitmap() == null) { return; } float cx = getWidth() / 2F; float cy = getHeight() / 2F; mSuppMatrix.postScale(rate, rate, cx, cy); setImageMatrix(getImageViewMatrix()); } protected void zoomOut(float rate) { if (mBitmapDisplayed.getBitmap() == null) { return; } float cx = getWidth() / 2F; float cy = getHeight() / 2F; // Zoom out to at most 1x. Matrix tmp = new Matrix(mSuppMatrix); tmp.postScale(1F / rate, 1F / rate, cx, cy); if (getScale(tmp) < 1F) { mSuppMatrix.setScale(1F, 1F, cx, cy); } else { mSuppMatrix.postScale(1F / rate, 1F / rate, cx, cy); } setImageMatrix(getImageViewMatrix()); center(true, true); } protected void postTranslate(float dx, float dy) { mSuppMatrix.postTranslate(dx, dy); } protected void panBy(float dx, float dy) { postTranslate(dx, dy); setImageMatrix(getImageViewMatrix()); } }
Java
package com.outsourcing.bottle.widget.crop; import java.util.concurrent.CountDownLatch; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.PointF; import android.graphics.Rect; import android.graphics.RectF; import android.media.FaceDetector; import android.os.Handler; import com.outsourcing.bottle.R; import com.outsourcing.bottle.util.Util; public class CropImage { public boolean mWaitingToPick; // Whether we are wait the user to pick a // face. public boolean mSaving; // Whether the "save" button is already clicked. public HighlightView mCrop; private Context mContext; private Handler mHandler = new Handler(); private CropImageView mImageView; private Bitmap mBitmap; private boolean mCircleCrop = false; private int mAspectX, mAspectY; private int mOutputX, mOutputY; public CropImage(Context context, CropImageView imageView, boolean mCircleCrop, int mOutputX, int mOutputY) { this.mContext = context; this.mImageView = imageView; this.mOutputX = mOutputX; this.mOutputY = mOutputY; if (mCircleCrop) { mAspectX = 1; mAspectY = 1; } mImageView.setCropImage(this); } public void crop(Bitmap bm) { mBitmap = bm; startFaceDetection(); } private void startFaceDetection() { if (((Activity) mContext).isFinishing()) { return; } showProgressDialog( mContext.getResources().getString( R.string.running_face_detection), new Runnable() { public void run() { final CountDownLatch latch = new CountDownLatch(1); final Bitmap b = mBitmap; mHandler.post(new Runnable() { public void run() { if (b != mBitmap && b != null) { mImageView.setImageBitmapResetBase(b, true); mBitmap.recycle(); mBitmap = b; } if (mImageView.getScale() == 1.0f) { mImageView.center(true, true); } latch.countDown(); } }); try { latch.await(); } catch (InterruptedException e) { throw new RuntimeException(e); } mRunFaceDetection.run(); } }, mHandler); } public Bitmap cropAndSave(Bitmap bm) { final Bitmap bmp = onSaveClicked(bm); mImageView.mHighlightViews.clear(); return bmp; } public void cropCancel() { mImageView.mHighlightViews.clear(); mImageView.invalidate(); } private Bitmap onSaveClicked(Bitmap bm) { // step api so that we don't require that the whole (possibly large) // bitmap doesn't have to be read into memory if (mSaving) return bm; if (mCrop == null) { return bm; } mSaving = true; Bitmap croppedImage; // if (mOutputX != 0 && mOutputY != 0) { // croppedImage = Bitmap.createBitmap(mOutputX, mOutputY, Bitmap.Config.RGB_565); // Canvas canvas = new Canvas(croppedImage); // // Rect srcRect = mCrop.getCropRect(); // Rect dstRect = new Rect(0, 0, mOutputX, mOutputY); // // int dx = (srcRect.width() - dstRect.width()) / 2; // int dy = (srcRect.height() - dstRect.height()) / 2; // // // If the srcRect is too big, use the center part of it. // srcRect.inset(Math.max(0, dx), Math.max(0, dy)); // // // If the dstRect is too big, use the center part of it. // dstRect.inset(Math.max(0, -dx), Math.max(0, -dy)); // // // Draw the cropped bitmap in the center // canvas.drawBitmap(mBitmap, srcRect, dstRect, null); // // // Release bitmap memory as soon as possible // mImageView.clear(); // mBitmap.recycle(); // } else { Rect r = mCrop.getCropRect(); int width = r.width(); int height = r.height(); // If we are circle cropping, we want alpha channel, which is the // third param here. croppedImage = Bitmap.createBitmap(width, height, mCircleCrop ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); Canvas canvas = new Canvas(croppedImage); Rect dstRect = new Rect(0, 0, width, height); canvas.drawBitmap(mBitmap, r, dstRect, null); // Release bitmap memory as soon as possible mImageView.clear(); mBitmap.recycle(); // } croppedImage = Util.transform(new Matrix(), croppedImage, mOutputX, mOutputY, true, Util.RECYCLE_INPUT); return croppedImage; } private void showProgressDialog(String msg, Runnable job, Handler handler) { final ProgressDialog progress = ProgressDialog.show(mContext, null, msg); new Thread(new BackgroundJob(progress, job, handler)).start(); } Runnable mRunFaceDetection = new Runnable() { float mScale = 1F; Matrix mImageMatrix; FaceDetector.Face[] mFaces = new FaceDetector.Face[3]; int mNumFaces; // For each face, we create a HightlightView for it. private void handleFace(FaceDetector.Face f) { PointF midPoint = new PointF(); int r = ((int) (f.eyesDistance() * mScale)) * 2; f.getMidPoint(midPoint); midPoint.x *= mScale; midPoint.y *= mScale; int midX = (int) midPoint.x; int midY = (int) midPoint.y; HighlightView hv = new HighlightView(mImageView); int width = mBitmap.getWidth(); int height = mBitmap.getHeight(); Rect imageRect = new Rect(0, 0, width, height); RectF faceRect = new RectF(midX, midY, midX, midY); faceRect.inset(-r, -r); if (faceRect.left < 0) { faceRect.inset(-faceRect.left, -faceRect.left); } if (faceRect.top < 0) { faceRect.inset(-faceRect.top, -faceRect.top); } if (faceRect.right > imageRect.right) { faceRect.inset(faceRect.right - imageRect.right, faceRect.right - imageRect.right); } if (faceRect.bottom > imageRect.bottom) { faceRect.inset(faceRect.bottom - imageRect.bottom, faceRect.bottom - imageRect.bottom); } hv.setup(mImageMatrix, imageRect, faceRect, mCircleCrop, mAspectX != 0 && mAspectY != 0); mImageView.add(hv); } // Create a default HightlightView if we found no face in the picture. private void makeDefault() { HighlightView hv = new HighlightView(mImageView); int width = mBitmap.getWidth(); int height = mBitmap.getHeight(); Rect imageRect = new Rect(0, 0, width, height); // CR: sentences! // make the default size about 4/5 of the width or height int cropWidth = Math.min(width, height) * 4 / 5; int cropHeight = cropWidth; int x = (width - cropWidth) / 2; int y = (height - cropHeight) / 2; RectF cropRect = new RectF(x, y, x + cropWidth, y + cropHeight); hv.setup(mImageMatrix, imageRect, cropRect, mCircleCrop, mAspectX != 0 && mAspectY != 0); mImageView.add(hv); } // Scale the image down for faster face detection. // public Bitmap prepareBitmap() { // if (mBitmap == null) { // return null; // } // // // 256 pixels wide is enough. // if (mBitmap.getWidth() > 256) { // mScale = 256.0F / mBitmap.getWidth(); // CR: F => f (or change // // all f to F). // } // Matrix matrix = new Matrix(); // matrix.setScale(mScale, mScale); // Bitmap faceBitmap = Bitmap.createBitmap(mBitmap, 0, 0, // mBitmap.getWidth(), mBitmap.getHeight(), matrix, true); // return faceBitmap; // } public void run() { mImageMatrix = mImageView.getImageMatrix(); // Bitmap faceBitmap = prepareBitmap(); mScale = 1.0F / mScale; // if (faceBitmap != null) { // FaceDetector detector = new FaceDetector(faceBitmap.getWidth(), // faceBitmap.getHeight(), mFaces.length); // mNumFaces = detector.findFaces(faceBitmap, mFaces); // } // // if (faceBitmap != null && faceBitmap != mBitmap) { // faceBitmap.recycle(); // } mHandler.post(new Runnable() { public void run() { mWaitingToPick = mNumFaces > 1; if (mNumFaces > 0) { for (int i = 0; i < mNumFaces; i++) { handleFace(mFaces[i]); } } else { makeDefault(); } mImageView.invalidate(); if (mImageView.mHighlightViews.size() == 1) { mCrop = mImageView.mHighlightViews.get(0); mCrop.setFocus(true); } if (mNumFaces > 1) { // CR: no need for the variable t. just do // Toast.makeText(...).show(). // Toast t = Toast.makeText(mContext, // R.string.multiface_crop_help, // Toast.LENGTH_SHORT); // t.show(); } } }); } }; class BackgroundJob implements Runnable { private ProgressDialog mProgress; private Runnable mJob; private Handler mHandler; public BackgroundJob(ProgressDialog progress, Runnable job, Handler handler) { mProgress = progress; mJob = job; mHandler = handler; } public void run() { try { mJob.run(); } finally { mHandler.post(new Runnable() { public void run() { if (mProgress != null && mProgress.isShowing()) { mProgress.dismiss(); mProgress = null; } } }); } } } }
Java
package com.outsourcing.bottle.widget.crop; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Region; import android.graphics.drawable.Drawable; import android.view.View; import com.outsourcing.bottle.R; public class HighlightView { @SuppressWarnings("unused") private static final String TAG = "HighlightView"; View mContext; // The View displaying the image. public static final int GROW_NONE = (1 << 0); public static final int GROW_LEFT_EDGE = (1 << 1); public static final int GROW_RIGHT_EDGE = (1 << 2); public static final int GROW_TOP_EDGE = (1 << 3); public static final int GROW_BOTTOM_EDGE = (1 << 4); public static final int MOVE = (1 << 5); public HighlightView(View ctx) { mContext = ctx; } private void init() { android.content.res.Resources resources = mContext.getResources(); mResizeDrawableWidth = resources.getDrawable(R.drawable.camera_crop_width); mResizeDrawableHeight = resources.getDrawable(R.drawable.camera_crop_height); mResizeDrawableDiagonal = resources.getDrawable(R.drawable.indicator_autocrop); } public boolean mIsFocused; boolean mHidden; public boolean hasFocus() { return mIsFocused; } public void setFocus(boolean f) { mIsFocused = f; } public void setHidden(boolean hidden) { mHidden = hidden; } public void draw(Canvas canvas) { if (mHidden) { return; } canvas.save(); Path path = new Path(); if (!hasFocus()) { mOutlinePaint.setColor(0xFF000000); canvas.drawRect(mDrawRect, mOutlinePaint); } else { Rect viewDrawingRect = new Rect(); mContext.getDrawingRect(viewDrawingRect); if (mCircle) { float width = mDrawRect.width(); float height = mDrawRect.height(); path.addCircle(mDrawRect.left + (width / 2), mDrawRect.top + (height / 2), width / 2, Path.Direction.CW); mOutlinePaint.setColor(0xFFEF04D6); } else { path.addRect(new RectF(mDrawRect), Path.Direction.CW); mOutlinePaint.setColor(0xFFFF8A00); } canvas.clipPath(path, Region.Op.DIFFERENCE); canvas.drawRect(viewDrawingRect, hasFocus() ? mFocusPaint : mNoFocusPaint); canvas.restore(); canvas.drawPath(path, mOutlinePaint); if (mMode == ModifyMode.Grow) { if (mCircle) { int width = mResizeDrawableDiagonal.getIntrinsicWidth(); int height = mResizeDrawableDiagonal.getIntrinsicHeight(); int d = (int) Math.round(Math.cos(/* 45deg */Math.PI / 4D) * (mDrawRect.width() / 2D)); int x = mDrawRect.left + (mDrawRect.width() / 2) + d - width / 2; int y = mDrawRect.top + (mDrawRect.height() / 2) - d - height / 2; mResizeDrawableDiagonal.setBounds(x, y, x + mResizeDrawableDiagonal.getIntrinsicWidth(), y + mResizeDrawableDiagonal.getIntrinsicHeight()); mResizeDrawableDiagonal.draw(canvas); } else { int left = mDrawRect.left + 1; int right = mDrawRect.right + 1; int top = mDrawRect.top + 4; int bottom = mDrawRect.bottom + 3; int widthWidth = mResizeDrawableWidth.getIntrinsicWidth() / 2; int widthHeight = mResizeDrawableWidth.getIntrinsicHeight() / 2; int heightHeight = mResizeDrawableHeight.getIntrinsicHeight() / 2; int heightWidth = mResizeDrawableHeight.getIntrinsicWidth() / 2; int xMiddle = mDrawRect.left + ((mDrawRect.right - mDrawRect.left) / 2); int yMiddle = mDrawRect.top + ((mDrawRect.bottom - mDrawRect.top) / 2); mResizeDrawableWidth.setBounds(left - widthWidth, yMiddle - widthHeight, left + widthWidth, yMiddle + widthHeight); mResizeDrawableWidth.draw(canvas); mResizeDrawableWidth.setBounds(right - widthWidth, yMiddle - widthHeight, right + widthWidth, yMiddle + widthHeight); mResizeDrawableWidth.draw(canvas); mResizeDrawableHeight.setBounds(xMiddle - heightWidth, top - heightHeight, xMiddle + heightWidth, top + heightHeight); mResizeDrawableHeight.draw(canvas); mResizeDrawableHeight.setBounds(xMiddle - heightWidth, bottom - heightHeight, xMiddle + heightWidth, bottom + heightHeight); mResizeDrawableHeight.draw(canvas); } } } } public void setMode(ModifyMode mode) { if (mode != mMode) { mMode = mode; mContext.invalidate(); } } // Determines which edges are hit by touching at (x, y). public int getHit(float x, float y) { Rect r = computeLayout(); final float hysteresis = 20F; int retval = GROW_NONE; if (mCircle) { float distX = x - r.centerX(); float distY = y - r.centerY(); int distanceFromCenter = (int) Math.sqrt(distX * distX + distY * distY); int radius = mDrawRect.width() / 2; int delta = distanceFromCenter - radius; if (Math.abs(delta) <= hysteresis) { if (Math.abs(distY) > Math.abs(distX)) { if (distY < 0) { retval = GROW_TOP_EDGE; } else { retval = GROW_BOTTOM_EDGE; } } else { if (distX < 0) { retval = GROW_LEFT_EDGE; } else { retval = GROW_RIGHT_EDGE; } } } else if (distanceFromCenter < radius) { retval = MOVE; } else { retval = GROW_NONE; } } else { // verticalCheck makes sure the position is between the top and // the bottom edge (with some tolerance). Similar for horizCheck. boolean verticalCheck = (y >= r.top - hysteresis) && (y < r.bottom + hysteresis); boolean horizCheck = (x >= r.left - hysteresis) && (x < r.right + hysteresis); // Check whether the position is near some edge(s). if ((Math.abs(r.left - x) < hysteresis) && verticalCheck) { retval |= GROW_LEFT_EDGE; } if ((Math.abs(r.right - x) < hysteresis) && verticalCheck) { retval |= GROW_RIGHT_EDGE; } if ((Math.abs(r.top - y) < hysteresis) && horizCheck) { retval |= GROW_TOP_EDGE; } if ((Math.abs(r.bottom - y) < hysteresis) && horizCheck) { retval |= GROW_BOTTOM_EDGE; } // Not near any edge but inside the rectangle: move. if (retval == GROW_NONE && r.contains((int) x, (int) y)) { retval = MOVE; } } return retval; } // Handles motion (dx, dy) in screen space. // The "edge" parameter specifies which edges the user is dragging. public void handleMotion(int edge, float dx, float dy) { Rect r = computeLayout(); if (edge == GROW_NONE) { return; } else if (edge == MOVE) { // Convert to image space before sending to moveBy(). moveBy(dx * (mCropRect.width() / r.width()), dy * (mCropRect.height() / r.height())); } else { if (((GROW_LEFT_EDGE | GROW_RIGHT_EDGE) & edge) == 0) { dx = 0; } if (((GROW_TOP_EDGE | GROW_BOTTOM_EDGE) & edge) == 0) { dy = 0; } // Convert to image space before sending to growBy(). float xDelta = dx * (mCropRect.width() / r.width()); float yDelta = dy * (mCropRect.height() / r.height()); growBy((((edge & GROW_LEFT_EDGE) != 0) ? -1 : 1) * xDelta, (((edge & GROW_TOP_EDGE) != 0) ? -1 : 1) * yDelta); } } // Grows the cropping rectange by (dx, dy) in image space. void moveBy(float dx, float dy) { Rect invalRect = new Rect(mDrawRect); mCropRect.offset(dx, dy); // Put the cropping rectangle inside image rectangle. mCropRect.offset(Math.max(0, mImageRect.left - mCropRect.left), Math.max(0, mImageRect.top - mCropRect.top)); mCropRect.offset(Math.min(0, mImageRect.right - mCropRect.right), Math.min(0, mImageRect.bottom - mCropRect.bottom)); mDrawRect = computeLayout(); invalRect.union(mDrawRect); invalRect.inset(-10, -10); mContext.invalidate(invalRect); } // Grows the cropping rectange by (dx, dy) in image space. void growBy(float dx, float dy) { if (mMaintainAspectRatio) { if (dx != 0) { dy = dx / mInitialAspectRatio; } else if (dy != 0) { dx = dy * mInitialAspectRatio; } } // Don't let the cropping rectangle grow too fast. // Grow at most half of the difference between the image rectangle and // the cropping rectangle. RectF r = new RectF(mCropRect); if (dx > 0F && r.width() + 2 * dx > mImageRect.width()) { float adjustment = (mImageRect.width() - r.width()) / 2F; dx = adjustment; if (mMaintainAspectRatio) { dy = dx / mInitialAspectRatio; } } if (dy > 0F && r.height() + 2 * dy > mImageRect.height()) { float adjustment = (mImageRect.height() - r.height()) / 2F; dy = adjustment; if (mMaintainAspectRatio) { dx = dy * mInitialAspectRatio; } } r.inset(-dx, -dy); // Don't let the cropping rectangle shrink too fast. final float widthCap = 25F; if (r.width() < widthCap) { r.inset(-(widthCap - r.width()) / 2F, 0F); } float heightCap = mMaintainAspectRatio ? (widthCap / mInitialAspectRatio) : widthCap; if (r.height() < heightCap) { r.inset(0F, -(heightCap - r.height()) / 2F); } // Put the cropping rectangle inside the image rectangle. if (r.left < mImageRect.left) { r.offset(mImageRect.left - r.left, 0F); } else if (r.right > mImageRect.right) { r.offset(-(r.right - mImageRect.right), 0); } if (r.top < mImageRect.top) { r.offset(0F, mImageRect.top - r.top); } else if (r.bottom > mImageRect.bottom) { r.offset(0F, -(r.bottom - mImageRect.bottom)); } mCropRect.set(r); mDrawRect = computeLayout(); mContext.invalidate(); } // Returns the cropping rectangle in image space. public Rect getCropRect() { return new Rect((int) mCropRect.left, (int) mCropRect.top, (int) mCropRect.right, (int) mCropRect.bottom); } // Maps the cropping rectangle from image space to screen space. private Rect computeLayout() { RectF r = new RectF(mCropRect.left, mCropRect.top, mCropRect.right, mCropRect.bottom); mMatrix.mapRect(r); return new Rect(Math.round(r.left), Math.round(r.top), Math.round(r.right), Math.round(r.bottom)); } public void invalidate() { mDrawRect = computeLayout(); } public void setup(Matrix m, Rect imageRect, RectF cropRect, boolean circle, boolean maintainAspectRatio) { if (circle) { maintainAspectRatio = true; } mMatrix = new Matrix(m); mCropRect = cropRect; mImageRect = new RectF(imageRect); mMaintainAspectRatio = maintainAspectRatio; mCircle = circle; mInitialAspectRatio = mCropRect.width() / mCropRect.height(); mDrawRect = computeLayout(); mFocusPaint.setARGB(125, 50, 50, 50); mNoFocusPaint.setARGB(125, 50, 50, 50); mOutlinePaint.setStrokeWidth(3F); mOutlinePaint.setStyle(Paint.Style.STROKE); mOutlinePaint.setAntiAlias(true); mMode = ModifyMode.None; init(); } public enum ModifyMode { None, Move, Grow } private ModifyMode mMode = ModifyMode.None; public Rect mDrawRect; // in screen space private RectF mImageRect; // in image space public RectF mCropRect; // in image space public Matrix mMatrix; private boolean mMaintainAspectRatio = false; private float mInitialAspectRatio; private boolean mCircle = false; private Drawable mResizeDrawableWidth; private Drawable mResizeDrawableHeight; private Drawable mResizeDrawableDiagonal; private final Paint mFocusPaint = new Paint(); private final Paint mNoFocusPaint = new Paint(); private final Paint mOutlinePaint = new Paint(); }
Java
package com.outsourcing.bottle.widget.crop; import java.util.ArrayList; import android.content.Context; import android.graphics.Canvas; import android.graphics.Rect; import android.util.AttributeSet; import android.view.MotionEvent; public class CropImageView extends ImageViewTouchBase { public ArrayList<HighlightView> mHighlightViews = new ArrayList<HighlightView>(); HighlightView mMotionHighlightView = null; float mLastX, mLastY; int mMotionEdge; private CropImage mCropImage; @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); if (mBitmapDisplayed.getBitmap() != null) { for (HighlightView hv : mHighlightViews) { hv.mMatrix.set(getImageMatrix()); hv.invalidate(); if (hv.mIsFocused) { centerBasedOnHighlightView(hv); } } } } public CropImageView(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void zoomTo(float scale, float centerX, float centerY) { super.zoomTo(scale, centerX, centerY); for (HighlightView hv : mHighlightViews) { hv.mMatrix.set(getImageMatrix()); hv.invalidate(); } } @Override protected void zoomIn() { super.zoomIn(); for (HighlightView hv : mHighlightViews) { hv.mMatrix.set(getImageMatrix()); hv.invalidate(); } } @Override protected void zoomOut() { super.zoomOut(); for (HighlightView hv : mHighlightViews) { hv.mMatrix.set(getImageMatrix()); hv.invalidate(); } } @Override protected void postTranslate(float deltaX, float deltaY) { super.postTranslate(deltaX, deltaY); for (int i = 0; i < mHighlightViews.size(); i++) { HighlightView hv = mHighlightViews.get(i); hv.mMatrix.postTranslate(deltaX, deltaY); hv.invalidate(); } } // According to the event's position, change the focus to the first // hitting cropping rectangle. private void recomputeFocus(MotionEvent event) { for (int i = 0; i < mHighlightViews.size(); i++) { HighlightView hv = mHighlightViews.get(i); hv.setFocus(false); hv.invalidate(); } for (int i = 0; i < mHighlightViews.size(); i++) { HighlightView hv = mHighlightViews.get(i); int edge = hv.getHit(event.getX(), event.getY()); if (edge != HighlightView.GROW_NONE) { if (!hv.hasFocus()) { hv.setFocus(true); hv.invalidate(); } break; } } invalidate(); } @Override public boolean onTouchEvent(MotionEvent event) { CropImage cropImage = mCropImage; if (cropImage.mSaving) { return false; } switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // CR: inline case blocks. if (cropImage.mWaitingToPick) { recomputeFocus(event); } else { for (int i = 0; i < mHighlightViews.size(); i++) { // CR: // iterator // for; if // not, then // i++ => // ++i. HighlightView hv = mHighlightViews.get(i); int edge = hv.getHit(event.getX(), event.getY()); if (edge != HighlightView.GROW_NONE) { mMotionEdge = edge; mMotionHighlightView = hv; mLastX = event.getX(); mLastY = event.getY(); // CR: get rid of the extraneous parens below. mMotionHighlightView.setMode((edge == HighlightView.MOVE) ? HighlightView.ModifyMode.Move : HighlightView.ModifyMode.Grow); break; } } } break; // CR: vertical space before case blocks. case MotionEvent.ACTION_UP: if (cropImage.mWaitingToPick) { for (int i = 0; i < mHighlightViews.size(); i++) { HighlightView hv = mHighlightViews.get(i); if (hv.hasFocus()) { cropImage.mCrop = hv; for (int j = 0; j < mHighlightViews.size(); j++) { if (j == i) { // CR: if j != i do your shit; no need // for continue. continue; } mHighlightViews.get(j).setHidden(true); } centerBasedOnHighlightView(hv); mCropImage.mWaitingToPick = false; return true; } } } else if (mMotionHighlightView != null) { centerBasedOnHighlightView(mMotionHighlightView); mMotionHighlightView.setMode(HighlightView.ModifyMode.None); } mMotionHighlightView = null; break; case MotionEvent.ACTION_MOVE: if (cropImage.mWaitingToPick) { recomputeFocus(event); } else if (mMotionHighlightView != null) { mMotionHighlightView.handleMotion(mMotionEdge, event.getX() - mLastX, event.getY() - mLastY); mLastX = event.getX(); mLastY = event.getY(); if (true) { // This section of code is optional. It has some user // benefit in that moving the crop rectangle against // the edge of the screen causes scrolling but it means // that the crop rectangle is no longer fixed under // the user's finger. ensureVisible(mMotionHighlightView); } } break; } switch (event.getAction()) { case MotionEvent.ACTION_UP: center(true, true); break; case MotionEvent.ACTION_MOVE: // if we're not zoomed then there's no point in even allowing // the user to move the image around. This call to center puts // it back to the normalized location (with false meaning don't // animate). // if (getScale() == 1F) { center(true, true); // } break; } return true; } // Pan the displayed image to make sure the cropping rectangle is visible. private void ensureVisible(HighlightView hv) { Rect r = hv.mDrawRect; int panDeltaX1 = Math.max(0, getLeft() - r.left); int panDeltaX2 = Math.min(0, getRight() - r.right); int panDeltaY1 = Math.max(0, getTop() - r.top); int panDeltaY2 = Math.min(0, getBottom() - r.bottom); int panDeltaX = panDeltaX1 != 0 ? panDeltaX1 : panDeltaX2; int panDeltaY = panDeltaY1 != 0 ? panDeltaY1 : panDeltaY2; if (panDeltaX != 0 || panDeltaY != 0) { panBy(panDeltaX, panDeltaY); } } // If the cropping rectangle's size changed significantly, change the // view's center and scale according to the cropping rectangle. private void centerBasedOnHighlightView(HighlightView hv) { Rect drawRect = hv.mDrawRect; float width = drawRect.width(); float height = drawRect.height(); float thisWidth = getWidth(); float thisHeight = getHeight(); float z1 = thisWidth / width * .6F; float z2 = thisHeight / height * .6F; float zoom = Math.min(z1, z2); zoom = zoom * this.getScale(); zoom = Math.max(1F, zoom); if ((Math.abs(zoom - getScale()) / zoom) > .1) { float[] coordinates = new float[] { hv.mCropRect.centerX(), hv.mCropRect.centerY() }; getImageMatrix().mapPoints(coordinates); zoomTo(zoom, coordinates[0], coordinates[1], 300F); // CR: 300.0f. } ensureVisible(hv); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); for (int i = 0; i < mHighlightViews.size(); i++) { mHighlightViews.get(i).draw(canvas); } } public void add(HighlightView hv) { mHighlightViews.add(hv); invalidate(); } public void setCropImage(CropImage cropImage) { mCropImage = cropImage; } }
Java
package com.outsourcing.bottle.widget.crop; import android.graphics.Bitmap; import android.graphics.Matrix; public class RotateBitmap { public static final String TAG = "RotateBitmap"; private Bitmap mBitmap; private int mRotation; public RotateBitmap(Bitmap bitmap) { mBitmap = bitmap; mRotation = 0; } public RotateBitmap(Bitmap bitmap, int rotation) { mBitmap = bitmap; mRotation = rotation % 360; } public void setRotation(int rotation) { mRotation = rotation; } public int getRotation() { return mRotation; } public Bitmap getBitmap() { return mBitmap; } public void setBitmap(Bitmap bitmap) { mBitmap = bitmap; } public Matrix getRotateMatrix() { // By default this is an identity matrix. Matrix matrix = new Matrix(); if (mRotation != 0) { // We want to do the rotation at origin, but since the bounding // rectangle will be changed after rotation, so the delta values // are based on old & new width/height respectively. int cx = mBitmap.getWidth() / 2; int cy = mBitmap.getHeight() / 2; matrix.preTranslate(-cx, -cy); matrix.postRotate(mRotation); matrix.postTranslate(getWidth() / 2, getHeight() / 2); } return matrix; } public boolean isOrientationChanged() { return (mRotation / 90) % 2 != 0; } public int getHeight() { if (isOrientationChanged()) { return mBitmap.getWidth(); } else { return mBitmap.getHeight(); } } public int getWidth() { if (isOrientationChanged()) { return mBitmap.getHeight(); } else { return mBitmap.getWidth(); } } public void recycle() { if (mBitmap != null) { mBitmap.recycle(); mBitmap = null; } } }
Java
package com.outsourcing.bottle.widget; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.ImageView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import com.outsourcing.bottle.R; /** * 重写ListView控件,增加了头部,状态栏等控件。 * @author 06peng * */ public class RefreshListView extends ListView implements OnScrollListener { private static final int TAP_TO_REFRESH = 1; private static final int PULL_TO_REFRESH = 2; private static final int RELEASE_TO_REFRESH = 3; private static final int REFRESHING = 4; private OnRefreshListener mOnRefreshListener; private OnScrollListener mOnScrollListener; private LayoutInflater mInflater; private RelativeLayout mRefreshView; private TextView mRefreshViewText; private ImageView mRefreshViewImage; private ProgressBar mRefreshViewProgress; private TextView mRefreshViewLastUpdated; private int mCurrentScrollState; private int mRefreshState; private RotateAnimation mFlipAnimation; private RotateAnimation mReverseFlipAnimation; private int mRefreshViewHeight; private int mRefreshOriginalTopPadding; private int mLastMotionY; private boolean mBounceHack; public RefreshListView(Context context) { super(context); init(context); } public RefreshListView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public RefreshListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); } /** * 初始化控件和动画 * @param context */ private void init(Context context) { mFlipAnimation = new RotateAnimation(0, -180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); mFlipAnimation.setInterpolator(new LinearInterpolator()); mFlipAnimation.setDuration(250); mFlipAnimation.setFillAfter(true); mReverseFlipAnimation = new RotateAnimation(-180, 0, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); mReverseFlipAnimation.setInterpolator(new LinearInterpolator()); mReverseFlipAnimation.setDuration(250); mReverseFlipAnimation.setFillAfter(true); mInflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); mRefreshView = (RelativeLayout) mInflater.inflate(R.layout.pull_to_refresh_header2, this, false); mRefreshViewText = (TextView) mRefreshView.findViewById(R.id.pull_to_refresh_text); mRefreshViewImage = (ImageView) mRefreshView.findViewById(R.id.pull_to_refresh_image); mRefreshViewProgress = (ProgressBar) mRefreshView.findViewById(R.id.pull_to_refresh_progress); mRefreshViewLastUpdated = (TextView) mRefreshView.findViewById(R.id.pull_to_refresh_updated_at); mRefreshViewImage.setMinimumHeight(50); mRefreshView.setOnClickListener(new OnClickRefreshListener()); mRefreshOriginalTopPadding = mRefreshView.getPaddingTop(); mRefreshState = TAP_TO_REFRESH; addHeaderView(mRefreshView); super.setOnScrollListener(this); measureView(mRefreshView); mRefreshViewHeight = mRefreshView.getMeasuredHeight(); } @Override protected void onAttachedToWindow() { setSelection(1); } @Override public void setAdapter(ListAdapter adapter) { super.setAdapter(adapter); setSelection(1); } @Override public void setOnScrollListener(AbsListView.OnScrollListener l) { mOnScrollListener = l; } public void setOnRefreshListener(OnRefreshListener onRefreshListener) { mOnRefreshListener = onRefreshListener; } public void setLastUpdated(CharSequence lastUpdated) { if (lastUpdated != null) { mRefreshViewLastUpdated.setVisibility(View.VISIBLE); mRefreshViewLastUpdated.setText(lastUpdated); } else { mRefreshViewLastUpdated.setVisibility(View.GONE); } } @Override public boolean onTouchEvent(MotionEvent event) { final int y = (int) event.getY(); mBounceHack = false; switch (event.getAction()) { case MotionEvent.ACTION_UP: if (!isVerticalScrollBarEnabled()) { setVerticalScrollBarEnabled(true); } if (getFirstVisiblePosition() == 0 && mRefreshState != REFRESHING) { if ((mRefreshView.getBottom() >= mRefreshViewHeight || mRefreshView.getTop() >= 0) && mRefreshState == RELEASE_TO_REFRESH) { mRefreshState = REFRESHING; prepareForRefresh(); onRefresh(); } else if (mRefreshView.getBottom() < mRefreshViewHeight || mRefreshView.getTop() <= 0) { resetHeader(); setSelection(1); } } break; case MotionEvent.ACTION_DOWN: mLastMotionY = y; break; case MotionEvent.ACTION_MOVE: applyHeaderPadding(event); break; } return super.onTouchEvent(event); } private void applyHeaderPadding(MotionEvent ev) { int pointerCount = ev.getHistorySize(); for (int p = 0; p < pointerCount; p++) { if (mRefreshState == RELEASE_TO_REFRESH) { if (isVerticalFadingEdgeEnabled()) { setVerticalScrollBarEnabled(false); } int historicalY = (int) ev.getHistoricalY(p); int topPadding = (int) (((historicalY - mLastMotionY) - mRefreshViewHeight) / 1.7); mRefreshView.setPadding( mRefreshView.getPaddingLeft(), topPadding, mRefreshView.getPaddingRight(), mRefreshView.getPaddingBottom()); } } } private void resetHeaderPadding() { mRefreshView.setPadding(mRefreshView.getPaddingLeft(), mRefreshOriginalTopPadding, mRefreshView.getPaddingRight(), mRefreshView.getPaddingBottom()); } private void resetHeader() { if (mRefreshState != TAP_TO_REFRESH) { mRefreshState = TAP_TO_REFRESH; resetHeaderPadding(); mRefreshViewText.setText(R.string.pull_to_refresh_tap_label); mRefreshViewImage.setImageResource(R.drawable.ic_pulltorefresh_arrow); mRefreshViewImage.clearAnimation(); mRefreshViewImage.setVisibility(View.GONE); mRefreshViewProgress.setVisibility(View.GONE); } } private void measureView(View child) { ViewGroup.LayoutParams p = child.getLayoutParams(); if (p == null) { p = new ViewGroup.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width); int lpHeight = p.height; int childHeightSpec; if (lpHeight > 0) { childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); } else { childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } child.measure(childWidthSpec, childHeightSpec); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (mCurrentScrollState == SCROLL_STATE_TOUCH_SCROLL && mRefreshState != REFRESHING) { if (firstVisibleItem == 0) { mRefreshViewImage.setVisibility(View.VISIBLE); if ((mRefreshView.getBottom() >= mRefreshViewHeight + 20 || mRefreshView.getTop() >= 0) && mRefreshState != RELEASE_TO_REFRESH) { mRefreshViewText.setText(R.string.pull_to_refresh_release_label); mRefreshViewImage.clearAnimation(); mRefreshViewImage.startAnimation(mFlipAnimation); mRefreshState = RELEASE_TO_REFRESH; } else if (mRefreshView.getBottom() < mRefreshViewHeight + 20 && mRefreshState != PULL_TO_REFRESH) { mRefreshViewText.setText(R.string.pull_to_refresh_pull_label); if (mRefreshState != TAP_TO_REFRESH) { mRefreshViewImage.clearAnimation(); mRefreshViewImage.startAnimation(mReverseFlipAnimation); } mRefreshState = PULL_TO_REFRESH; } } else { mRefreshViewImage.setVisibility(View.GONE); resetHeader(); } } else if (mCurrentScrollState == SCROLL_STATE_FLING && firstVisibleItem == 0 && mRefreshState != REFRESHING) { setSelection(1); mBounceHack = true; } else if (mBounceHack && mCurrentScrollState == SCROLL_STATE_FLING) { setSelection(1); } if (mOnScrollListener != null) { mOnScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount); } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { mCurrentScrollState = scrollState; if (mCurrentScrollState == SCROLL_STATE_IDLE) { mBounceHack = false; } if (mOnScrollListener != null) { mOnScrollListener.onScrollStateChanged(view, scrollState); } } public void prepareForRefresh() { resetHeaderPadding(); mRefreshViewImage.setVisibility(View.GONE); mRefreshViewImage.setImageDrawable(null); mRefreshViewProgress.setVisibility(View.VISIBLE); mRefreshViewText.setText(R.string.pull_to_refresh_refreshing_label); mRefreshState = REFRESHING; } public void onRefresh() { if (mOnRefreshListener != null) { mOnRefreshListener.onRefresh(); } } public void onRefreshComplete(CharSequence lastUpdated) { setLastUpdated(lastUpdated); onRefreshComplete(); } public void onRefreshComplete() { resetHeader(); if (mRefreshView.getBottom() > 0) { invalidateViews(); setSelection(1); } } public RelativeLayout getHeader() { return mRefreshView; } private class OnClickRefreshListener implements OnClickListener { @Override public void onClick(View v) { if (mRefreshState != REFRESHING) { prepareForRefresh(); onRefresh(); } } } public interface OnRefreshListener { public void onRefresh(); } }
Java
package com.outsourcing.bottle.widget; import android.content.Context; import android.util.AttributeSet; import android.widget.GridView; /** * * @author 06peng * */ public class CustomGridView extends GridView { public CustomGridView(Context context) { super(context); } public CustomGridView(Context context, AttributeSet attrs) { super(context, attrs); } public CustomGridView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); } }
Java
package com.outsourcing.bottle.widget; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.animation.AlphaAnimation; import android.widget.LinearLayout; import android.widget.ZoomButton; import com.outsourcing.bottle.R; public class CustomZoomControls extends LinearLayout { private final ZoomButton mZoomIn; private final ZoomButton mZoomOut; public CustomZoomControls(Context context) { this(context, null); } public CustomZoomControls(Context context, AttributeSet attrs) { super(context, attrs); setFocusable(false); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.zoom_controls, this, // we are the parent true); mZoomIn = (ZoomButton) findViewById(R.id.zoomIn); mZoomOut = (ZoomButton) findViewById(R.id.zoomOut); } public void setOnZoomInClickListener(OnClickListener listener) { mZoomIn.setOnClickListener(listener); } public void setOnZoomOutClickListener(OnClickListener listener) { mZoomOut.setOnClickListener(listener); } /* * Sets how fast you get zoom events when the user holds down the * zoom in/out buttons. */ public void setZoomSpeed(long speed) { mZoomIn.setZoomSpeed(speed); mZoomOut.setZoomSpeed(speed); } @Override public boolean onTouchEvent(MotionEvent event) { /* Consume all touch events so they don't get dispatched to the view * beneath this view. */ return true; } public void show() { fade(View.VISIBLE, 0.0f, 1.0f); } public void hide() { fade(View.GONE, 1.0f, 0.0f); } private void fade(int visibility, float startAlpha, float endAlpha) { AlphaAnimation anim = new AlphaAnimation(startAlpha, endAlpha); anim.setDuration(500); startAnimation(anim); setVisibility(visibility); } public void setIsZoomInEnabled(boolean isEnabled) { mZoomIn.setEnabled(isEnabled); } public void setIsZoomOutEnabled(boolean isEnabled) { mZoomOut.setEnabled(isEnabled); } @Override public boolean hasFocus() { return mZoomIn.hasFocus() || mZoomOut.hasFocus(); } }
Java
package com.outsourcing.bottle.widget; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.outsourcing.bottle.R; import com.outsourcing.bottle.ui.HomeActivity; import com.outsourcing.bottle.ui.fragment.FriendFragment; import com.outsourcing.bottle.util.AppContext; /** * * @author 06peng * */ public class ViewPagerIndicator extends RelativeLayout implements OnPageChangeListener { private static final int PADDING = 5; TextView mPrevious; public TextView mCurrent; TextView mNext; public int mCurItem; LinearLayout mPreviousGroup; LinearLayout mNextGroup; RelativeLayout mCurrentGroup; int mArrowPadding; int mSize; ImageView mCurrentIndicator; ImageView mPrevArrow; ImageView mNextArrow; int[] mFocusedTextColor; int[] mUnfocusedTextColor; OnClickListener mOnClickHandler; public Context context; public void setContext(Context context) { this.context = context; } public interface PageInfoProvider{ String getTitle(int pos); } public interface OnClickListener{ void onNextClicked(View v); void onPreviousClicked(View v); void onCurrentClicked(View v); } public void setOnClickListener(OnClickListener handler){ this.mOnClickHandler = handler; mPreviousGroup.setOnClickListener(new OnPreviousClickedListener()); mCurrent.setOnClickListener(new OnCurrentClickedListener()); mCurrentGroup.setOnClickListener(new OnCurrentClickedListener()); mNextGroup.setOnClickListener(new OnNextClickedListener()); } public int getCurrentPosition(){ return mCurItem; } PageInfoProvider mPageInfoProvider; public void setPageInfoProvider(PageInfoProvider pageInfoProvider){ this.mPageInfoProvider = pageInfoProvider; } /** * set the color of focused text * @param col */ public void setFocusedTextColor(int[] col){ System.arraycopy(col, 0, mFocusedTextColor, 0, 3); updateColor(0); } /** * set the color of unfocused text * @param col */ public void setUnfocusedTextColor(int[] col){ System.arraycopy(col, 0, mUnfocusedTextColor, 0, 3); mNext.setTextColor(Color.argb(255, col[0], col[1], col[2])); mPrevious.setTextColor(Color.argb(255, col[0], col[1], col[2])); updateColor(0); } public void setTextColor(int color){ mNext.setTextColor(color); mPrevious.setTextColor(color); mCurrent.setTextColor(color); updateColor(0); } /** * Initialization * * @param startPos The initially selected element in the ViewPager * @param size Total amount of elements in the ViewPager * @param pageInfoProvider Interface that returns page titles */ public void init(int startPos, int size, PageInfoProvider pageInfoProvider){ setPageInfoProvider(pageInfoProvider); this.mSize = size; setText(startPos - 1); mCurItem = startPos; } public ViewPagerIndicator(Context context, AttributeSet attrs) { super(context, attrs); addContent(); } public ViewPagerIndicator(Context context, AttributeSet attrs, int defStyle){ super(context, attrs, defStyle); addContent(); } public ViewPagerIndicator(Context context) { super(context); addContent(); } /** * Add drawables for arrows * * @param prev Left pointing arrow * @param next Right pointing arrow */ public void setArrows(Drawable prev, Drawable next){ this.mPrevArrow = new ImageView(getContext()); this.mPrevArrow.setImageDrawable(prev); this.mNextArrow = new ImageView(getContext()); this.mNextArrow.setImageDrawable(next); LinearLayout.LayoutParams arrowLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); arrowLayoutParams.gravity = Gravity.CENTER; mPreviousGroup.removeAllViews(); mPreviousGroup.addView(mPrevArrow, arrowLayoutParams); mPreviousGroup.addView(mPrevious, arrowLayoutParams); mPrevious.setPadding(PADDING, 0, 0, 0); mNext.setPadding(0, 0, PADDING, 0); mArrowPadding = PADDING + prev.getIntrinsicWidth(); mNextGroup.addView(mNextArrow, arrowLayoutParams); updateArrows(mCurItem); } /** * Create all views, build the layout */ private void addContent(){ mFocusedTextColor = new int[]{0, 0, 0}; mUnfocusedTextColor = new int[]{190, 190, 190}; // Text views mPrevious = new TextView(getContext()); mCurrent = new TextView(getContext()); mCurrent.setGravity(Gravity.CENTER); mCurrent.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.down_gray, 0); mCurrentGroup = new RelativeLayout(getContext()); mCurrentGroup.setBackgroundResource(R.drawable.buttle_selected); mCurrentGroup.setPadding(20, 10, 20, 10); LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); lp.addRule(RelativeLayout.CENTER_IN_PARENT); mCurrentGroup.addView(mCurrent, lp); mNext = new TextView(getContext()); RelativeLayout.LayoutParams previousParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); previousParams.addRule(RelativeLayout.ALIGN_LEFT); previousParams.addRule(RelativeLayout.CENTER_VERTICAL); RelativeLayout.LayoutParams currentParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); currentParams.addRule(RelativeLayout.CENTER_HORIZONTAL); currentParams.addRule(RelativeLayout.CENTER_VERTICAL); RelativeLayout.LayoutParams nextParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); nextParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); nextParams.addRule(RelativeLayout.CENTER_VERTICAL); // Groups holding text and arrows mPreviousGroup = new LinearLayout(getContext()); mPreviousGroup.setOrientation(LinearLayout.HORIZONTAL); mNextGroup = new LinearLayout(getContext()); mNextGroup.setOrientation(LinearLayout.HORIZONTAL); mPreviousGroup.addView(mPrevious, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); mNextGroup.addView(mNext, new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); addView(mPreviousGroup, previousParams); addView(mCurrentGroup, currentParams); addView(mNextGroup, nextParams); mPrevious.setSingleLine(); mCurrent.setSingleLine(); mNext.setSingleLine(); mPrevious.setText("previous"); mCurrent.setText("current"); mNext.setText("next"); mPrevious.setClickable(false); mNext.setClickable(false); mCurrent.setClickable(true); mPreviousGroup.setClickable(true); mNextGroup.setClickable(true); // Set colors mNext.setTextColor(Color.argb(255, mUnfocusedTextColor[0], mUnfocusedTextColor[1], mUnfocusedTextColor[2])); mPrevious.setTextColor(Color.argb(255, mUnfocusedTextColor[0], mUnfocusedTextColor[1], mUnfocusedTextColor[2])); updateColor(0); } @Override public void onPageScrollStateChanged(int state) { } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { positionOffsetPixels = adjustOffset(positionOffsetPixels); position = updatePosition(position, positionOffsetPixels); setText(position - 1); updateColor(positionOffsetPixels); updateArrows(position); updatePositions(positionOffsetPixels); } void updatePositions(int positionOffsetPixels){ int textWidth = mCurrent.getWidth() - mCurrent.getPaddingLeft() - mCurrent.getPaddingRight(); int maxOffset = this.getWidth() / 2 - textWidth / 2 - mArrowPadding; if(positionOffsetPixels > 0){ maxOffset -= this.getPaddingLeft(); int offset = Math.min(positionOffsetPixels, maxOffset - 1); mCurrent.setPadding(0, 0, 2 * offset, 0); // Move previous text out of the way. Slightly buggy. /* int overlapLeft = mPreviousGroup.getRight() - mCurrent.getLeft() + mArrowPadding; mPreviousGroup.setPadding(0, 0, Math.max(0, overlapLeft), 0); mNextGroup.setPadding(0, 0, 0, 0); */ }else{ maxOffset -= this.getPaddingRight(); int offset = Math.max(positionOffsetPixels, -maxOffset); mCurrent.setPadding(-2 * offset, 0, 0, 0); // Move next text out of the way. Slightly buggy. /* int overlapRight = mCurrent.getRight() - mNextGroup.getLeft() + mArrowPadding; mNextGroup.setPadding(Math.max(0, overlapRight), 0, 0, 0); mPreviousGroup.setPadding(0, 0, 0, 0); */ } } /** * Hide arrows if we can't scroll further * * @param position */ void updateArrows(int position){ if(mPrevArrow != null){ mPrevArrow.setVisibility(position == 0 ? View.INVISIBLE : View.VISIBLE); mNextArrow.setVisibility(position == mSize - 1 ? View.INVISIBLE : View.VISIBLE); } } /** * Adjust position to be the view that is showing the most. * * @param givenPosition * @param offset * @return */ int updatePosition(int givenPosition, int offset){ int pos; if(offset < 0){ pos = givenPosition + 1; }else{ pos = givenPosition; } return pos; } /** * Fade "currently showing" color depending on it's position * * @param offset */ void updateColor(int offset){ offset = Math.abs(offset); // Initial condition: offset is always 0, this.getWidth is also 0! 0/0 = NaN int width = this.getWidth(); float fraction = width == 0 ? 0 : offset / ((float)width / 4.0f); fraction = Math.min(1, fraction); int r = (int)(mUnfocusedTextColor[0] * fraction + mFocusedTextColor[0] * (1 - fraction)); int g = (int)(mUnfocusedTextColor[1] * fraction + mFocusedTextColor[1] * (1 - fraction)); int b = (int)(mUnfocusedTextColor[2] * fraction + mFocusedTextColor[2] * (1 - fraction)); mCurrent.setTextColor(Color.argb(255, r, g, b)); } /** * Update text depending on it's position * * @param prevPos */ void setText(int prevPos) { if (prevPos < 0) { mPrevious.setText(""); } else { mPrevious.setText(mPageInfoProvider.getTitle(prevPos)); } mCurrent.setText(mPageInfoProvider.getTitle(prevPos + 1)); if (prevPos + 2 == this.mSize) { mNext.setText(""); } else { mNext.setText(mPageInfoProvider.getTitle(prevPos + 2)); } } // Original: // 244, 245, 0, 1, 2 // New: // -2, -1, 0, 1, 2 int adjustOffset(int positionOffsetPixels){ // Move offset half width positionOffsetPixels += this.getWidth() / 2; // Clamp to width positionOffsetPixels %= this.getWidth(); // Center around zero positionOffsetPixels -= this.getWidth() / 2; return positionOffsetPixels; } @Override public void onPageSelected(int position) { // Reset padding when the page is finally selected (May not be necessary) mCurrent.setPadding(0, 0, 0, 0); mCurItem = position; System.out.println(">>>>>>>>>>>>>>ViewPagerIndicator onPageSelected:" + mCurItem); AppContext.getInstance().setCurrentItem(mCurItem); HomeActivity activity = (HomeActivity) context; if (mCurItem == 0) { if (activity.exchange_choices != null) { activity.titleView.setText(activity.exchange_choices[activity.exchange_item]); } else { activity.titleView.setText(""); } // activity.exchangeFragment.doGetExTimeline(); } else if (mCurItem == 1) { if (activity.bottle_choices != null) { activity.titleView.setText(activity.bottle_choices[activity.bottle_item]); } else { activity.titleView.setText(""); } // activity.bottleFragment.doGetBottleTimeline(); } else if (mCurItem == 2) { if (activity.friendFragment.getState() == FriendFragment.EXEU_GET_MYFRIEND_LIST_MORE || activity.friendFragment.getState() == FriendFragment.EXEU_GET_MYFRIEND_LIST) { if (activity.friend_choices != null) { activity.titleView.setText(activity.friend_choices[activity.friend_item]); } else { activity.titleView.setText(""); } } else { if (activity.friendFragment.groupNames != null) { activity.titleView .setText(activity.friendFragment.groupNames[activity.friendFragment.groupItem]); } else { activity.titleView.setText(""); } } // activity.friendFragment.doGetBTfriendList(); } } class OnPreviousClickedListener implements android.view.View.OnClickListener{ @Override public void onClick(View v) { if(mOnClickHandler != null){ mOnClickHandler.onPreviousClicked(ViewPagerIndicator.this); } } } class OnCurrentClickedListener implements android.view.View.OnClickListener{ @Override public void onClick(View v) { if(mOnClickHandler != null){ mOnClickHandler.onCurrentClicked(ViewPagerIndicator.this); } } } class OnNextClickedListener implements android.view.View.OnClickListener{ @Override public void onClick(View v) { if(mOnClickHandler != null){ mOnClickHandler.onNextClicked(ViewPagerIndicator.this); } } } }
Java
/* * Copyright (C) 2012 Capricorn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.outsourcing.bottle.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Rect; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.view.animation.AccelerateInterpolator; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationSet; import android.view.animation.Interpolator; import android.view.animation.LayoutAnimationController; import android.view.animation.LinearInterpolator; import android.view.animation.OvershootInterpolator; import android.view.animation.RotateAnimation; import com.outsourcing.bottle.R; /** * A Layout that arranges its children around its center. The arc can be set by * calling {@link #setArc(float, float) setArc()}. You can override the method * {@link #onMeasure(int, int) onMeasure()}, otherwise it is always * WRAP_CONTENT. * * @author Capricorn * */ public class ArcLayout extends ViewGroup { /** * children will be set the same size. */ private int mChildSize; private int mChildPadding = 5; private int mLayoutPadding = 10; public static final float DEFAULT_FROM_DEGREES = 270.0f; public static final float DEFAULT_TO_DEGREES = 360.0f; private float mFromDegrees = DEFAULT_FROM_DEGREES; private float mToDegrees = DEFAULT_TO_DEGREES; private static final int MIN_RADIUS = 100; /* the distance between the layout's center and any child's center */ private int mRadius; private boolean mExpanded = false; public ArcLayout(Context context) { super(context); } public ArcLayout(Context context, AttributeSet attrs) { super(context, attrs); if (attrs != null) { TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ArcLayout, 0, 0); mFromDegrees = a.getFloat(R.styleable.ArcLayout_fromDegrees, DEFAULT_FROM_DEGREES); mToDegrees = a.getFloat(R.styleable.ArcLayout_toDegrees, DEFAULT_TO_DEGREES); mChildSize = Math.max(a.getDimensionPixelSize(R.styleable.ArcLayout_childSize, 0), 0); a.recycle(); } } private static int computeRadius(final float arcDegrees, final int childCount, final int childSize, final int childPadding, final int minRadius) { if (childCount < 2) { return minRadius; } final float perDegrees = arcDegrees / (childCount - 1); final float perHalfDegrees = perDegrees / 2; final int perSize = childSize + childPadding; final int radius = (int) ((perSize / 2) / Math.sin(Math.toRadians(perHalfDegrees))); return Math.max(radius, minRadius); } private static Rect computeChildFrame(final int centerX, final int centerY, final int radius, final float degrees, final int size) { final double childCenterX = centerX + radius * Math.cos(Math.toRadians(degrees)); final double childCenterY = centerY + radius * Math.sin(Math.toRadians(degrees)); return new Rect((int) (childCenterX - size / 2), (int) (childCenterY - size / 2), (int) (childCenterX + size / 2), (int) (childCenterY + size / 2)); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int radius = mRadius = computeRadius(Math.abs(mToDegrees - mFromDegrees), getChildCount(), mChildSize, mChildPadding, MIN_RADIUS); final int size = radius * 2 + mChildSize + mChildPadding + mLayoutPadding * 2; setMeasuredDimension(size, size); final int count = getChildCount(); for (int i = 0; i < count; i++) { getChildAt(i).measure(MeasureSpec.makeMeasureSpec(mChildSize, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(mChildSize, MeasureSpec.EXACTLY)); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { final int centerX = getWidth() / 2; final int centerY = getHeight() / 2; final int radius = mExpanded ? mRadius : 0; final int childCount = getChildCount(); final float perDegrees = (mToDegrees - mFromDegrees) / (childCount - 1); float degrees = mFromDegrees; for (int i = 0; i < childCount; i++) { Rect frame = computeChildFrame(centerX, centerY, radius, degrees, mChildSize); degrees += perDegrees; getChildAt(i).layout(frame.left, frame.top, frame.right, frame.bottom); } } /** * refers to {@link LayoutAnimationController#getDelayForView(View view)} */ private static long computeStartOffset(final int childCount, final boolean expanded, final int index, final float delayPercent, final long duration, Interpolator interpolator) { final float delay = delayPercent * duration; final long viewDelay = (long) (getTransformedIndex(expanded, childCount, index) * delay); final float totalDelay = delay * childCount; float normalizedDelay = viewDelay / totalDelay; normalizedDelay = interpolator.getInterpolation(normalizedDelay); return (long) (normalizedDelay * totalDelay); } private static int getTransformedIndex(final boolean expanded, final int count, final int index) { if (expanded) { return count - 1 - index; } return index; } private static Animation createExpandAnimation(float fromXDelta, float toXDelta, float fromYDelta, float toYDelta, long startOffset, long duration, Interpolator interpolator) { Animation animation = new RotateAndTranslateAnimation(0, toXDelta, 0, toYDelta, 0, 720); animation.setStartOffset(startOffset); animation.setDuration(duration); animation.setInterpolator(interpolator); animation.setFillAfter(true); return animation; } private static Animation createShrinkAnimation(float fromXDelta, float toXDelta, float fromYDelta, float toYDelta, long startOffset, long duration, Interpolator interpolator) { AnimationSet animationSet = new AnimationSet(false); animationSet.setFillAfter(true); final long preDuration = duration / 2; Animation rotateAnimation = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); rotateAnimation.setStartOffset(startOffset); rotateAnimation.setDuration(preDuration); rotateAnimation.setInterpolator(new LinearInterpolator()); rotateAnimation.setFillAfter(true); animationSet.addAnimation(rotateAnimation); Animation translateAnimation = new RotateAndTranslateAnimation(0, toXDelta, 0, toYDelta, 360, 720); translateAnimation.setStartOffset(startOffset + preDuration); translateAnimation.setDuration(duration - preDuration); translateAnimation.setInterpolator(interpolator); translateAnimation.setFillAfter(true); animationSet.addAnimation(translateAnimation); return animationSet; } private void bindChildAnimation(final View child, final int index, final long duration) { final boolean expanded = mExpanded; final int centerX = getWidth() / 2; final int centerY = getHeight() / 2; final int radius = expanded ? 0 : mRadius; final int childCount = getChildCount(); final float perDegrees = (mToDegrees - mFromDegrees) / (childCount - 1); Rect frame = computeChildFrame(centerX, centerY, radius, mFromDegrees + index * perDegrees, mChildSize); final int toXDelta = frame.left - child.getLeft(); final int toYDelta = frame.top - child.getTop(); Interpolator interpolator = mExpanded ? new AccelerateInterpolator() : new OvershootInterpolator(1.5f); final long startOffset = computeStartOffset(childCount, mExpanded, index, 0.1f, duration, interpolator); Animation animation = mExpanded ? createShrinkAnimation(0, toXDelta, 0, toYDelta, startOffset, duration, interpolator) : createExpandAnimation(0, toXDelta, 0, toYDelta, startOffset, duration, interpolator); final boolean isLast = getTransformedIndex(expanded, childCount, index) == childCount - 1; animation.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { if (isLast) { postDelayed(new Runnable() { @Override public void run() { onAllAnimationsEnd(); } }, 0); } } }); child.setAnimation(animation); } public boolean isExpanded() { return mExpanded; } public void setArc(float fromDegrees, float toDegrees) { if (mFromDegrees == fromDegrees && mToDegrees == toDegrees) { return; } mFromDegrees = fromDegrees; mToDegrees = toDegrees; requestLayout(); } public void setChildSize(int size) { if (mChildSize == size || size < 0) { return; } mChildSize = size; requestLayout(); } /** * switch between expansion and shrinkage * * @param showAnimation */ public void switchState(final boolean showAnimation) { if (showAnimation) { final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { bindChildAnimation(getChildAt(i), i, 300); } } mExpanded = !mExpanded; if (!showAnimation) { requestLayout(); } } private void onAllAnimationsEnd() { final int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { getChildAt(i).clearAnimation(); } requestLayout(); } }
Java
/* * Copyright (C) 2012 Capricorn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.outsourcing.bottle.widget; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationSet; import android.view.animation.DecelerateInterpolator; import android.view.animation.RotateAnimation; import android.view.animation.ScaleAnimation; import android.widget.ImageView; import android.widget.RelativeLayout; import com.outsourcing.bottle.R; /** * A custom view that looks like the menu in <a href="https://path.com">Path * 2.0</a> (for iOS). * * @author Capricorn * */ public class ArcMenu extends RelativeLayout { private ArcLayout mArcLayout; private ImageView mHintView; public ArcMenu(Context context) { super(context); init(context); } public ArcMenu(Context context, AttributeSet attrs) { super(context, attrs); init(context); } private void init(Context context) { LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); li.inflate(R.layout.arc_menu, this); mArcLayout = (ArcLayout) findViewById(R.id.item_layout); final ViewGroup controlLayout = (ViewGroup) findViewById(R.id.control_layout); controlLayout.setClickable(true); controlLayout.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { mHintView.startAnimation(createHintSwitchAnimation(mArcLayout.isExpanded())); mArcLayout.switchState(true); } return false; } }); mHintView = (ImageView) findViewById(R.id.control_hint); } public void addItem(View item, OnClickListener listener) { mArcLayout.addView(item); item.setOnClickListener(getItemClickListener(listener)); } private OnClickListener getItemClickListener(final OnClickListener listener) { return new OnClickListener() { @Override public void onClick(final View viewClicked) { Animation animation = bindItemAnimation(viewClicked, true, 400); animation.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { postDelayed(new Runnable() { @Override public void run() { itemDidDisappear(); } }, 0); } }); final int itemCount = mArcLayout.getChildCount(); for (int i = 0; i < itemCount; i++) { View item = mArcLayout.getChildAt(i); if (viewClicked != item) { bindItemAnimation(item, false, 300); } } mArcLayout.invalidate(); mHintView.startAnimation(createHintSwitchAnimation(true)); if (listener != null) { listener.onClick(viewClicked); } } }; } private Animation bindItemAnimation(final View child, final boolean isClicked, final long duration) { Animation animation = createItemDisapperAnimation(duration, isClicked); child.setAnimation(animation); return animation; } private void itemDidDisappear() { final int itemCount = mArcLayout.getChildCount(); for (int i = 0; i < itemCount; i++) { View item = mArcLayout.getChildAt(i); item.clearAnimation(); } mArcLayout.switchState(false); } private static Animation createItemDisapperAnimation(final long duration, final boolean isClicked) { AnimationSet animationSet = new AnimationSet(true); animationSet.addAnimation(new ScaleAnimation(1.0f, isClicked ? 2.0f : 0.0f, 1.0f, isClicked ? 2.0f : 0.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)); animationSet.addAnimation(new AlphaAnimation(1.0f, 0.0f)); animationSet.setDuration(duration); animationSet.setInterpolator(new DecelerateInterpolator()); animationSet.setFillAfter(true); return animationSet; } private static Animation createHintSwitchAnimation(final boolean expanded) { Animation animation = new RotateAnimation(expanded ? 45 : 0, expanded ? 0 : 45, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); animation.setStartOffset(0); animation.setDuration(100); animation.setInterpolator(new DecelerateInterpolator()); animation.setFillAfter(true); return animation; } }
Java
package com.outsourcing.bottle.widget; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.outsourcing.bottle.R; public class IPhoneDialog extends Dialog { public IPhoneDialog(Context context, int theme) { super(context, theme); } public IPhoneDialog(Context context) { super(context); } /** * Helper class for creating a custom dialog */ public static class Builder { private Context context; private String title; private String message; private String positiveButtonText; private String negativeButtonText; private View contentView; private DialogInterface.OnClickListener positiveButtonClickListener, negativeButtonClickListener; public Builder(Context context) { this.context = context; } /** * Set the Dialog message from String * @param title * @return */ public Builder setMessage(String message) { this.message = message; return this; } /** * Set the Dialog message from resource * @param title * @return */ public Builder setMessage(int message) { this.message = (String) context.getText(message); return this; } /** * Set the Dialog title from resource * @param title * @return */ public Builder setTitle(int title) { this.title = (String) context.getText(title); return this; } /** * Set the Dialog title from String * @param title * @return */ public Builder setTitle(String title) { this.title = title; return this; } /** * Set a custom content view for the Dialog. * If a message is set, the contentView is not * added to the Dialog... * @param v * @return */ public Builder setContentView(View v) { this.contentView = v; return this; } /** * Set the positive button resource and it's listener * @param positiveButtonText * @param listener * @return */ public Builder setPositiveButton(int positiveButtonText, DialogInterface.OnClickListener listener) { this.positiveButtonText = (String) context .getText(positiveButtonText); this.positiveButtonClickListener = listener; return this; } /** * Set the positive button text and it's listener * @param positiveButtonText * @param listener * @return */ public Builder setPositiveButton(String positiveButtonText, DialogInterface.OnClickListener listener) { this.positiveButtonText = positiveButtonText; this.positiveButtonClickListener = listener; return this; } /** * Set the negative button resource and it's listener * @param negativeButtonText * @param listener * @return */ public Builder setNegativeButton(int negativeButtonText, DialogInterface.OnClickListener listener) { this.negativeButtonText = (String) context .getText(negativeButtonText); this.negativeButtonClickListener = listener; return this; } /** * Set the negative button text and it's listener * @param negativeButtonText * @param listener * @return */ public Builder setNegativeButton(String negativeButtonText, DialogInterface.OnClickListener listener) { this.negativeButtonText = negativeButtonText; this.negativeButtonClickListener = listener; return this; } /** * Create the custom dialog */ public IPhoneDialog create() { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); // instantiate the dialog with the custom Theme final IPhoneDialog dialog = new IPhoneDialog(context, R.style.iphone_Dialog); View layout = inflater.inflate(R.layout.iphone_dialog, null); dialog.addContentView(layout, new LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); // set the dialog title ((TextView) layout.findViewById(R.id.title)).setText(title); // set the confirm button if (positiveButtonText != null) { ((Button) layout.findViewById(R.id.positiveButton)) .setText(positiveButtonText); if (positiveButtonClickListener != null) { ((Button) layout.findViewById(R.id.positiveButton)) .setOnClickListener(new View.OnClickListener() { public void onClick(View v) { positiveButtonClickListener.onClick( dialog, DialogInterface.BUTTON_POSITIVE); } }); } } else { // if no confirm button just set the visibility to GONE layout.findViewById(R.id.positiveButton).setVisibility( View.GONE); } // set the cancel button if (negativeButtonText != null) { ((Button) layout.findViewById(R.id.negativeButton)) .setText(negativeButtonText); if (negativeButtonClickListener != null) { ((Button) layout.findViewById(R.id.negativeButton)) .setOnClickListener(new View.OnClickListener() { public void onClick(View v) { negativeButtonClickListener.onClick( dialog, DialogInterface.BUTTON_NEGATIVE); } }); } } else { // if no confirm button just set the visibility to GONE layout.findViewById(R.id.negativeButton).setVisibility( View.GONE); } // set the content message if (message != null) { ((TextView) layout.findViewById( R.id.message)).setText(message); } else if (contentView != null) { // if no message set // add the contentView to the dialog body ((LinearLayout) layout.findViewById(R.id.content)) .removeAllViews(); ((LinearLayout) layout.findViewById(R.id.content)) .addView(contentView, new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); } dialog.setContentView(layout); return dialog; } } }
Java
package com.outsourcing.bottle.widget; import java.text.DecimalFormat; import java.util.Observable; import java.util.Observer; import com.outsourcing.bottle.R; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.Log; import android.widget.ImageView; /** * * @author 06peng * */ public class ImageZoomView extends ImageView implements Observer { private final Paint mPaint = new Paint(Paint.FILTER_BITMAP_FLAG); private final Rect mRectSrc = new Rect(); private final Rect mRectDst = new Rect(); private float mAspectQuotient; private Bitmap mBitmap; private ZoomState mState; private static final String TAG = "PorterDuffView"; /** 前景Bitmap高度为1像素。采用循环多次填充进度区域。 */ public static final int FG_HEIGHT = 1; /** 下载进度前景色 */ // public static final int FOREGROUND_COLOR = 0x77123456; public static final int FOREGROUND_COLOR = 0x77ff0000; /** 下载进度条的颜色。 */ public static final int TEXT_COLOR = 0xff7fff00; /** 进度百分比字体大小。 */ public static final int FONT_SIZE = 30; private Bitmap bitmapBg, bitmapFg; private Paint paint; /** 标识当前进度。 */ private float progress; /** 标识进度图片的宽度与高度。 */ private int width, height; /** 格式化输出百分比。 */ private DecimalFormat decFormat; /** 进度百分比文本的锚定Y中心坐标值。 */ private float txtBaseY; /** 标识是否使用PorterDuff模式重组界面。 */ private boolean porterduffMode; /** 标识是否正在下载图片。 */ private boolean loading; /** 生成一宽与背景图片等同高为1像素的Bitmap,。 */ private static Bitmap createForegroundBitmap(int w) { Bitmap bm = Bitmap.createBitmap(w, FG_HEIGHT, Bitmap.Config.ARGB_8888); Canvas c = new Canvas(bm); Paint p = new Paint(Paint.ANTI_ALIAS_FLAG); p.setColor(FOREGROUND_COLOR); c.drawRect(0, 0, w, FG_HEIGHT, p); return bm; } private void init(Context context, AttributeSet attrs) { if (attrs != null) { TypedArray typedArr = context.obtainStyledAttributes(attrs, R.styleable.PorterDuffView); porterduffMode = typedArr.getBoolean(R.styleable.PorterDuffView_porterduffMode, false); } Drawable drawable = getDrawable(); if (porterduffMode && drawable != null && drawable instanceof BitmapDrawable) { bitmapBg = ((BitmapDrawable) drawable).getBitmap(); width = bitmapBg.getWidth(); height = bitmapBg.getHeight(); bitmapFg = createForegroundBitmap(width); } else { // 不符合要求,自动设置为false。 porterduffMode = false; } paint = new Paint(); paint.setFilterBitmap(false); paint.setAntiAlias(true); paint.setTextSize(FONT_SIZE); Paint.FontMetrics fontMetrics = paint.getFontMetrics(); // 注意观察本输出: // ascent:单个字符基线以上的推荐间距,为负数 Log.i(TAG, "ascent:" + fontMetrics.ascent// // descent:单个字符基线以下的推荐间距,为正数 + " descent:" + fontMetrics.descent // // 单个字符基线以上的最大间距,为负数 + " top:" + fontMetrics.top // // 单个字符基线以下的最大间距,为正数 + " bottom:" + fontMetrics.bottom// // 文本行与行之间的推荐间距 + " leading:" + fontMetrics.leading); // 在此处直接计算出来,避免了在onDraw()处的重复计算 txtBaseY = (height - fontMetrics.bottom - fontMetrics.top) / 2; decFormat = new DecimalFormat("0.0%"); } public ImageZoomView(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } public void setZoomState(ZoomState state) { if (mState != null) { mState.deleteObserver(this); } mState = state; mState.addObserver(this); invalidate(); } protected void onDraw(Canvas canvas) { if (porterduffMode && bitmapBg != null) { int tmpW = (getWidth() - width) / 2, tmpH = (getHeight() - height) / 2; // 画出背景图 canvas.drawBitmap(bitmapBg, tmpW, tmpH, paint); // 设置PorterDuff模式 paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DARKEN)); // canvas.drawBitmap(bitmapFg, tmpW, tmpH - progress * height, // paint); int tH = height - (int) (progress * height); for (int i = 0; i < tH; i++) { canvas.drawBitmap(bitmapFg, tmpW, tmpH + i, paint); } // 立即取消xfermode paint.setXfermode(null); int oriColor = paint.getColor(); paint.setColor(TEXT_COLOR); paint.setTextSize(FONT_SIZE); String tmp = decFormat.format(progress); float tmpWidth = paint.measureText(tmp); canvas.drawText(decFormat.format(progress), tmpW + (width - tmpWidth) / 2, tmpH + txtBaseY, paint); // 恢复为初始值时的颜色 paint.setColor(oriColor); } else { if (mBitmap != null && mState != null) { final int viewWidth = getWidth(); final int viewHeight = getHeight(); final int bitmapWidth = mBitmap.getWidth(); final int bitmapHeight = mBitmap.getHeight(); final float panX = mState.getPanX(); final float panY = mState.getPanY(); final float zoomX = mState.getZoomX(mAspectQuotient) * viewWidth / bitmapWidth; final float zoomY = mState.getZoomY(mAspectQuotient) * viewHeight / bitmapHeight; // Setup source and destination rectangles mRectSrc.left = (int) (panX * bitmapWidth - viewWidth / (zoomX * 2)); mRectSrc.top = (int) (panY * bitmapHeight - viewHeight / (zoomY * 2)); mRectSrc.right = (int) (mRectSrc.left + viewWidth / zoomX); mRectSrc.bottom = (int) (mRectSrc.top + viewHeight / zoomY); mRectDst.left = getLeft(); mRectDst.top = getTop(); mRectDst.right = getRight(); mRectDst.bottom = getBottom(); // Adjust source rectangle so that it fits within the source // image. if (mRectSrc.left < 0) { mRectDst.left += -mRectSrc.left * zoomX; mRectSrc.left = 0; } if (mRectSrc.right > bitmapWidth) { mRectDst.right -= (mRectSrc.right - bitmapWidth) * zoomX; mRectSrc.right = bitmapWidth; } if (mRectSrc.top < 0) { mRectDst.top += -mRectSrc.top * zoomY; mRectSrc.top = 0; } if (mRectSrc.bottom > bitmapHeight) { mRectDst.bottom -= (mRectSrc.bottom - bitmapHeight) * zoomY; mRectSrc.bottom = bitmapHeight; } canvas.drawBitmap(mBitmap, mRectSrc, mRectDst, mPaint); } } } public void update(Observable observable, Object data) { invalidate(); } private void calculateAspectQuotient() { if (mBitmap != null) { mAspectQuotient = (((float) mBitmap.getWidth()) / mBitmap .getHeight()) / (((float) getWidth()) / getHeight()); } } public void setImage(Bitmap bitmap) { mBitmap = bitmap; calculateAspectQuotient(); invalidate(); } public void invalidateImage() { initThumbnail(); invalidate(); porterduffMode = false; } private void initThumbnail() { Drawable drawable = getDrawable(); porterduffMode = true; if (porterduffMode && drawable != null && drawable instanceof BitmapDrawable) { bitmapBg = ((BitmapDrawable) drawable).getBitmap(); width = bitmapBg.getWidth(); height = bitmapBg.getHeight(); bitmapFg = createForegroundBitmap(width); } else { // 不符合要求,自动设置为false。 porterduffMode = false; } paint = new Paint(); paint.setFilterBitmap(false); paint.setAntiAlias(true); paint.setTextSize(FONT_SIZE); Paint.FontMetrics fontMetrics = paint.getFontMetrics(); // 注意观察本输出: // ascent:单个字符基线以上的推荐间距,为负数 Log.i(TAG, "ascent:" + fontMetrics.ascent// // descent:单个字符基线以下的推荐间距,为正数 + " descent:" + fontMetrics.descent // // 单个字符基线以上的最大间距,为负数 + " top:" + fontMetrics.top // // 单个字符基线以下的最大间距,为正数 + " bottom:" + fontMetrics.bottom// // 文本行与行之间的推荐间距 + " leading:" + fontMetrics.leading); // 在此处直接计算出来,避免了在onDraw()处的重复计算 txtBaseY = (height - fontMetrics.bottom - fontMetrics.top) / 2; decFormat = new DecimalFormat("0.0%"); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); calculateAspectQuotient(); } public void setProgress(float progress) { if (porterduffMode) { this.progress = progress; // 刷新自身。 invalidate(); } } public void setBitmap(Bitmap bg) { if (porterduffMode) { bitmapBg = bg; width = bitmapBg.getWidth(); height = bitmapBg.getHeight(); bitmapFg = createForegroundBitmap(width); Paint.FontMetrics fontMetrics = paint.getFontMetrics(); txtBaseY = (height - fontMetrics.bottom - fontMetrics.top) / 2; setImageBitmap(bg); // 请求重新布局,将会再次调用onMeasure() // requestLayout(); } } public boolean isLoading() { return loading; } public void setLoading(boolean loading) { this.loading = loading; } public void setPorterDuffMode(boolean bool) { porterduffMode = bool; } }
Java
package com.outsourcing.bottle.widget; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.LinearLayout; import android.widget.TextView; import com.outsourcing.bottle.R; /** * * Create custom Dialog windows for your application * Custom dialogs rely on custom layouts wich allow you to * create and use your own look & feel. * * Under GPL v3 : http://www.gnu.org/licenses/gpl-3.0.html * * @author antoine vianey * */ public class CustomDialog extends Dialog { public CustomDialog(Context context, int theme) { super(context, theme); } public CustomDialog(Context context) { super(context); } /** * Helper class for creating a custom dialog */ public static class Builder { private Context context; private String title; private String message; private String positiveButtonText; private String negativeButtonText; private View contentView; private DialogInterface.OnClickListener positiveButtonClickListener, negativeButtonClickListener; public Builder(Context context) { this.context = context; } /** * Set the Dialog message from String * @param title * @return */ public Builder setMessage(String message) { this.message = message; return this; } /** * Set the Dialog message from resource * @param title * @return */ public Builder setMessage(int message) { this.message = (String) context.getText(message); return this; } /** * Set the Dialog title from resource * @param title * @return */ public Builder setTitle(int title) { this.title = (String) context.getText(title); return this; } /** * Set the Dialog title from String * @param title * @return */ public Builder setTitle(String title) { this.title = title; return this; } /** * Set a custom content view for the Dialog. * If a message is set, the contentView is not * added to the Dialog... * @param v * @return */ public Builder setContentView(View v) { this.contentView = v; return this; } /** * Set the positive button resource and it's listener * @param positiveButtonText * @param listener * @return */ public Builder setPositiveButton(int positiveButtonText, DialogInterface.OnClickListener listener) { this.positiveButtonText = (String) context .getText(positiveButtonText); this.positiveButtonClickListener = listener; return this; } /** * Set the positive button text and it's listener * @param positiveButtonText * @param listener * @return */ public Builder setPositiveButton(String positiveButtonText, DialogInterface.OnClickListener listener) { this.positiveButtonText = positiveButtonText; this.positiveButtonClickListener = listener; return this; } /** * Set the negative button resource and it's listener * @param negativeButtonText * @param listener * @return */ public Builder setNegativeButton(int negativeButtonText, DialogInterface.OnClickListener listener) { this.negativeButtonText = (String) context .getText(negativeButtonText); this.negativeButtonClickListener = listener; return this; } /** * Set the negative button text and it's listener * @param negativeButtonText * @param listener * @return */ public Builder setNegativeButton(String negativeButtonText, DialogInterface.OnClickListener listener) { this.negativeButtonText = negativeButtonText; this.negativeButtonClickListener = listener; return this; } /** * Create the custom dialog */ public CustomDialog create() { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); // instantiate the dialog with the custom Theme final CustomDialog dialog = new CustomDialog(context, R.style.Dialog); View layout = inflater.inflate(R.layout.dialog, null); dialog.addContentView(layout, new LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); // set the dialog title // set the confirm button if (positiveButtonText != null) { // ((Button) layout.findViewById(R.id.positiveButton)) // .setText(positiveButtonText); // if (positiveButtonClickListener != null) { // ((Button) layout.findViewById(R.id.positiveButton)) // .setOnClickListener(new View.OnClickListener() { // public void onClick(View v) { // positiveButtonClickListener.onClick( // dialog, // DialogInterface.BUTTON_POSITIVE); // } // }); // } } else { // // if no confirm button just set the visibility to GONE // layout.findViewById(R.id.positiveButton).setVisibility( // View.GONE); } // set the cancel button if (negativeButtonText != null) { // ((Button) layout.findViewById(R.id.negativeButton)) // .setText(negativeButtonText); // if (negativeButtonClickListener != null) { // ((Button) layout.findViewById(R.id.negativeButton)) // .setOnClickListener(new View.OnClickListener() { // public void onClick(View v) { // negativeButtonClickListener.onClick( // dialog, // DialogInterface.BUTTON_NEGATIVE); // } // }); // } } else { // if no confirm button just set the visibility to GONE // layout.findViewById(R.id.negativeButton).setVisibility( // View.GONE); } // set the content message if (message != null) { ((TextView) layout.findViewById( R.id.message)).setText(message); } else if (contentView != null) { // if no message set // add the contentView to the dialog body ((LinearLayout) layout.findViewById(R.id.content)) .removeAllViews(); ((LinearLayout) layout.findViewById(R.id.content)) .addView(contentView, new LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); } dialog.setContentView(layout); return dialog; } } }
Java
package com.outsourcing.bottle.widget; import com.outsourcing.bottle.BasicActivity; import com.outsourcing.bottle.R; import com.outsourcing.bottle.util.AppContext; import android.view.MotionEvent; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.RelativeLayout; /** * * @author 06peng * */ public class SimpleZoomListener implements View.OnTouchListener { private RelativeLayout topBarView; private Animation inAnimation; private Animation outAnimation; public enum ControlType { PAN, ZOOM } private ZoomState mState; private float mX; private float mY; private float mGap; public void setZoomState(ZoomState state) { mState = state; topBarView = (RelativeLayout) ((BasicActivity) AppContext.getContext()).findViewById(R.id.qa_bar); inAnimation = AnimationUtils.loadAnimation(AppContext.getContext(), R.anim.alaph_bar_in); outAnimation = AnimationUtils.loadAnimation(AppContext.getContext(), R.anim.alaph_bar_out); } @SuppressWarnings("deprecation") public boolean onTouch(View v, MotionEvent event) { final int action = event.getAction(); int pointCount = event.getPointerCount(); if (pointCount == 1) { final float x = event.getX(); final float y = event.getY(); switch (action) { case MotionEvent.ACTION_DOWN: mX = x; mY = y; try { if (topBarView.getVisibility() == View.VISIBLE) { topBarView.startAnimation(outAnimation); topBarView.setVisibility(View.GONE); } else { topBarView.startAnimation(inAnimation); topBarView.setVisibility(View.VISIBLE); } } catch (Exception e) { e.printStackTrace(); } break; case MotionEvent.ACTION_MOVE: { final float dx = (x - mX) / v.getWidth(); final float dy = (y - mY) / v.getHeight(); mState.setPanX(mState.getPanX() - dx); mState.setPanY(mState.getPanY() - dy); mState.notifyObservers(); mX = x; mY = y; break; } } } if (pointCount == 2) { final float x0 = event.getX(event.getPointerId(0)); final float y0 = event.getY(event.getPointerId(0)); final float x1 = event.getX(event.getPointerId(1)); final float y1 = event.getY(event.getPointerId(1)); final float gap = getGap(x0, x1, y0, y1); switch (action) { case MotionEvent.ACTION_POINTER_2_DOWN: case MotionEvent.ACTION_POINTER_1_DOWN: mGap = gap; break; case MotionEvent.ACTION_POINTER_1_UP: mX = x1; mY = y1; break; case MotionEvent.ACTION_POINTER_2_UP: mX = x0; mY = y0; break; case MotionEvent.ACTION_MOVE: final float dgap = (gap - mGap) / mGap; if (mState.getZoom() < 0.5) { mState.setZoom(0.5f); } else if (mState.getZoom() > 100f) { mState.setZoom(98f); } else { mState.setZoom(mState.getZoom() * (float) Math.pow(2, dgap)); } mState.notifyObservers(); mGap = gap; break; } } return true; } private float getGap(float x0, float x1, float y0, float y1) { return (float) Math.pow(Math.pow((x0 - x1), 2) + Math.pow((y0 - y1), 2), 0.5); } }
Java
package com.outsourcing.bottle.widget; import java.util.Date; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.ScrollView; import android.widget.TextView; import com.outsourcing.bottle.R; import com.outsourcing.bottle.util.AppContext; public class ElasticScrollView extends ScrollView { private static final String TAG = "ElasticScrollView"; private final static int RELEASE_To_REFRESH = 0; private final static int PULL_To_REFRESH = 1; private final static int REFRESHING = 2; private final static int DONE = 3; private final static int LOADING = 4; // 实际的padding的距离与界面上偏移距离的比例 private final static int RATIO = 3; private int headContentWidth; private int headContentHeight; private LinearLayout innerLayout; private LinearLayout headView; private ImageView arrowImageView; private ProgressBar progressBar; private TextView tipsTextview; private TextView lastUpdatedTextView; private OnRefreshListener refreshListener; private boolean isRefreshable; private int state; private boolean isBack; private RotateAnimation animation; private RotateAnimation reverseAnimation; private boolean canReturn; private boolean isRecored; private int startY; private ProgressBar moreProgressBar; private TextView loadMoreView; private View moreView; private boolean moreCount; private boolean isLoadingMore; private Context context; public ElasticScrollView(Context context) { super(context); init(context); } public ElasticScrollView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } private void init(Context context) { this.context = context; LayoutInflater inflater = LayoutInflater.from(context); innerLayout = new LinearLayout(context); innerLayout.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); innerLayout.setOrientation(LinearLayout.VERTICAL); headView = (LinearLayout) inflater.inflate(R.layout.mylistview_head, null); arrowImageView = (ImageView) headView.findViewById(R.id.head_arrowImageView); progressBar = (ProgressBar) headView.findViewById(R.id.head_progressBar); tipsTextview = (TextView) headView.findViewById(R.id.head_tipsTextView); lastUpdatedTextView = (TextView) headView.findViewById(R.id.head_lastUpdatedTextView); measureView(headView); headContentHeight = headView.getMeasuredHeight(); headContentWidth = headView.getMeasuredWidth(); headView.setPadding(0, -1 * headContentHeight, 0, 0); headView.invalidate(); Log.i("size", "width:" + headContentWidth + " height:" + headContentHeight); innerLayout.addView(headView); addView(innerLayout); animation = new RotateAnimation(0, -180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); animation.setInterpolator(new LinearInterpolator()); animation.setDuration(250); animation.setFillAfter(true); reverseAnimation = new RotateAnimation(-180, 0, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); reverseAnimation.setInterpolator(new LinearInterpolator()); reverseAnimation.setDuration(200); reverseAnimation.setFillAfter(true); state = DONE; isRefreshable = false; canReturn = false; moreView = LayoutInflater.from(context).inflate(R.layout.listfooter_more, null); moreView.setVisibility(View.GONE); moreProgressBar = (ProgressBar) moreView.findViewById(R.id.pull_to_refresh_progress); loadMoreView = (TextView) moreView.findViewById(R.id.load_more); } @Override public boolean onTouchEvent(MotionEvent event) { if (isRefreshable) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (getScrollY() == 0 && !isRecored) { isRecored = true; startY = (int) event.getY(); Log.i(TAG, "在down时候记录当前位置‘"); } break; case MotionEvent.ACTION_UP: if (state != REFRESHING && state != LOADING) { if (state == DONE) { // 什么都不做 } if (state == PULL_To_REFRESH) { state = DONE; changeHeaderViewByState(); Log.i(TAG, "由下拉刷新状态,到done状态"); } if (state == RELEASE_To_REFRESH) { state = REFRESHING; changeHeaderViewByState(); onRefresh(); Log.i(TAG, "由松开刷新状态,到done状态"); } } isRecored = false; isBack = false; break; case MotionEvent.ACTION_MOVE: int tempY = (int) event.getY(); if (!isRecored && getScrollY() == 0) { Log.i(TAG, "在move时候记录下位置"); isRecored = true; startY = tempY; } if (state != REFRESHING && isRecored && state != LOADING) { // 可以松手去刷新了 if (state == RELEASE_To_REFRESH) { canReturn = true; if (((tempY - startY) / RATIO < headContentHeight) && (tempY - startY) > 0) { state = PULL_To_REFRESH; changeHeaderViewByState(); Log.i(TAG, "由松开刷新状态转变到下拉刷新状态"); } // 一下子推到顶了 else if (tempY - startY <= 0) { state = DONE; changeHeaderViewByState(); Log.i(TAG, "由松开刷新状态转变到done状态"); } else { // 不用进行特别的操作,只用更新paddingTop的值就行了 } } // 还没有到达显示松开刷新的时候,DONE或者是PULL_To_REFRESH状态 if (state == PULL_To_REFRESH) { canReturn = true; // 下拉到可以进入RELEASE_TO_REFRESH的状态 if ((tempY - startY) / RATIO >= headContentHeight) { state = RELEASE_To_REFRESH; isBack = true; changeHeaderViewByState(); Log.i(TAG, "由done或者下拉刷新状态转变到松开刷新"); } // 上推到顶了 else if (tempY - startY <= 0) { state = DONE; changeHeaderViewByState(); Log.i(TAG, "由DOne或者下拉刷新状态转变到done状态"); } } // done状态下 if (state == DONE) { if (tempY - startY > 0) { state = PULL_To_REFRESH; changeHeaderViewByState(); } } // 更新headView的size if (state == PULL_To_REFRESH) { headView.setPadding(0, -1 * headContentHeight + (tempY - startY) / RATIO, 0, 0); } // 更新headView的paddingTop if (state == RELEASE_To_REFRESH) { headView.setPadding(0, (tempY - startY) / RATIO - headContentHeight, 0, 0); } if (canReturn) { canReturn = false; return true; } } break; } } return super.onTouchEvent(event); } // 当状态改变时候,调用该方法,以更新界面 private void changeHeaderViewByState() { switch (state) { case RELEASE_To_REFRESH: arrowImageView.setVisibility(View.VISIBLE); progressBar.setVisibility(View.GONE); tipsTextview.setVisibility(View.VISIBLE); lastUpdatedTextView.setVisibility(View.VISIBLE); arrowImageView.clearAnimation(); arrowImageView.startAnimation(animation); tipsTextview.setText(context.getString(R.string.scrollview_to_refresh_release_label)); Log.i(TAG, "当前状态,松开刷新"); break; case PULL_To_REFRESH: progressBar.setVisibility(View.GONE); tipsTextview.setVisibility(View.VISIBLE); lastUpdatedTextView.setVisibility(View.VISIBLE); arrowImageView.clearAnimation(); arrowImageView.setVisibility(View.VISIBLE); // 是由RELEASE_To_REFRESH状态转变来的 if (isBack) { isBack = false; arrowImageView.clearAnimation(); arrowImageView.startAnimation(reverseAnimation); tipsTextview.setText(context.getString(R.string.scrollview_to_refresh_pull_label)); } else { // tipsTextview.setText("下拉刷新"); tipsTextview.setText(context.getString(R.string.scrollview_to_refresh_pull_label)); } Log.i(TAG, "当前状态,下拉刷新"); break; case REFRESHING: headView.setPadding(0, 0, 0, 0); progressBar.setVisibility(View.VISIBLE); arrowImageView.clearAnimation(); arrowImageView.setVisibility(View.GONE); tipsTextview.setText(context.getString(R.string.scrollview_to_refreshing_label)); lastUpdatedTextView.setVisibility(View.VISIBLE); Log.i(TAG, "当前状态,正在刷新..."); break; case DONE: headView.setPadding(0, -1 * headContentHeight, 0, 0); progressBar.setVisibility(View.GONE); arrowImageView.clearAnimation(); arrowImageView.setImageResource(R.drawable.goicon); tipsTextview.setText(context.getString(R.string.scrollview_to_refresh_pull_label)); lastUpdatedTextView.setVisibility(View.VISIBLE); Log.i(TAG, "当前状态,done"); break; } } private void measureView(View child) { ViewGroup.LayoutParams p = child.getLayoutParams(); if (p == null) { p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width); int lpHeight = p.height; int childHeightSpec; if (lpHeight > 0) { childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); } else { childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } child.measure(childWidthSpec, childHeightSpec); } public void setonRefreshListener(OnRefreshListener refreshListener) { this.refreshListener = refreshListener; isRefreshable = true; } public interface OnRefreshListener { public void onRefresh(); } public void onRefreshComplete() { state = DONE; lastUpdatedTextView.setText(context.getString(R.string.scrollview_to_refresh_lasttime_label) + new Date().toLocaleString()); changeHeaderViewByState(); invalidate(); scrollTo(0, 0); } private void onRefresh() { if (refreshListener != null) { refreshListener.onRefresh(); } } public interface OnScrollChangeBottom { public void onScrollBottom(); } private OnScrollChangeBottom onScrollListener; public void setonScrollChangeListener(OnScrollChangeBottom onScrollListener) { this.onScrollListener = onScrollListener; } private void onScrollBottom() { if (onScrollListener != null) { onScrollListener.onScrollBottom(); } } public void onScrollChangeComplete() { isLoadingMore = false; moreProgressBar.setVisibility(View.GONE); loadMoreView.setText(AppContext.getContext().getString(R.string.more_data)); } public void setMoreCount(boolean moreCount) { this.moreCount = moreCount; } public void removeChild(View child) { innerLayout.removeView(child); } public void removeChild() { // innerLayout.removeAllViews(); innerLayout.removeViewAt(1); } public void addChild(View child) { innerLayout.addView(child); innerLayout.addView(moreView); } public void addChild(View child, int position) { innerLayout.addView(child, position); innerLayout.addView(moreView); } @Override protected void onScrollChanged(int l, int t, int oldl, int oldt) { super.onScrollChanged(l, t, oldl, oldt); if (t + getHeight() >= computeVerticalScrollRange()) { if (moreCount) { System.out.println("----------------scroll bottom----------------"); moreView.setVisibility(View.VISIBLE); moreProgressBar.setVisibility(View.VISIBLE); loadMoreView.setText(AppContext.getContext().getString(R.string.load_more)); if (!isLoadingMore) { onScrollBottom(); } isLoadingMore = true; } else { moreView.setVisibility(View.GONE); } } } }
Java
package com.outsourcing.bottle.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.os.Handler; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewConfiguration; import android.view.animation.Animation; import android.view.animation.Animation.AnimationListener; import android.view.animation.AnimationUtils; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.ListView; import com.outsourcing.bottle.R; public class ExtendedListView extends ListView implements OnScrollListener { public static interface OnPositionChangedListener { public void onPositionChanged(ExtendedListView listView, int position, View scrollBarPanel); public void onScollPositionChanged(View scrollBarPanel,int top); } private OnScrollListener mOnScrollListener = null; private View mScrollBarPanel = null; private int mScrollBarPanelPosition = 0; private OnPositionChangedListener mPositionChangedListener; private int mLastPosition = -1; private Animation mInAnimation = null; private Animation mOutAnimation = null; private final Handler mHandler = new Handler(); private final Runnable mScrollBarPanelFadeRunnable = new Runnable() { @Override public void run() { if (mOutAnimation != null) { // mScrollBarPanel.startAnimation(mOutAnimation); } } }; /* * keep track of Measure Spec */ private int mWidthMeasureSpec; private int mHeightMeasureSpec; public ExtendedListView(Context context) { this(context, null); } public ExtendedListView(Context context, AttributeSet attrs) { this(context, attrs, android.R.attr.listViewStyle); } public ExtendedListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); super.setOnScrollListener(this); final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ExtendedListView); final int scrollBarPanelLayoutId = a.getResourceId( R.styleable.ExtendedListView_scrollBarPanel, -1); final int scrollBarPanelInAnimation = a.getResourceId( R.styleable.ExtendedListView_scrollBarPanelInAnimation, R.anim.in_animation); final int scrollBarPanelOutAnimation = a.getResourceId( R.styleable.ExtendedListView_scrollBarPanelOutAnimation, R.anim.out_animation); a.recycle(); if (scrollBarPanelLayoutId != -1) { setScrollBarPanel(scrollBarPanelLayoutId); } final int scrollBarPanelFadeDuration = ViewConfiguration.getScrollBarFadeDuration(); if (scrollBarPanelInAnimation > 0) { mInAnimation = AnimationUtils.loadAnimation(getContext(), scrollBarPanelInAnimation); } if (scrollBarPanelOutAnimation > 0) { mOutAnimation = AnimationUtils.loadAnimation(getContext(), scrollBarPanelOutAnimation); mOutAnimation.setDuration(scrollBarPanelFadeDuration); mOutAnimation.setAnimationListener(new AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { if (mScrollBarPanel != null) { mScrollBarPanel.setVisibility(View.GONE); } } }); } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { if (mOnScrollListener != null) { mOnScrollListener.onScrollStateChanged(view, scrollState); } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (null != mPositionChangedListener && null != mScrollBarPanel) { // Don't do anything if there is no itemviews if (totalItemCount > 0) { /* * from android source code (ScrollBarDrawable.java) */ final int thickness = getVerticalScrollbarWidth(); int height = Math.round((float) getMeasuredHeight() * computeVerticalScrollExtent() / computeVerticalScrollRange()); int thumbOffset = Math.round((float) (getMeasuredHeight() - height) * computeVerticalScrollOffset() / (computeVerticalScrollRange() - computeVerticalScrollExtent())); final int minLength = thickness * 2; if (height < minLength) { height = minLength; } thumbOffset += height / 2; /* * find out which itemviews the center of thumb is on */ final int count = getChildCount(); for (int i = 0; i < count; ++i) { final View childView = getChildAt(i); if (childView != null) { if (thumbOffset > childView.getTop() && thumbOffset < childView.getBottom()) { /* * we have our candidate */ if (mLastPosition != firstVisibleItem + i) { mLastPosition = firstVisibleItem + i; /* * inform the position of the panel has changed */ mPositionChangedListener.onPositionChanged(this, mLastPosition, mScrollBarPanel); /* * measure panel right now since it has just * changed INFO: quick hack to handle TextView * has ScrollBarPanel (to wrap text in case * TextView's content has changed) */ measureChild(mScrollBarPanel, mWidthMeasureSpec, mHeightMeasureSpec); } break; } } } /* * update panel position */ mScrollBarPanelPosition = thumbOffset - mScrollBarPanel.getMeasuredHeight() / 2; final int x = getMeasuredWidth() - mScrollBarPanel.getMeasuredWidth() - getVerticalScrollbarWidth(); System.out.println("left==" + x + " top==" + mScrollBarPanelPosition + " bottom==" + (x + mScrollBarPanel.getMeasuredWidth()) + " right==" + (mScrollBarPanelPosition + mScrollBarPanel.getMeasuredHeight())); mScrollBarPanel.layout(x, mScrollBarPanelPosition, x + mScrollBarPanel.getMeasuredWidth(), mScrollBarPanelPosition + mScrollBarPanel.getMeasuredHeight()); mPositionChangedListener.onScollPositionChanged(this, mScrollBarPanelPosition); } } if (mOnScrollListener != null) { mOnScrollListener.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount); } } public void setOnPositionChangedListener(OnPositionChangedListener onPositionChangedListener) { mPositionChangedListener = onPositionChangedListener; } @Override public void setOnScrollListener(OnScrollListener onScrollListener) { mOnScrollListener = onScrollListener; } public void setScrollBarPanel(View scrollBarPanel) { mScrollBarPanel = scrollBarPanel; mScrollBarPanel.setVisibility(View.GONE); requestLayout(); } public void setScrollBarPanel(int resId) { setScrollBarPanel(LayoutInflater.from(getContext()).inflate(resId, this, false)); } public View getScrollBarPanel() { return mScrollBarPanel; } @Override protected boolean awakenScrollBars(int startDelay, boolean invalidate) { final boolean isAnimationPlayed = super.awakenScrollBars(startDelay, invalidate); if (isAnimationPlayed == true && mScrollBarPanel != null) { if (mScrollBarPanel.getVisibility() == View.GONE) { // mScrollBarPanel.setVisibility(View.VISIBLE); if (mInAnimation != null) { // mScrollBarPanel.startAnimation(mInAnimation); } } mHandler.removeCallbacks(mScrollBarPanelFadeRunnable); mHandler.postAtTime(mScrollBarPanelFadeRunnable, AnimationUtils.currentAnimationTimeMillis() + startDelay); } return isAnimationPlayed; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); System.out.println("onMeasure......................."); if (mScrollBarPanel != null && getAdapter() != null) { mWidthMeasureSpec = widthMeasureSpec; mHeightMeasureSpec = heightMeasureSpec; measureChild(mScrollBarPanel, widthMeasureSpec, heightMeasureSpec); } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); System.out.println("onLayout......................."); if (mScrollBarPanel != null) { final int x = getMeasuredWidth() - mScrollBarPanel.getMeasuredWidth() - getVerticalScrollbarWidth(); mScrollBarPanel.layout(x, mScrollBarPanelPosition, x + mScrollBarPanel.getMeasuredWidth(), mScrollBarPanelPosition + mScrollBarPanel.getMeasuredHeight()); } } @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); System.out.println("dispatchDraw......................."); if (mScrollBarPanel != null && mScrollBarPanel.getVisibility() == View.VISIBLE) { drawChild(canvas, mScrollBarPanel, getDrawingTime()); } } @Override public void onDetachedFromWindow() { super.onDetachedFromWindow(); System.out.println("onDetachedFromWindow......................."); mHandler.removeCallbacks(mScrollBarPanelFadeRunnable); } }
Java
package com.outsourcing.bottle.widget; import android.content.Context; import android.os.Handler; import android.util.AttributeSet; import android.view.View; import android.widget.ScrollView; /** * * @author taro * */ public class TryPullToRefreshScrollView extends ScrollView { public TryPullToRefreshScrollView(Context context) { super(context); init(context); } public TryPullToRefreshScrollView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public TryPullToRefreshScrollView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); } private void init(Context context) { } public static void ScrollToPoint(final View scroll, final View inner,final int i) { Handler mHandler = new Handler(); mHandler.post(new Runnable() { public void run() { if (scroll == null || inner == null) { return; } int offset =inner.getMeasuredHeight() - scroll.getHeight()-i; if (offset < 0) { offset = 0; } scroll.scrollTo(0, offset); scroll.invalidate(); } }); } }
Java
package com.outsourcing.bottle.widget; import java.util.Observable; /** * * @author 06peng * */ public class ZoomState extends Observable { private float mZoom; private float mPanX; private float mPanY; public float getPanX() { return mPanX; } public float getPanY() { return mPanY; } public float getZoom() { return mZoom; } public void setPanX(float panX) { if (panX != mPanX) { mPanX = panX; setChanged(); } } public void setPanY(float panY) { if (panY != mPanY) { mPanY = panY; setChanged(); } } public void setZoom(float zoom) { if (zoom != mZoom) { mZoom = zoom; setChanged(); } } public float getZoomX(float aspectQuotient) { return Math.min(mZoom, mZoom * aspectQuotient); } public float getZoomY(float aspectQuotient) { return Math.min(mZoom, mZoom / aspectQuotient); } }
Java
package com.outsourcing.bottle.widget; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListView; /** * 自定义的ListView * @author 06peng * */ public class CustomScrollListView extends ListView { private List<Object> mListData; private List<View> mAllListView; private InitScrollListViewListener listener; public CustomScrollListView(Context context) { super(context); } public CustomScrollListView(Context context, AttributeSet attrs) { super(context, attrs); } public CustomScrollListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public interface InitScrollListViewListener { public void initListView(List<View> mAllListView, List<Object> mListData); } public void setInitScrollListViewListener(InitScrollListViewListener listener) { this.listener = listener; } private void initListView(List<View> mAllListView, List<Object> mListData) { if (listener != null) { listener.initListView(mAllListView, mListData); } } public void setAdapter() { if (mAllListView == null) { mAllListView = new ArrayList<View>(); } if (mListData == null) { mListData = new ArrayList<Object>(); } initListView(mAllListView, mListData); if (!mAllListView.isEmpty()) { ScrollListAdapter apdater = new ScrollListAdapter(); setAdapter(apdater); } } public class ScrollListAdapter extends BaseAdapter { @Override public int getCount() { return mListData == null ? 0 : mListData.size(); } @Override public Object getItem(int position) { return mListData == null ? null : mListData.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { return mAllListView == null ? null : mAllListView.get(position); } } }
Java
package com.outsourcing.bottle.widget; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.GestureDetector; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.outsourcing.bottle.R; public class PullToRefreshListView extends ListView implements OnScrollListener, GestureDetector.OnGestureListener { private final int MAXHEIGHT = 20; private static final int TAP_TO_REFRESH = 1; private static final int PULL_TO_REFRESH = 2; private static final int RELEASE_TO_REFRESH = 3; private static final int REFRESHING = 4; // private static final int RELEASING = 5;//释放过程做动画用 private static final String TAG = "PullToRefreshListView"; private OnRefreshListener mOnRefreshListener; /** * Listener that will receive notifications every time the list scrolls. */ private OnScrollListener mOnScrollListener; private LayoutInflater mInflater; private LinearLayout mRefreshView; private TextView mRefreshViewText; private ImageView mRefreshViewImage; private ProgressBar mRefreshViewProgress; private TextView mRefreshViewLastUpdated; private int mCurrentScrollState; private int mRefreshState; private RotateAnimation mFlipAnimation; private RotateAnimation mReverseFlipAnimation; private int mRefreshViewHeight; private int mRefreshOriginalTopPadding; private int mLastMotionY; private GestureDetector mDetector; // private int mPadding; public PullToRefreshListView(Context context) { super(context); init(context); } public PullToRefreshListView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } public PullToRefreshListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); } private void init(Context context) { GestureDetector localGestureDetector = new GestureDetector(this); this.mDetector = localGestureDetector; // Load all of the animations we need in code rather than through XML mFlipAnimation = new RotateAnimation(0, -180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); mFlipAnimation.setInterpolator(new LinearInterpolator()); mFlipAnimation.setDuration(200); mFlipAnimation.setFillAfter(true); mReverseFlipAnimation = new RotateAnimation(-180, 0, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); mReverseFlipAnimation.setInterpolator(new LinearInterpolator()); mReverseFlipAnimation.setDuration(200); mReverseFlipAnimation.setFillAfter(true); mInflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); mRefreshView = (LinearLayout) mInflater.inflate( R.layout.pull_to_refresh_header, null); mRefreshViewText = (TextView) mRefreshView .findViewById(R.id.pull_to_refresh_text); mRefreshViewImage = (ImageView) mRefreshView .findViewById(R.id.pull_to_refresh_image); mRefreshViewProgress = (ProgressBar) mRefreshView .findViewById(R.id.pull_to_refresh_progress); mRefreshViewLastUpdated = (TextView) mRefreshView .findViewById(R.id.pull_to_refresh_updated_at); mRefreshViewImage.setMinimumHeight(50); mRefreshView.setOnClickListener(new OnClickRefreshListener()); mRefreshOriginalTopPadding = mRefreshView.getPaddingTop(); mRefreshState = TAP_TO_REFRESH; addHeaderView(mRefreshView); super.setOnScrollListener(this); measureView(mRefreshView); mRefreshViewHeight = mRefreshView.getMeasuredHeight(); } @Override public void setAdapter(ListAdapter adapter) { super.setAdapter(adapter); setSelection(1); } /** * Set the listener that will receive notifications every time the list * scrolls. * * @param l * The scroll listener. */ @Override public void setOnScrollListener(AbsListView.OnScrollListener l) { mOnScrollListener = l; } /** * Register a callback to be invoked when this list should be refreshed. * * @param onRefreshListener * The callback to run. */ public void setOnRefreshListener(OnRefreshListener onRefreshListener) { mOnRefreshListener = onRefreshListener; } /** * Set a text to represent when the list was last updated. * * @param lastUpdated * Last updated at. */ public void setLastUpdated(CharSequence lastUpdated) { if (lastUpdated != null) { mRefreshViewLastUpdated.setVisibility(View.VISIBLE); mRefreshViewLastUpdated.setText(lastUpdated); } else { mRefreshViewLastUpdated.setVisibility(View.GONE); } } @Override /** * TODO:此方法重写 */ public boolean onTouchEvent(MotionEvent event) { GestureDetector localGestureDetector = this.mDetector; localGestureDetector.onTouchEvent(event); int y = 0; try { y = (int) event.getY(); } catch (Exception e) { e.printStackTrace(); } Log.d(TAG, String.format( "[onTouchEvent]event.Action=%d, currState=%d, refreshState=%d,y=%d", event.getAction(), mCurrentScrollState, mRefreshState, y)); switch (event.getAction()) { case MotionEvent.ACTION_UP: if (!isVerticalScrollBarEnabled()) { setVerticalScrollBarEnabled(true); } if (getFirstVisiblePosition() == 0 && mRefreshState != REFRESHING) { if ((mRefreshView.getBottom() >= mRefreshViewHeight + MAXHEIGHT || mRefreshView .getTop() >= 0)) { // Initiate the refresh mRefreshState = REFRESHING; prepareForRefresh(); onRefresh(); } else if (mRefreshView.getBottom() < mRefreshViewHeight + MAXHEIGHT || mRefreshView.getTop() <= 0) { // Abort refresh and scroll down below the refresh view resetHeader(); setSelection(1); } } break; case MotionEvent.ACTION_DOWN: mLastMotionY = y; break; case MotionEvent.ACTION_MOVE: applyHeaderPadding(event); break; } return super.onTouchEvent(event); } /** * TODO:此方法重写 * @param ev */ private void applyHeaderPadding(MotionEvent ev) { final int historySize = ev.getHistorySize(); Log.d(TAG, String.format( "[applyHeaderPadding]currState=%d, refreshState=%d", mCurrentScrollState, mRefreshState)); // Workaround for getPointerCount() which is unavailable in 1.5 // (it's always 1 in 1.5) int pointerCount = 1; try { Method method = MotionEvent.class.getMethod("getPointerCount"); pointerCount = (Integer) method.invoke(ev); } catch (NoSuchMethodException e) { pointerCount = 1; } catch (IllegalArgumentException e) { throw e; } catch (IllegalAccessException e) { System.err.println("unexpected " + e); } catch (InvocationTargetException e) { System.err.println("unexpected " + e); } if (mRefreshState == RELEASE_TO_REFRESH) { // this.offsetTopAndBottom(-mPadding); for (int h = 0; h < historySize; h++) { for (int p = 0; p < pointerCount; p++) { if (isVerticalFadingEdgeEnabled()) { setVerticalScrollBarEnabled(false); } int historicalY = 0; try { // For Android > 2.0 Method method = MotionEvent.class.getMethod( "getHistoricalY", Integer.TYPE, Integer.TYPE); historicalY = ((Float) method.invoke(ev, p, h)) .intValue(); } catch (NoSuchMethodException e) { // For Android < 2.0 historicalY = (int) (ev.getHistoricalY(h)); } catch (IllegalArgumentException e) { throw e; } catch (IllegalAccessException e) { System.err.println("unexpected " + e); } catch (InvocationTargetException e) { System.err.println("unexpected " + e); } // Calculate the padding to apply, we divide by 1.7 to // simulate a more resistant effect during pull. int topPadding = (int) (((historicalY - mLastMotionY) - mRefreshViewHeight) / 1.7); // Log.d(TAG, // String.format( // "[applyHeaderPadding]historicalY=%d,topPadding=%d,mRefreshViewHeight=%d,mLastMotionY=%d", // historicalY, topPadding, // mRefreshViewHeight, mLastMotionY)); mRefreshView.setPadding(mRefreshView.getPaddingLeft(), topPadding, mRefreshView.getPaddingRight(), mRefreshView.getPaddingBottom()); } } } } /** * Sets the header padding back to original size. */ private void resetHeaderPadding() { Log.d(TAG, String.format( "[resetHeaderPadding]currState=%d, refreshState=%d", mCurrentScrollState, mRefreshState)); // invalidate(); //this.mPadding=0; //this.offsetTopAndBottom(this.mPadding); mRefreshView.setPadding(mRefreshView.getPaddingLeft(), mRefreshOriginalTopPadding, mRefreshView.getPaddingRight(), mRefreshView.getPaddingBottom()); } /** * Resets the header to the original state. */ private void resetHeader() { Log.d(TAG, String.format("[resetHeader]currState=%d, refreshState=%d", mCurrentScrollState, mRefreshState)); if (mRefreshState != TAP_TO_REFRESH) { mRefreshState = TAP_TO_REFRESH; resetHeaderPadding(); // Set refresh view text to the pull label // mRefreshViewText.setText(R.string.pull_to_refresh_tap_label);//点击刷新是否有用 mRefreshViewText.setText(R.string.pull_to_refresh_pull_label); // Replace refresh drawable with arrow drawable mRefreshViewImage .setImageResource(R.drawable.ic_pulltorefresh_arrow); // Clear the full rotation animation mRefreshViewImage.clearAnimation(); // Hide progress bar and arrow. mRefreshViewImage.setVisibility(View.GONE); mRefreshViewProgress.setVisibility(View.GONE); } } private void measureView(View child) { Log.d(TAG, String.format("[measureView]currState=%d, refreshState=%d", mCurrentScrollState, mRefreshState)); ViewGroup.LayoutParams p = child.getLayoutParams(); if (p == null) { p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width); int lpHeight = p.height; int childHeightSpec; if (lpHeight > 0) { childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); } else { childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } child.measure(childWidthSpec, childHeightSpec); } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { Log.d(TAG, "List onScroll"); if (mCurrentScrollState == SCROLL_STATE_FLING && firstVisibleItem == 0 && mRefreshState != REFRESHING) { setSelection(1); mRefreshViewImage.setVisibility(View.INVISIBLE); } if (mOnScrollListener != null) { mOnScrollListener.onScroll(this, firstVisibleItem, visibleItemCount, totalItemCount); } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { mCurrentScrollState = scrollState; if (mOnScrollListener != null) { mOnScrollListener.onScrollStateChanged(view, scrollState); } } public void prepareForRefresh() { resetHeaderPadding(); mRefreshViewImage.setVisibility(View.GONE); // We need this hack, otherwise it will keep the previous drawable. mRefreshViewImage.setImageDrawable(null); mRefreshViewProgress.setVisibility(View.VISIBLE); // Set refresh view text to the refreshing label mRefreshViewText.setText(R.string.pull_to_refresh_refreshing_label); mRefreshState = REFRESHING; } public void onRefresh() { Log.d(TAG, "onRefresh"); if (mOnRefreshListener != null) { mOnRefreshListener.onRefresh(); } } /** * Resets the list to a normal state after a refresh. * * @param lastUpdated * Last updated at. */ public void onRefreshComplete(CharSequence lastUpdated) { setLastUpdated(lastUpdated); onRefreshComplete(); } /** * Resets the list to a normal state after a refresh. */ public void onRefreshComplete() { Log.d(TAG, "onRefreshComplete"); resetHeader(); // If refresh view is visible when loading completes, scroll down to // the next item. if (mRefreshView.getBottom() > 0) { invalidateViews(); // setSelection(1); } } /** * Invoked when the refresh view is clicked on. This is mainly used when * there's only a few items in the list and it's not possible to drag the * list. */ private class OnClickRefreshListener implements OnClickListener { @Override public void onClick(View v) { if (mRefreshState != REFRESHING) { prepareForRefresh(); onRefresh(); } } } /** * Interface definition for a callback to be invoked when list should be * refreshed. */ public interface OnRefreshListener { /** * Called when the list should be refreshed. * <p> * A call to {@link PullToRefreshListView #onRefreshComplete()} is * expected to indicate that the refresh has completed. */ public void onRefresh(); } @Override public boolean onDown(MotionEvent e) { // TODO Auto-generated method stub return false; } @Override public void onShowPress(MotionEvent e) { // TODO Auto-generated method stub } @Override public boolean onSingleTapUp(MotionEvent e) { // TODO Auto-generated method stub return false; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { int firstVisibleItem = this.getFirstVisiblePosition(); // When the refresh view is completely visible, change the text to say // "Release to refresh..." and flip the arrow drawable. Log.d(TAG, String.format( "[OnScroll]first=%d, currState=%d, refreshState=%d", firstVisibleItem, mCurrentScrollState, mRefreshState)); if (mCurrentScrollState == SCROLL_STATE_TOUCH_SCROLL && mRefreshState != REFRESHING) { if (firstVisibleItem == 0) { mRefreshViewImage.setVisibility(View.VISIBLE); // Log.d(TAG, // String.format( // "getBottom=%d,refreshViewHeight=%d,getTop=%d,mRefreshOriginalTopPadding=%d", // mRefreshView.getBottom(), mRefreshViewHeight // + MAXHEIGHT, // this.getTopPaddingOffset(), // mRefreshOriginalTopPadding)); if ((mRefreshView.getBottom() >= mRefreshViewHeight + MAXHEIGHT || mRefreshView .getTop() >= 0) && mRefreshState != RELEASE_TO_REFRESH) { //this.mPadding+=distanceY;//备用 mRefreshViewText .setText(R.string.pull_to_refresh_release_label); mRefreshViewImage.clearAnimation(); mRefreshViewImage.startAnimation(mFlipAnimation); mRefreshState = RELEASE_TO_REFRESH; } else if (mRefreshView.getBottom() < mRefreshViewHeight + MAXHEIGHT && mRefreshState != PULL_TO_REFRESH) { mRefreshViewText .setText(R.string.pull_to_refresh_pull_label); if (mRefreshState != TAP_TO_REFRESH) { mRefreshViewImage.clearAnimation(); mRefreshViewImage.startAnimation(mReverseFlipAnimation); } mRefreshState = PULL_TO_REFRESH; } } else { mRefreshViewImage.setVisibility(View.GONE); resetHeader(); } } /*not execute else if (mCurrentScrollState == SCROLL_STATE_FLING && firstVisibleItem == 0 && mRefreshState != REFRESHING) { setSelection(1); }*/ return false; } @Override public void onLongPress(MotionEvent e) { } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return false; } }
Java
/* * Copyright 2011 woozzu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.outsourcing.bottle.widget; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.animation.AnimationUtils; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.outsourcing.bottle.R; public class RefreshableListView extends ListView { private View mHeaderContainer = null; private View mHeaderView = null; private ImageView mArrow = null; private ProgressBar mProgress = null; private TextView mText = null; private float mY = 0; private float mHistoricalY = 0; private int mHistoricalTop = 0; private int mInitialHeight = 0; private boolean mFlag = false; private boolean mArrowUp = false; private boolean mIsRefreshing = false; private int mHeaderHeight = 0; private OnRefreshListener mListener = null; private static final int REFRESH = 0; private static final int NORMAL = 1; private static final int HEADER_HEIGHT_DP = 62; public RefreshableListView(Context context) { super(context); initialize(); } public RefreshableListView(Context context, AttributeSet attrs) { super(context, attrs); initialize(); } public RefreshableListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); initialize(); } public void setOnRefreshListener(OnRefreshListener l) { mListener = l; } public void completeRefreshing() { mProgress.setVisibility(View.INVISIBLE); mArrow.setVisibility(View.VISIBLE); mHandler.sendMessage(mHandler.obtainMessage(NORMAL, mHeaderHeight, 0)); mIsRefreshing = false; invalidateViews(); } @Override public boolean onTouchEvent(MotionEvent ev) { try { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: mHandler.removeMessages(REFRESH); mHandler.removeMessages(NORMAL); mY = mHistoricalY = ev.getY(); if (mHeaderContainer.getLayoutParams() != null) mInitialHeight = mHeaderContainer.getLayoutParams().height; break; case MotionEvent.ACTION_MOVE: mHistoricalTop = getChildAt(0).getTop(); break; case MotionEvent.ACTION_UP: if (!mIsRefreshing) { if (mArrowUp) { startRefreshing(); mHandler.sendMessage(mHandler.obtainMessage(REFRESH, (int) (ev.getY() - mY) / 2 + mInitialHeight, 0)); } else { if (getChildAt(0).getTop() == 0) mHandler.sendMessage(mHandler .obtainMessage(NORMAL, (int) (ev.getY() - mY) / 2 + mInitialHeight, 0)); } } else { mHandler.sendMessage(mHandler.obtainMessage(REFRESH, (int) (ev.getY() - mY) / 2 + mInitialHeight, 0)); } mFlag = false; break; } } catch (Exception e) { e.printStackTrace(); } return super.onTouchEvent(ev); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_MOVE && getFirstVisiblePosition() == 0) { float direction = ev.getY() - mHistoricalY; int height = (int) (ev.getY() - mY) / 2 + mInitialHeight; if (height < 0) height = 0; // Scrolling downward if (direction > 0) { // Refresh bar is extended if top pixel of the first item is // visible if (getChildAt(0).getTop() == 0) { if (mHistoricalTop < 0) { mY = ev.getY(); mHistoricalTop = 0; } // Extends refresh bar setHeaderHeight(height); // Stop list scroll to prevent the list from overscrolling ev.setAction(MotionEvent.ACTION_CANCEL); mFlag = false; } } else if (direction < 0) { // Scrolling upward // Refresh bar is shortened if top pixel of the first item is // visible if (getChildAt(0).getTop() == 0) { setHeaderHeight(height); // If scroll reaches top of the list, list scroll is enabled if (getChildAt(1) != null && getChildAt(1).getTop() <= 1 && !mFlag) { ev.setAction(MotionEvent.ACTION_DOWN); mFlag = true; } } } mHistoricalY = ev.getY(); } return super.dispatchTouchEvent(ev); } private void initialize() { LayoutInflater inflater = (LayoutInflater) getContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); mHeaderContainer = inflater.inflate(R.layout.refreshable_list_header, null); mHeaderView = mHeaderContainer .findViewById(R.id.refreshable_list_header); mArrow = (ImageView) mHeaderContainer .findViewById(R.id.refreshable_list_arrow); mProgress = (ProgressBar) mHeaderContainer .findViewById(R.id.refreshable_list_progress); mText = (TextView) mHeaderContainer .findViewById(R.id.refreshable_list_text); addHeaderView(mHeaderContainer); mHeaderHeight = (int) (HEADER_HEIGHT_DP * getContext().getResources() .getDisplayMetrics().density); setHeaderHeight(0); } private void setHeaderHeight(int height) { if (height <= 1) mHeaderView.setVisibility(View.GONE); else mHeaderView.setVisibility(View.VISIBLE); // Extends refresh bar LayoutParams lp = (LayoutParams) mHeaderContainer.getLayoutParams(); if (lp == null) lp = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); lp.height = height; mHeaderContainer.setLayoutParams(lp); // Refresh bar shows up from bottom to top LinearLayout.LayoutParams headerLp = (LinearLayout.LayoutParams) mHeaderView .getLayoutParams(); if (headerLp == null) headerLp = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); headerLp.topMargin = -mHeaderHeight + height; mHeaderView.setLayoutParams(headerLp); if (!mIsRefreshing) { // If scroll reaches the trigger line, start refreshing if (height > mHeaderHeight && !mArrowUp) { mArrow.startAnimation(AnimationUtils.loadAnimation( getContext(), R.anim.rotate)); mText.setText("松开可以刷新"); rotateArrow(); mArrowUp = true; } else if (height < mHeaderHeight && mArrowUp) { mArrow.startAnimation(AnimationUtils.loadAnimation( getContext(), R.anim.rotate)); mText.setText("下拉刷新"); rotateArrow(); mArrowUp = false; } } } private void rotateArrow() { Drawable drawable = mArrow.getDrawable(); Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); canvas.save(); canvas.rotate(180.0f, canvas.getWidth() / 2.0f, canvas.getHeight() / 2.0f); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); drawable.draw(canvas); canvas.restore(); mArrow.setImageBitmap(bitmap); } private void startRefreshing() { mArrow.setVisibility(View.INVISIBLE); mProgress.setVisibility(View.VISIBLE); mText.setText("加载中..."); mIsRefreshing = true; if (mListener != null) mListener.onRefresh(); } private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); int limit = 0; switch (msg.what) { case REFRESH: limit = mHeaderHeight; break; case NORMAL: limit = 0; break; } // Elastic scrolling if (msg.arg1 >= limit) { setHeaderHeight(msg.arg1); int displacement = (msg.arg1 - limit) / 10; if (displacement == 0) mHandler.sendMessage(mHandler.obtainMessage(msg.what, msg.arg1 - 1, 0)); else mHandler.sendMessage(mHandler.obtainMessage(msg.what, msg.arg1 - displacement, 0)); } } }; public interface OnRefreshListener { public void onRefresh(); } }
Java
/* * Copyright (C) 2012 Capricorn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.outsourcing.bottle.widget; import android.view.animation.Animation; import android.view.animation.Transformation; /** * An animation that controls the position of an object, and make the object * rotate on its center at the same time. * */ public class RotateAndTranslateAnimation extends Animation { private int mFromXType = ABSOLUTE; private int mToXType = ABSOLUTE; private int mFromYType = ABSOLUTE; private int mToYType = ABSOLUTE; private float mFromXValue = 0.0f; private float mToXValue = 0.0f; private float mFromYValue = 0.0f; private float mToYValue = 0.0f; private float mFromXDelta; private float mToXDelta; private float mFromYDelta; private float mToYDelta; private float mFromDegrees; private float mToDegrees; private int mPivotXType = ABSOLUTE; private int mPivotYType = ABSOLUTE; private float mPivotXValue = 0.0f; private float mPivotYValue = 0.0f; private float mPivotX; private float mPivotY; /** * Constructor to use when building a TranslateAnimation from code * * @param fromXDelta * Change in X coordinate to apply at the start of the animation * @param toXDelta * Change in X coordinate to apply at the end of the animation * @param fromYDelta * Change in Y coordinate to apply at the start of the animation * @param toYDelta * Change in Y coordinate to apply at the end of the animation * * @param fromDegrees * Rotation offset to apply at the start of the animation. * @param toDegrees * Rotation offset to apply at the end of the animation. */ public RotateAndTranslateAnimation(float fromXDelta, float toXDelta, float fromYDelta, float toYDelta, float fromDegrees, float toDegrees) { mFromXValue = fromXDelta; mToXValue = toXDelta; mFromYValue = fromYDelta; mToYValue = toYDelta; mFromXType = ABSOLUTE; mToXType = ABSOLUTE; mFromYType = ABSOLUTE; mToYType = ABSOLUTE; mFromDegrees = fromDegrees; mToDegrees = toDegrees; mPivotXValue = 0.5f; mPivotXType = RELATIVE_TO_SELF; mPivotYValue = 0.5f; mPivotYType = RELATIVE_TO_SELF; } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { final float degrees = mFromDegrees + ((mToDegrees - mFromDegrees) * interpolatedTime); if (mPivotX == 0.0f && mPivotY == 0.0f) { t.getMatrix().setRotate(degrees); } else { t.getMatrix().setRotate(degrees, mPivotX, mPivotY); } float dx = mFromXDelta; float dy = mFromYDelta; if (mFromXDelta != mToXDelta) { dx = mFromXDelta + ((mToXDelta - mFromXDelta) * interpolatedTime); } if (mFromYDelta != mToYDelta) { dy = mFromYDelta + ((mToYDelta - mFromYDelta) * interpolatedTime); } t.getMatrix().postTranslate(dx, dy); } @Override public void initialize(int width, int height, int parentWidth, int parentHeight) { super.initialize(width, height, parentWidth, parentHeight); mFromXDelta = resolveSize(mFromXType, mFromXValue, width, parentWidth); mToXDelta = resolveSize(mToXType, mToXValue, width, parentWidth); mFromYDelta = resolveSize(mFromYType, mFromYValue, height, parentHeight); mToYDelta = resolveSize(mToYType, mToYValue, height, parentHeight); mPivotX = resolveSize(mPivotXType, mPivotXValue, width, parentWidth); mPivotY = resolveSize(mPivotYType, mPivotYValue, height, parentHeight); } }
Java
package com.outsourcing.bottle.widget.pullrefresh; import android.view.MotionEvent; public class PullingDownState implements ScrollingState { private float firstY; public PullingDownState(MotionEvent event) { this.firstY = event.getY(); } @Override public boolean touchStopped(MotionEvent event, PullToRefreshComponent pullToRefreshComponent) { if (pullToRefreshComponent.getListTop() > PullToRefreshComponent.MIN_PULL_ELEMENT_HEIGHT) { pullToRefreshComponent.beginPullDownRefresh(); } else { pullToRefreshComponent.refreshFinished(pullToRefreshComponent .getOnUpperRefreshAction()); } return true; } @Override public boolean handleMovement(MotionEvent event, PullToRefreshComponent pullToRefreshComponent) { pullToRefreshComponent.updateEventStates(event); pullToRefreshComponent.pullDown(event, this.firstY); pullToRefreshComponent.readyToReleaseUpper(pullToRefreshComponent .getListTop() > PullToRefreshComponent.MIN_PULL_ELEMENT_HEIGHT); return true; } }
Java
package com.outsourcing.bottle.widget.pullrefresh; public interface RefreshListener { void doRefresh(); void refreshFinished(); }
Java
package com.outsourcing.bottle.widget.pullrefresh; import android.view.MotionEvent; public class PullToRefreshState implements ScrollingState { @Override public boolean touchStopped(MotionEvent event, PullToRefreshComponent onTouchListener) { return false; } @Override public boolean handleMovement(MotionEvent event, PullToRefreshComponent pullToRefreshComponent) { pullToRefreshComponent.updateEventStates(event); if (pullToRefreshComponent.isPullingDownToRefresh()) { pullToRefreshComponent.setPullingDown(event); return true; } else if (pullToRefreshComponent.isPullingUpToRefresh()) { pullToRefreshComponent.setPullingUp(event); return true; } return false; } }
Java
package com.outsourcing.bottle.widget.pullrefresh; public class NoRefreshListener implements RefreshListener { @Override public void doRefresh() { } @Override public void refreshFinished() { } }
Java
package com.outsourcing.bottle.widget.pullrefresh; import android.view.MotionEvent; public class PullingUpState implements ScrollingState { private float firstY; public PullingUpState(MotionEvent event) { this.firstY = event.getY(); } @Override public boolean touchStopped(MotionEvent event, PullToRefreshComponent pullToRefreshComponent) { if (pullToRefreshComponent.getBottomViewHeight() > PullToRefreshComponent.MIN_PULL_ELEMENT_HEIGHT) { pullToRefreshComponent.beginPullUpRefresh(); } else { pullToRefreshComponent.refreshFinished(pullToRefreshComponent .getOnLowerRefreshAction()); } return true; } @Override public boolean handleMovement(MotionEvent event, PullToRefreshComponent pullToRefreshComponent) { pullToRefreshComponent.updateEventStates(event); pullToRefreshComponent.pullUp(event, this.firstY); pullToRefreshComponent .readyToReleaseLower(pullToRefreshComponent .getBottomViewHeight() > PullToRefreshComponent.MIN_PULL_ELEMENT_HEIGHT); return true; } }
Java
package com.outsourcing.bottle.widget.pullrefresh; import android.content.Context; import android.os.Handler; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import com.outsourcing.bottle.R; public class PullToRefreshListView extends RelativeLayout { private PullToRefreshComponent pullToRefresh; private ViewGroup upperButton; private ViewGroup lowerButton; private Handler uiThreadHandler; private ListView listView; public PullToRefreshListView(Context context, AttributeSet attrs) { super(context, attrs); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.pull_to_refresh_list, this); this.listView = (ListView) this.findViewById(android.R.id.list); this.uiThreadHandler = new Handler(); this.initializePullToRefreshList(); } private void initializePullToRefreshList() { this.initializeRefreshUpperButton(); this.initializeRefreshLowerButton(); this.pullToRefresh = new PullToRefreshComponent( this.upperButton, this.lowerButton, this.listView, this.uiThreadHandler); this.pullToRefresh.setOnReleaseUpperReady(new OnReleaseReady() { @Override public void releaseReady(boolean ready) { if (ready) { ((TextView) PullToRefreshListView.this.upperButton .findViewById(R.id.pull_to_refresh_text)) .setText(R.string.pull_to_refresh_release_label); } else { ((TextView) PullToRefreshListView.this.upperButton .findViewById(R.id.pull_to_refresh_text)) .setText(R.string.pull_to_refresh_pull_down_label); } } }); this.pullToRefresh.setOnReleaseLowerReady(new OnReleaseReady() { @Override public void releaseReady(boolean ready) { if (ready) { ((TextView) PullToRefreshListView.this.lowerButton .findViewById(R.id.pull_to_refresh_text)) .setText(R.string.pull_to_refresh_release_label); } else { ((TextView) PullToRefreshListView.this.lowerButton .findViewById(R.id.pull_to_refresh_text)) .setText(R.string.pull_to_refresh_pull_up_label); } } }); } public void setOnPullDownRefreshAction(final RefreshListener listener) { this.pullToRefresh.setOnPullDownRefreshAction(new RefreshListener() { @Override public void refreshFinished() { PullToRefreshListView.this.runOnUIThread(new Runnable() { @Override public void run() { PullToRefreshListView.this .setPullToRefresh(PullToRefreshListView.this.upperButton); PullToRefreshListView.this.invalidate(); } }); PullToRefreshListView.this.runOnUIThread(new Runnable() { @Override public void run() { listener.refreshFinished(); } }); } @Override public void doRefresh() { PullToRefreshListView.this.uiThreadHandler.post(new Runnable() { @Override public void run() { PullToRefreshListView.this .setRefreshing(PullToRefreshListView.this.upperButton); PullToRefreshListView.this.invalidate(); } }); listener.doRefresh(); } }); } protected void runOnUIThread(Runnable runnable) { this.uiThreadHandler.post(runnable); } public void setOnPullUpRefreshAction(final RefreshListener listener) { this.pullToRefresh.setOnPullUpRefreshAction(new RefreshListener() { @Override public void refreshFinished() { PullToRefreshListView.this .setPullToRefresh(PullToRefreshListView.this.lowerButton); PullToRefreshListView.this.invalidate(); listener.refreshFinished(); } @Override public void doRefresh() { PullToRefreshListView.this.uiThreadHandler.post(new Runnable() { @Override public void run() { PullToRefreshListView.this .setRefreshing(PullToRefreshListView.this.lowerButton); PullToRefreshListView.this.invalidate(); } }); listener.doRefresh(); } }); } private void initializeRefreshLowerButton() { this.upperButton = (ViewGroup) this .findViewById(R.id.refresh_upper_button); } private void initializeRefreshUpperButton() { this.lowerButton = (ViewGroup) this .findViewById(R.id.refresh_lower_button); } protected void setPullToRefresh(ViewGroup refreshView) { int text = 0; if (refreshView == this.upperButton) { text = R.string.pull_to_refresh_pull_down_label; } else { text = R.string.pull_to_refresh_pull_up_label; } ((TextView) refreshView.findViewById(R.id.pull_to_refresh_text)) .setText(text); refreshView.findViewById(R.id.pull_to_refresh_progress).setVisibility( View.INVISIBLE); refreshView.findViewById(R.id.pull_to_refresh_image).setVisibility( View.VISIBLE); } protected void setRefreshing(ViewGroup refreshView) { ((TextView) refreshView.findViewById(R.id.pull_to_refresh_text)) .setText(R.string.pull_to_refresh_refreshing_label); refreshView.findViewById(R.id.pull_to_refresh_progress).setVisibility( View.VISIBLE); refreshView.findViewById(R.id.pull_to_refresh_image).setVisibility( View.INVISIBLE); } public void disablePullUpToRefresh() { this.pullToRefresh.disablePullUpToRefresh(); } public void disablePullDownToRefresh() { this.pullToRefresh.disablePullDownToRefresh(); } public ListView getListView() { return listView; } }
Java
package com.outsourcing.bottle.widget.pullrefresh; import android.content.res.Resources; /** * * @author 06peng * */ public class Pixel { private Resources resources; private int value; public Pixel(int value, Resources resources) { this.value = value; this.resources = resources; } public float toDp() { return this.value * this.resources.getDisplayMetrics().density + 0.5f; } }
Java
package com.outsourcing.bottle.widget.pullrefresh; import android.view.MotionEvent; public class RefreshingState implements ScrollingState { @Override public boolean touchStopped(MotionEvent event, PullToRefreshComponent pullToRefreshComponent) { return true; } @Override public boolean handleMovement(MotionEvent event, PullToRefreshComponent pullToRefreshComponent) { return true; } }
Java
package com.outsourcing.bottle.widget.pullrefresh; import java.util.Date; import android.os.Handler; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.ListView; public class PullToRefreshComponent { private static final int EVENT_COUNT = 3; protected static final float MIN_PULL_ELEMENT_HEIGHT = 100; protected static final float MAX_PULL_ELEMENT_HEIGHT = 200; private static final float PULL_ELEMENT_STANDBY_HEIGHT = 100; protected static int firstVisibleItem = 0; private View upperView; private View lowerView; private ListView listView; private Handler uiThreadHandler; private float[] lastYs = new float[EVENT_COUNT]; private RefreshListener onPullDownRefreshAction = new NoRefreshListener(); private RefreshListener onPullUpRefreshAction = new NoRefreshListener(); protected ScrollingState state; private boolean mayPullUpToRefresh = true; private boolean mayPullDownToRefresh; private OnReleaseReady onReleaseLowerReady; private OnReleaseReady onReleaseUpperReady; public PullToRefreshComponent(View upperView, View lowerView, ListView listView, Handler uiThreadHandler) { this.upperView = upperView; this.lowerView = lowerView; this.listView = listView; this.uiThreadHandler = uiThreadHandler; this.initialize(); } private void initialize() { this.state = new PullToRefreshState(); this.listView.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { PullToRefreshComponent.this.initializeYsHistory(); return PullToRefreshComponent.this.state.touchStopped( event, PullToRefreshComponent.this); } else if (event.getAction() == MotionEvent.ACTION_MOVE) { return PullToRefreshComponent.this.state.handleMovement( event, PullToRefreshComponent.this); } return false; } }); } protected float average(float[] ysArray) { float avg = 0; for (int i = 0; i < EVENT_COUNT; i++) { avg += ysArray[i]; } return avg / EVENT_COUNT; } public void beginPullDownRefresh() { this.beginRefresh(this.upperView, this.onPullDownRefreshAction); } private void beginRefresh(View viewToUpdate, final RefreshListener refreshAction) { android.view.ViewGroup.LayoutParams params = viewToUpdate .getLayoutParams(); params.height = (int) PULL_ELEMENT_STANDBY_HEIGHT; viewToUpdate.setLayoutParams(params); Log.i("PullDown", "refreshing"); this.state = new RefreshingState(); new Thread(new Runnable() { @Override public void run() { try { Date start = new Date(); refreshAction.doRefresh(); Date finish = new Date(); long difference = finish.getTime() - start.getTime(); try { Thread.sleep(Math.max(difference, 1500)); } catch (InterruptedException e) { } } catch (RuntimeException e) { Log.e("Error", e.getMessage(), e); throw e; } finally { PullToRefreshComponent.this.runOnUiThread(new Runnable() { @Override public void run() { PullToRefreshComponent.this .refreshFinished(refreshAction); } }); } } }).start(); } public void beginPullUpRefresh() { this.beginRefresh(this.lowerView, this.onPullUpRefreshAction); } /**************************************************************/ // Listeners /**************************************************************/ public void setOnPullDownRefreshAction(RefreshListener onRefreshAction) { this.enablePullDownToRefresh(); this.onPullDownRefreshAction = onRefreshAction; } public void setOnPullUpRefreshAction(RefreshListener onRefreshAction) { this.enablePullUpToRefresh(); this.onPullUpRefreshAction = onRefreshAction; } protected void refreshFinished(final RefreshListener refreshAction) { Log.i("PullDown", "ready"); this.state = new PullToRefreshState(); this.initializeYsHistory(); this.runOnUiThread(new Runnable() { @Override public void run() { float dp = new Pixel(0, PullToRefreshComponent.this.listView .getResources()).toDp(); PullToRefreshComponent.this.setUpperButtonHeight(dp); PullToRefreshComponent.this.setLowerButtonHeight(dp); refreshAction.refreshFinished(); } }); } private void runOnUiThread(Runnable runnable) { this.uiThreadHandler.post(runnable); } synchronized void setUpperButtonHeight(float height) { this.setHeight(height, this.upperView); } synchronized void setLowerButtonHeight(float height) { this.setHeight(height, this.lowerView); } private void setHeight(float height, View view) { if (view == null) { return; } android.view.ViewGroup.LayoutParams params = view.getLayoutParams(); if (params == null) { return; } params.height = (int) height; view.setLayoutParams(params); view.getParent().requestLayout(); } public int getListTop() { return this.listView.getTop(); } public void initializeYsHistory() { for (int i = 0; i < EVENT_COUNT; i++) { PullToRefreshComponent.this.lastYs[i] = 0; } } /**************************************************************/ // HANDLE PULLING /**************************************************************/ public void pullDown(MotionEvent event, float firstY) { float averageY = PullToRefreshComponent.this .average(PullToRefreshComponent.this.lastYs); int height = (int) Math.max( Math.min(averageY - firstY, MAX_PULL_ELEMENT_HEIGHT), 0); PullToRefreshComponent.this.setUpperButtonHeight(height); } public void pullUp(MotionEvent event, float firstY) { float averageY = PullToRefreshComponent.this .average(PullToRefreshComponent.this.lastYs); int height = (int) Math.max( Math.min(firstY - averageY, MAX_PULL_ELEMENT_HEIGHT), 0); PullToRefreshComponent.this.setLowerButtonHeight(height); } public boolean isPullingDownToRefresh() { return this.mayPullDownToRefresh && this.isIncremental() && this.isFirstVisible(); } public boolean isPullingUpToRefresh() { return this.mayPullUpToRefresh && this.isDecremental() && this.isLastVisible(); } private boolean isFirstVisible() { if (this.listView.getCount() == 0) { return true; } else if (this.listView.getFirstVisiblePosition() == 0) { return this.listView.getChildAt(0).getTop() >= this.listView .getTop(); } else { return false; } } private boolean isLastVisible() { if (this.listView.getCount() == 0) { return true; } else if (this.listView.getLastVisiblePosition() + 1 == this.listView .getCount()) { return this.listView.getChildAt(this.listView.getChildCount() - 1) .getBottom() <= this.listView.getBottom(); } else { return false; } } private boolean isIncremental(int from, int to, int step) { float realFrom = this.lastYs[from]; float realTo = this.lastYs[to]; return this.lastYs[from] != 0 && realTo != 0 && Math.abs(realFrom - realTo) > 50 && realFrom * step < realTo; } private boolean isIncremental() { return this.isIncremental(0, EVENT_COUNT - 1, +1); } private boolean isDecremental() { return this.isIncremental(0, EVENT_COUNT - 1, -1); } public void updateEventStates(MotionEvent event) { for (int i = 0; i < EVENT_COUNT - 1; i++) { PullToRefreshComponent.this.lastYs[i] = PullToRefreshComponent.this.lastYs[i + 1]; } float y = event.getY(); int top = PullToRefreshComponent.this.listView.getTop(); PullToRefreshComponent.this.lastYs[EVENT_COUNT - 1] = y + top; } /**************************************************************/ // State Change /**************************************************************/ public void setPullingDown(MotionEvent event) { this.state = new PullingDownState(event); } public void setPullingUp(MotionEvent event) { this.state = new PullingUpState(event); } public float getBottomViewHeight() { return this.lowerView.getHeight(); } public RefreshListener getOnUpperRefreshAction() { return this.onPullDownRefreshAction; } public RefreshListener getOnLowerRefreshAction() { return this.onPullUpRefreshAction; } public void disablePullUpToRefresh() { this.mayPullUpToRefresh = false; } public void disablePullDownToRefresh() { this.mayPullDownToRefresh = false; } public void enablePullUpToRefresh() { this.mayPullUpToRefresh = true; } public void enablePullDownToRefresh() { this.mayPullDownToRefresh = true; } public void setOnReleaseUpperReady(OnReleaseReady onReleaseUpperReady) { this.onReleaseUpperReady = onReleaseUpperReady; } public void setOnReleaseLowerReady(OnReleaseReady onReleaseUpperReady) { this.onReleaseLowerReady = onReleaseUpperReady; } public void readyToReleaseUpper(boolean ready) { if (this.onReleaseUpperReady != null) { this.onReleaseUpperReady.releaseReady(ready); } } public void readyToReleaseLower(boolean ready) { if (this.onReleaseLowerReady != null) { this.onReleaseLowerReady.releaseReady(ready); } } }
Java
package com.outsourcing.bottle.widget.pullrefresh; import android.view.MotionEvent; public interface ScrollingState { boolean touchStopped(MotionEvent event, PullToRefreshComponent pullToRefreshComponent); boolean handleMovement(MotionEvent event, PullToRefreshComponent pullToRefreshComponent); }
Java
package com.outsourcing.bottle.widget.pullrefresh; public interface OnReleaseReady { void releaseReady(boolean ready); }
Java
package com.outsourcing.bottle.widget.pullrefresh; public interface OnPullingAction { void handlePull(boolean down, int height); }
Java
package com.outsourcing.bottle.widget; import java.util.Date; import android.content.Context; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.outsourcing.bottle.R; /** * ListView下拉刷新 * @author 06peng * */ public class CustomListView extends ListView implements OnScrollListener { private final static int RELEASE_To_REFRESH = 0; private final static int PULL_To_REFRESH = 1; private final static int REFRESHING = 2; private final static int DONE = 3; private final static int LOADING = 4; // 实际的padding的距离与界面上偏移距离的比例 private final static int RATIO = 3; private LayoutInflater inflater; private LinearLayout headView; private TextView tipsTextview; private TextView lastUpdatedTextView; private ImageView arrowImageView; private ProgressBar progressBar; private RotateAnimation animation; private RotateAnimation reverseAnimation; // 用于保证startY的值在一个完整的touch事件中只被记录一次 private boolean isRecored; private int headContentWidth; private int headContentHeight; private int startY; private int firstItemIndex; private int state; private boolean isBack; private OnRefreshListener refreshListener; private boolean isRefreshable; private Context context; public CustomListView(Context context) { super(context); init(context); } public CustomListView(Context context, AttributeSet attrs) { super(context, attrs); init(context); } private void init(Context context) { this.context = context; setCacheColorHint(context.getResources().getColor(R.color.transparent)); inflater = LayoutInflater.from(context); headView = (LinearLayout) inflater.inflate(R.layout.mylistview_head, null); arrowImageView = (ImageView) headView.findViewById(R.id.head_arrowImageView); arrowImageView.setMinimumWidth(70); arrowImageView.setMinimumHeight(50); progressBar = (ProgressBar) headView.findViewById(R.id.head_progressBar); tipsTextview = (TextView) headView.findViewById(R.id.head_tipsTextView); lastUpdatedTextView = (TextView) headView.findViewById(R.id.head_lastUpdatedTextView); measureView(headView); headContentHeight = headView.getMeasuredHeight(); headContentWidth = headView.getMeasuredWidth(); headView.setPadding(0, -1 * headContentHeight, 0, 0); headView.invalidate(); Log.v("size", "width:" + headContentWidth + " height:" + headContentHeight); addHeaderView(headView, null, false); setOnScrollListener(this); animation = new RotateAnimation(0, -180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); animation.setInterpolator(new LinearInterpolator()); animation.setDuration(250); animation.setFillAfter(true); reverseAnimation = new RotateAnimation(-180, 0, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); reverseAnimation.setInterpolator(new LinearInterpolator()); reverseAnimation.setDuration(200); reverseAnimation.setFillAfter(true); state = DONE; isRefreshable = false; } public void onScroll(AbsListView arg0, int firstVisiableItem, int arg2, int arg3) { firstItemIndex = firstVisiableItem; } public void setFirstVisiableItem(int firstVisiableItem){ this.firstItemIndex = firstVisiableItem; } public void onScrollStateChanged(AbsListView arg0, int arg1) { } public boolean onTouchEvent(MotionEvent event) { if (isRefreshable) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (firstItemIndex == 0 && !isRecored) { isRecored = true; startY = (int) event.getY(); } break; case MotionEvent.ACTION_UP: if (state != REFRESHING && state != LOADING) { if (state == DONE) { } if (state == PULL_To_REFRESH) { state = DONE; changeHeaderViewByState(); } if (state == RELEASE_To_REFRESH) { state = REFRESHING; changeHeaderViewByState(); onRefresh(); } } isRecored = false; isBack = false; break; case MotionEvent.ACTION_MOVE: int tempY = (int) event.getY(); if (!isRecored && firstItemIndex == 0) { isRecored = true; startY = tempY; } if (state != REFRESHING && isRecored && state != LOADING) { // 保证在设置padding的过程中,当前的位置一直是在head,否则如果当列表超出屏幕的话,当在上推的时候,列表会同时进行滚动 // 可以松手去刷新了 if (state == RELEASE_To_REFRESH) { setSelection(0); // 往上推了,推到了屏幕足够掩盖head的程度,但是还没有推到全部掩盖的地步 if (((tempY - startY) / RATIO < headContentHeight) && (tempY - startY) > 0) { state = PULL_To_REFRESH; changeHeaderViewByState(); } // 一下子推到顶了 else if (tempY - startY <= 0) { state = DONE; changeHeaderViewByState(); } // 往下拉了,或者还没有上推到屏幕顶部掩盖head的地步 } // 还没有到达显示松开刷新的时候,DONE或者是PULL_To_REFRESH状态 if (state == PULL_To_REFRESH) { setSelection(0); // 下拉到可以进入RELEASE_TO_REFRESH的状态 if ((tempY - startY) / RATIO >= headContentHeight) { state = RELEASE_To_REFRESH; isBack = true; changeHeaderViewByState(); } else if (tempY - startY <= 0) { state = DONE; changeHeaderViewByState(); } } if (state == DONE) { if (tempY - startY > 0) { state = PULL_To_REFRESH; changeHeaderViewByState(); } } if (state == PULL_To_REFRESH) { headView.setPadding(0, -1 * headContentHeight + (tempY - startY) / RATIO, 0, 0); } if (state == RELEASE_To_REFRESH) { headView.setPadding(0, (tempY - startY) / RATIO - headContentHeight, 0, 0); } } break; } } return super.onTouchEvent(event); } // 当状态改变时候,调用该方法,以更新界面 private void changeHeaderViewByState() { switch (state) { case RELEASE_To_REFRESH: arrowImageView.setVisibility(View.VISIBLE); progressBar.setVisibility(View.GONE); tipsTextview.setVisibility(View.VISIBLE); lastUpdatedTextView.setVisibility(View.VISIBLE); arrowImageView.clearAnimation(); arrowImageView.startAnimation(animation); tipsTextview.setText(context.getString(R.string.scrollview_to_refresh_release_label)); break; case PULL_To_REFRESH: progressBar.setVisibility(View.GONE); tipsTextview.setVisibility(View.VISIBLE); lastUpdatedTextView.setVisibility(View.VISIBLE); arrowImageView.clearAnimation(); arrowImageView.setVisibility(View.VISIBLE); // 是由RELEASE_To_REFRESH状态转变来的 if (isBack) { isBack = false; arrowImageView.clearAnimation(); arrowImageView.startAnimation(reverseAnimation); tipsTextview.setText(context.getString(R.string.scrollview_to_refresh_pull_label)); // tipsTextview.setText("下拉刷新"); } else { // tipsTextview.setText("下拉刷新"); tipsTextview.setText(context.getString(R.string.scrollview_to_refresh_pull_label)); } break; case REFRESHING: headView.setPadding(0, 0, 0, 0); progressBar.setVisibility(View.VISIBLE); arrowImageView.clearAnimation(); arrowImageView.setVisibility(View.GONE); // tipsTextview.setText("正在刷新..."); tipsTextview.setText(context.getString(R.string.scrollview_to_refreshing_label)); lastUpdatedTextView.setVisibility(View.VISIBLE); break; case DONE: headView.setPadding(0, -1 * headContentHeight, 0, 0); progressBar.setVisibility(View.GONE); arrowImageView.clearAnimation(); arrowImageView.setImageResource(R.drawable.ic_pulltorefresh_arrow); // tipsTextview.setText("下拉刷新"); tipsTextview.setText(context.getString(R.string.scrollview_to_refresh_pull_label)); lastUpdatedTextView.setVisibility(View.VISIBLE); break; } } public void setonRefreshListener(OnRefreshListener refreshListener) { this.refreshListener = refreshListener; isRefreshable = true; } public interface OnRefreshListener { public void onRefresh(); } public void onRefreshComplete() { state = DONE; lastUpdatedTextView.setText(context.getString(R.string.scrollview_to_refresh_lasttime_label) + new Date().toLocaleString()); changeHeaderViewByState(); } private void onRefresh() { if (refreshListener != null) { refreshListener.onRefresh(); } } // 此方法直接照搬自网络上的一个下拉刷新的demo,此处是“估计”headView的width以及height private void measureView(View child) { ViewGroup.LayoutParams p = child.getLayoutParams(); if (p == null) { p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width); int lpHeight = p.height; int childHeightSpec; if (lpHeight > 0) { childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); } else { childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } child.measure(childWidthSpec, childHeightSpec); } public void setAdapter(BaseAdapter adapter) { lastUpdatedTextView.setText(context.getString(R.string.scrollview_to_refresh_lasttime_label) + new Date().toLocaleString()); super.setAdapter(adapter); } }
Java
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.outsourcing.bottle.widget; import java.lang.ref.WeakReference; import android.content.Context; import android.graphics.PixelFormat; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.IBinder; import android.view.Gravity; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.ViewTreeObserver.OnScrollChangedListener; import android.view.WindowManager; import android.widget.FrameLayout; import com.outsourcing.bottle.R; /** * <p>A popup window that can be used to display an arbitrary view. The popup * windows is a floating container that appears on top of the current * activity.</p> * * @see android.widget.AutoCompleteTextView * @see android.widget.Spinner */ public class CustomPopupWindow { /** * Mode for {@link #setInputMethodMode(int)}: the requirements for the * input method should be based on the focusability of the popup. That is * if it is focusable than it needs to work with the input method, else * it doesn't. */ public static final int INPUT_METHOD_FROM_FOCUSABLE = 0; /** * Mode for {@link #setInputMethodMode(int)}: this popup always needs to * work with an input method, regardless of whether it is focusable. This * means that it will always be displayed so that the user can also operate * the input method while it is shown. */ public static final int INPUT_METHOD_NEEDED = 1; /** * Mode for {@link #setInputMethodMode(int)}: this popup never needs to * work with an input method, regardless of whether it is focusable. This * means that it will always be displayed to use as much space on the * screen as needed, regardless of whether this covers the input method. */ public static final int INPUT_METHOD_NOT_NEEDED = 2; private Context mContext; private WindowManager mWindowManager; private boolean mIsShowing; private boolean mIsDropdown; private View mContentView; private View mPopupView; private boolean mFocusable; private int mInputMethodMode = INPUT_METHOD_FROM_FOCUSABLE; private int mSoftInputMode; private boolean mTouchable = true; private boolean mOutsideTouchable = false; private boolean mClippingEnabled = true; private OnTouchListener mTouchInterceptor; private int mWidthMode; private int mWidth; private int mLastWidth; private int mHeightMode; private int mHeight; private int mLastHeight; private int mPopupWidth; private int mPopupHeight; private int[] mDrawingLocation = new int[2]; private int[] mScreenLocation = new int[2]; private Rect mTempRect = new Rect(); private Drawable mBackground; private Drawable mAboveAnchorBackgroundDrawable; private Drawable mBelowAnchorBackgroundDrawable; private boolean mAboveAnchor; private OnDismissListener mOnDismissListener; private boolean mIgnoreCheekPress = false; private int mAnimationStyle = -1; private static final int[] ABOVE_ANCHOR_STATE_SET = new int[] { R.attr.state_above_anchor }; private WeakReference<View> mAnchor; private OnScrollChangedListener mOnScrollChangedListener = new OnScrollChangedListener() { public void onScrollChanged() { View anchor = mAnchor.get(); if (anchor != null && mPopupView != null) { WindowManager.LayoutParams p = (WindowManager.LayoutParams) mPopupView.getLayoutParams(); updateAboveAnchor(findDropDownPosition(anchor, p, mAnchorXoff, mAnchorYoff)); update(p.x, p.y, -1, -1, true); } } }; private int mAnchorXoff, mAnchorYoff; /** * <p>Create a new empty, non focusable popup window of dimension (0,0).</p> * * <p>The popup does provide a background.</p> */ // public PopupWindow(Context context) { // this(context, null); // } /** * <p>Create a new empty, non focusable popup window of dimension (0,0).</p> * * <p>The popup does provide a background.</p> */ // public PopupWindow(Context context, AttributeSet attrs) { // this(context, attrs, R.attr.popupWindowStyle); // } /** * <p>Create a new empty, non focusable popup window of dimension (0,0).</p> * * <p>The popup does provide a background.</p> */ // public PopupWindow(Context context, AttributeSet attrs, int defStyle) { // mContext = context; // mWindowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE); // // TypedArray a = // context.obtainStyledAttributes( // attrs, R.styleable.PopupWindow, defStyle, 0); // // mBackground = a.getDrawable(R.styleable.PopupWindow_popupBackground); // // // If this is a StateListDrawable, try to find and store the drawable to be // // used when the drop-down is placed above its anchor view, and the one to be // // used when the drop-down is placed below its anchor view. We extract // // the drawables ourselves to work around a problem with using refreshDrawableState // // that it will take into account the padding of all drawables specified in a // // StateListDrawable, thus adding superfluous padding to drop-down views. // // // // We assume a StateListDrawable will have a drawable for ABOVE_ANCHOR_STATE_SET and // // at least one other drawable, intended for the 'below-anchor state'. // if (mBackground instanceof StateListDrawable) { // StateListDrawable background = (StateListDrawable) mBackground; // // // Find the above-anchor view - this one's easy, it should be labeled as such. // int aboveAnchorStateIndex = background.getStateDrawableIndex(ABOVE_ANCHOR_STATE_SET); // // // Now, for the below-anchor view, look for any other drawable specified in the // // StateListDrawable which is not for the above-anchor state and use that. // int count = background.getStateCount(); // int belowAnchorStateIndex = -1; // for (int i = 0; i < count; i++) { // if (i != aboveAnchorStateIndex) { // belowAnchorStateIndex = i; // break; // } // } // // // Store the drawables we found, if we found them. Otherwise, set them both // // to null so that we'll just use refreshDrawableState. // if (aboveAnchorStateIndex != -1 && belowAnchorStateIndex != -1) { // mAboveAnchorBackgroundDrawable = background.getStateDrawable(aboveAnchorStateIndex); // mBelowAnchorBackgroundDrawable = background.getStateDrawable(belowAnchorStateIndex); // } else { // mBelowAnchorBackgroundDrawable = null; // mAboveAnchorBackgroundDrawable = null; // } // } // // a.recycle(); // } /** * <p>Create a new empty, non focusable popup window of dimension (0,0).</p> * * <p>The popup does not provide any background. This should be handled * by the content view.</p> */ public CustomPopupWindow() { this(null, 0, 0); } /** * <p>Create a new non focusable popup window which can display the * <tt>contentView</tt>. The dimension of the window are (0,0).</p> * * <p>The popup does not provide any background. This should be handled * by the content view.</p> * * @param contentView the popup's content */ public CustomPopupWindow(View contentView) { this(contentView, 0, 0); } /** * <p>Create a new empty, non focusable popup window. The dimension of the * window must be passed to this constructor.</p> * * <p>The popup does not provide any background. This should be handled * by the content view.</p> * * @param width the popup's width * @param height the popup's height */ public CustomPopupWindow(int width, int height) { this(null, width, height); } /** * <p>Create a new non focusable popup window which can display the * <tt>contentView</tt>. The dimension of the window must be passed to * this constructor.</p> * * <p>The popup does not provide any background. This should be handled * by the content view.</p> * * @param contentView the popup's content * @param width the popup's width * @param height the popup's height */ public CustomPopupWindow(View contentView, int width, int height) { this(contentView, width, height, false); } /** * <p>Create a new popup window which can display the <tt>contentView</tt>. * The dimension of the window must be passed to this constructor.</p> * * <p>The popup does not provide any background. This should be handled * by the content view.</p> * * @param contentView the popup's content * @param width the popup's width * @param height the popup's height * @param focusable true if the popup can be focused, false otherwise */ public CustomPopupWindow(View contentView, int width, int height, boolean focusable) { if (contentView != null) { mContext = contentView.getContext(); mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); } setContentView(contentView); setWidth(width); setHeight(height); setFocusable(focusable); } /** * <p>Return the drawable used as the popup window's background.</p> * * @return the background drawable or null */ public Drawable getBackground() { return mBackground; } /** * <p>Change the background drawable for this popup window. The background * can be set to null.</p> * * @param background the popup's background */ public void setBackgroundDrawable(Drawable background) { mBackground = background; } /** * <p>Return the animation style to use the popup appears and disappears</p> * * @return the animation style to use the popup appears and disappears */ public int getAnimationStyle() { return mAnimationStyle; } /** * Set the flag on popup to ignore cheek press eventt; by default this flag * is set to false * which means the pop wont ignore cheek press dispatch events. * * <p>If the popup is showing, calling this method will take effect only * the next time the popup is shown or through a manual call to one of * the {@link #update()} methods.</p> * * @see #update() */ public void setIgnoreCheekPress() { mIgnoreCheekPress = true; } /** * <p>Change the animation style resource for this popup.</p> * * <p>If the popup is showing, calling this method will take effect only * the next time the popup is shown or through a manual call to one of * the {@link #update()} methods.</p> * * @param animationStyle animation style to use when the popup appears * and disappears. Set to -1 for the default animation, 0 for no * animation, or a resource identifier for an explicit animation. * * @see #update() */ public void setAnimationStyle(int animationStyle) { mAnimationStyle = animationStyle; } /** * <p>Return the view used as the content of the popup window.</p> * * @return a {@link android.view.View} representing the popup's content * * @see #setContentView(android.view.View) */ public View getContentView() { return mContentView; } /** * <p>Change the popup's content. The content is represented by an instance * of {@link android.view.View}.</p> * * <p>This method has no effect if called when the popup is showing. To * apply it while a popup is showing, call </p> * * @param contentView the new content for the popup * * @see #getContentView() * @see #isShowing() */ public void setContentView(View contentView) { if (isShowing()) { return; } mContentView = contentView; if (mContext == null) { mContext = mContentView.getContext(); } if (mWindowManager == null) { mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE); } } /** * Set a callback for all touch events being dispatched to the popup * window. */ public void setTouchInterceptor(OnTouchListener l) { mTouchInterceptor = l; } /** * <p>Indicate whether the popup window can grab the focus.</p> * * @return true if the popup is focusable, false otherwise * * @see #setFocusable(boolean) */ public boolean isFocusable() { return mFocusable; } /** * <p>Changes the focusability of the popup window. When focusable, the * window will grab the focus from the current focused widget if the popup * contains a focusable {@link android.view.View}. By default a popup * window is not focusable.</p> * * <p>If the popup is showing, calling this method will take effect only * the next time the popup is shown or through a manual call to one of * the {@link #update()} methods.</p> * * @param focusable true if the popup should grab focus, false otherwise. * * @see #isFocusable() * @see #isShowing() * @see #update() */ public void setFocusable(boolean focusable) { mFocusable = focusable; } /** * Return the current value in {@link #setInputMethodMode(int)}. * * @see #setInputMethodMode(int) */ public int getInputMethodMode() { return mInputMethodMode; } /** * Control how the popup operates with an input method: one of * {@link #INPUT_METHOD_FROM_FOCUSABLE}, {@link #INPUT_METHOD_NEEDED}, * or {@link #INPUT_METHOD_NOT_NEEDED}. * * <p>If the popup is showing, calling this method will take effect only * the next time the popup is shown or through a manual call to one of * the {@link #update()} methods.</p> * * @see #getInputMethodMode() * @see #update() */ public void setInputMethodMode(int mode) { mInputMethodMode = mode; } /** * Sets the operating mode for the soft input area. * * @param mode The desired mode, see * {@link android.view.WindowManager.LayoutParams#softInputMode} * for the full list * * @see android.view.WindowManager.LayoutParams#softInputMode * @see #getSoftInputMode() */ public void setSoftInputMode(int mode) { mSoftInputMode = mode; } /** * Returns the current value in {@link #setSoftInputMode(int)}. * * @see #setSoftInputMode(int) * @see android.view.WindowManager.LayoutParams#softInputMode */ public int getSoftInputMode() { return mSoftInputMode; } /** * <p>Indicates whether the popup window receives touch events.</p> * * @return true if the popup is touchable, false otherwise * * @see #setTouchable(boolean) */ public boolean isTouchable() { return mTouchable; } /** * <p>Changes the touchability of the popup window. When touchable, the * window will receive touch events, otherwise touch events will go to the * window below it. By default the window is touchable.</p> * * <p>If the popup is showing, calling this method will take effect only * the next time the popup is shown or through a manual call to one of * the {@link #update()} methods.</p> * * @param touchable true if the popup should receive touch events, false otherwise * * @see #isTouchable() * @see #isShowing() * @see #update() */ public void setTouchable(boolean touchable) { mTouchable = touchable; } /** * <p>Indicates whether the popup window will be informed of touch events * outside of its window.</p> * * @return true if the popup is outside touchable, false otherwise * * @see #setOutsideTouchable(boolean) */ public boolean isOutsideTouchable() { return mOutsideTouchable; } /** * <p>Controls whether the pop-up will be informed of touch events outside * of its window. This only makes sense for pop-ups that are touchable * but not focusable, which means touches outside of the window will * be delivered to the window behind. The default is false.</p> * * <p>If the popup is showing, calling this method will take effect only * the next time the popup is shown or through a manual call to one of * the {@link #update()} methods.</p> * * @param touchable true if the popup should receive outside * touch events, false otherwise * * @see #isOutsideTouchable() * @see #isShowing() * @see #update() */ public void setOutsideTouchable(boolean touchable) { mOutsideTouchable = touchable; } /** * <p>Indicates whether clipping of the popup window is enabled.</p> * * @return true if the clipping is enabled, false otherwise * * @see #setClippingEnabled(boolean) */ public boolean isClippingEnabled() { return mClippingEnabled; } /** * <p>Allows the popup window to extend beyond the bounds of the screen. By default the * window is clipped to the screen boundaries. Setting this to false will allow windows to be * accurately positioned.</p> * * <p>If the popup is showing, calling this method will take effect only * the next time the popup is shown or through a manual call to one of * the {@link #update()} methods.</p> * * @param enabled false if the window should be allowed to extend outside of the screen * @see #isShowing() * @see #isClippingEnabled() * @see #update() */ public void setClippingEnabled(boolean enabled) { mClippingEnabled = enabled; } /** * <p>Change the width and height measure specs that are given to the * window manager by the popup. By default these are 0, meaning that * the current width or height is requested as an explicit size from * the window manager. You can supply * {@link ViewGroup.LayoutParams#WRAP_CONTENT} or * {@link ViewGroup.LayoutParams#MATCH_PARENT} to have that measure * spec supplied instead, replacing the absolute width and height that * has been set in the popup.</p> * * <p>If the popup is showing, calling this method will take effect only * the next time the popup is shown.</p> * * @param widthSpec an explicit width measure spec mode, either * {@link ViewGroup.LayoutParams#WRAP_CONTENT}, * {@link ViewGroup.LayoutParams#MATCH_PARENT}, or 0 to use the absolute * width. * @param heightSpec an explicit height measure spec mode, either * {@link ViewGroup.LayoutParams#WRAP_CONTENT}, * {@link ViewGroup.LayoutParams#MATCH_PARENT}, or 0 to use the absolute * height. */ public void setWindowLayoutMode(int widthSpec, int heightSpec) { mWidthMode = widthSpec; mHeightMode = heightSpec; } /** * <p>Return this popup's height MeasureSpec</p> * * @return the height MeasureSpec of the popup * * @see #setHeight(int) */ public int getHeight() { return mHeight; } /** * <p>Change the popup's height MeasureSpec</p> * * <p>If the popup is showing, calling this method will take effect only * the next time the popup is shown.</p> * * @param height the height MeasureSpec of the popup * * @see #getHeight() * @see #isShowing() */ public void setHeight(int height) { mHeight = height; } /** * <p>Return this popup's width MeasureSpec</p> * * @return the width MeasureSpec of the popup * * @see #setWidth(int) */ public int getWidth() { return mWidth; } /** * <p>Change the popup's width MeasureSpec</p> * * <p>If the popup is showing, calling this method will take effect only * the next time the popup is shown.</p> * * @param width the width MeasureSpec of the popup * * @see #getWidth() * @see #isShowing() */ public void setWidth(int width) { mWidth = width; } /** * <p>Indicate whether this popup window is showing on screen.</p> * * @return true if the popup is showing, false otherwise */ public boolean isShowing() { return mIsShowing; } /** * <p> * Display the content view in a popup window at the specified location. If the popup window * cannot fit on screen, it will be clipped. See {@link android.view.WindowManager.LayoutParams} * for more information on how gravity and the x and y parameters are related. Specifying * a gravity of {@link android.view.Gravity#NO_GRAVITY} is similar to specifying * <code>Gravity.LEFT | Gravity.TOP</code>. * </p> * * @param parent a parent view to get the {@link android.view.View#getWindowToken()} token from * @param gravity the gravity which controls the placement of the popup window * @param x the popup's x location offset * @param y the popup's y location offset */ public void showAtLocation(View parent, int gravity, int x, int y) { if (isShowing() || mContentView == null) { return; } unregisterForScrollChanged(); mIsShowing = true; mIsDropdown = false; WindowManager.LayoutParams p = createPopupLayout(parent.getWindowToken()); p.windowAnimations = computeAnimationResource(); preparePopup(p); if (gravity == Gravity.NO_GRAVITY) { gravity = Gravity.TOP | Gravity.LEFT; } p.gravity = gravity; p.x = x; p.y = y; invokePopup(p); } /** * <p>Display the content view in a popup window anchored to the bottom-left * corner of the anchor view. If there is not enough room on screen to show * the popup in its entirety, this method tries to find a parent scroll * view to scroll. If no parent scroll view can be scrolled, the bottom-left * corner of the popup is pinned at the top left corner of the anchor view.</p> * * @param anchor the view on which to pin the popup window * * @see #dismiss() */ public void showAsDropDown(View anchor) { showAsDropDown(anchor, 0, 0); } /** * <p>Display the content view in a popup window anchored to the bottom-left * corner of the anchor view offset by the specified x and y coordinates. * If there is not enough room on screen to show * the popup in its entirety, this method tries to find a parent scroll * view to scroll. If no parent scroll view can be scrolled, the bottom-left * corner of the popup is pinned at the top left corner of the anchor view.</p> * <p>If the view later scrolls to move <code>anchor</code> to a different * location, the popup will be moved correspondingly.</p> * * @param anchor the view on which to pin the popup window * * @see #dismiss() */ public void showAsDropDown(View anchor, int xoff, int yoff) { if (isShowing() || mContentView == null) { return; } registerForScrollChanged(anchor, xoff, yoff); mIsShowing = true; mIsDropdown = true; WindowManager.LayoutParams p = createPopupLayout(anchor.getWindowToken()); preparePopup(p); updateAboveAnchor(findDropDownPosition(anchor, p, xoff, yoff)); if (mHeightMode < 0) p.height = mLastHeight = mHeightMode; if (mWidthMode < 0) p.width = mLastWidth = mWidthMode; p.windowAnimations = computeAnimationResource(); invokePopup(p); } private void updateAboveAnchor(boolean aboveAnchor) { if (aboveAnchor != mAboveAnchor) { mAboveAnchor = aboveAnchor; if (mBackground != null) { // If the background drawable provided was a StateListDrawable with above-anchor // and below-anchor states, use those. Otherwise rely on refreshDrawableState to // do the job. if (mAboveAnchorBackgroundDrawable != null) { if (mAboveAnchor) { mPopupView.setBackgroundDrawable(mAboveAnchorBackgroundDrawable); } else { mPopupView.setBackgroundDrawable(mBelowAnchorBackgroundDrawable); } } else { mPopupView.refreshDrawableState(); } } } } /** * Indicates whether the popup is showing above (the y coordinate of the popup's bottom * is less than the y coordinate of the anchor) or below the anchor view (the y coordinate * of the popup is greater than y coordinate of the anchor's bottom). * * The value returned * by this method is meaningful only after {@link #showAsDropDown(android.view.View)} * or {@link #showAsDropDown(android.view.View, int, int)} was invoked. * * @return True if this popup is showing above the anchor view, false otherwise. */ public boolean isAboveAnchor() { return mAboveAnchor; } /** * <p>Prepare the popup by embedding in into a new ViewGroup if the * background drawable is not null. If embedding is required, the layout * parameters' height is mnodified to take into account the background's * padding.</p> * * @param p the layout parameters of the popup's content view */ private void preparePopup(WindowManager.LayoutParams p) { if (mContentView == null || mContext == null || mWindowManager == null) { throw new IllegalStateException("You must specify a valid content view by " + "calling setContentView() before attempting to show the popup."); } if (mBackground != null) { final ViewGroup.LayoutParams layoutParams = mContentView.getLayoutParams(); int height = ViewGroup.LayoutParams.MATCH_PARENT; if (layoutParams != null && layoutParams.height == ViewGroup.LayoutParams.WRAP_CONTENT) { height = ViewGroup.LayoutParams.WRAP_CONTENT; } // when a background is available, we embed the content view // within another view that owns the background drawable PopupViewContainer popupViewContainer = new PopupViewContainer(mContext); PopupViewContainer.LayoutParams listParams = new PopupViewContainer.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, height ); popupViewContainer.setBackgroundDrawable(mBackground); popupViewContainer.addView(mContentView, listParams); mPopupView = popupViewContainer; } else { mPopupView = mContentView; } mPopupWidth = p.width; mPopupHeight = p.height; } /** * <p>Invoke the popup window by adding the content view to the window * manager.</p> * * <p>The content view must be non-null when this method is invoked.</p> * * @param p the layout parameters of the popup's content view */ private void invokePopup(WindowManager.LayoutParams p) { p.packageName = mContext.getPackageName(); mWindowManager.addView(mPopupView, p); } /** * <p>Generate the layout parameters for the popup window.</p> * * @param token the window token used to bind the popup's window * * @return the layout parameters to pass to the window manager */ private WindowManager.LayoutParams createPopupLayout(IBinder token) { // generates the layout parameters for the drop down // we want a fixed size view located at the bottom left of the anchor WindowManager.LayoutParams p = new WindowManager.LayoutParams(); // these gravity settings put the view at the top left corner of the // screen. The view is then positioned to the appropriate location // by setting the x and y offsets to match the anchor's bottom // left corner p.gravity = Gravity.LEFT | Gravity.TOP; p.width = mLastWidth = mWidth; p.height = mLastHeight = mHeight; if (mBackground != null) { p.format = mBackground.getOpacity(); } else { p.format = PixelFormat.TRANSLUCENT; } p.flags = computeFlags(p.flags); p.type = WindowManager.LayoutParams.TYPE_APPLICATION_PANEL; p.token = token; p.softInputMode = mSoftInputMode; p.setTitle("PopupWindow:" + Integer.toHexString(hashCode())); return p; } private int computeFlags(int curFlags) { curFlags &= ~( WindowManager.LayoutParams.FLAG_IGNORE_CHEEK_PRESSES | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); if(mIgnoreCheekPress) { curFlags |= WindowManager.LayoutParams.FLAG_IGNORE_CHEEK_PRESSES; } if (!mFocusable) { curFlags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; if (mInputMethodMode == INPUT_METHOD_NEEDED) { curFlags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM; } } else if (mInputMethodMode == INPUT_METHOD_NOT_NEEDED) { curFlags |= WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM; } if (!mTouchable) { curFlags |= WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE; } if (mOutsideTouchable) { curFlags |= WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH; } if (!mClippingEnabled) { curFlags |= WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS; } return curFlags; } private int computeAnimationResource() { if (mAnimationStyle == -1) { if (mIsDropdown) { // return mAboveAnchor // ? com.android.internal.R.style.Animation_DropDownUp // : com.android.internal.R.style.Animation_DropDownDown; return R.style.PopupAlaphAnimation; } return 0; } return mAnimationStyle; } /** * <p>Positions the popup window on screen. When the popup window is too * tall to fit under the anchor, a parent scroll view is seeked and scrolled * up to reclaim space. If scrolling is not possible or not enough, the * popup window gets moved on top of the anchor.</p> * * <p>The height must have been set on the layout parameters prior to * calling this method.</p> * * @param anchor the view on which the popup window must be anchored * @param p the layout parameters used to display the drop down * * @return true if the popup is translated upwards to fit on screen */ private boolean findDropDownPosition(View anchor, WindowManager.LayoutParams p, int xoff, int yoff) { anchor.getLocationInWindow(mDrawingLocation); p.x = mDrawingLocation[0] + xoff; p.y = mDrawingLocation[1] + anchor.getHeight() + yoff; boolean onTop = false; p.gravity = Gravity.LEFT | Gravity.TOP; anchor.getLocationOnScreen(mScreenLocation); final Rect displayFrame = new Rect(); anchor.getWindowVisibleDisplayFrame(displayFrame); final View root = anchor.getRootView(); if (p.y + mPopupHeight > displayFrame.bottom || p.x + mPopupWidth - root.getWidth() > 0) { // if the drop down disappears at the bottom of the screen. we try to // scroll a parent scrollview or move the drop down back up on top of // the edit box int scrollX = anchor.getScrollX(); int scrollY = anchor.getScrollY(); Rect r = new Rect(scrollX, scrollY, scrollX + mPopupWidth + xoff, scrollY + mPopupHeight + anchor.getHeight() + yoff); anchor.requestRectangleOnScreen(r, true); // now we re-evaluate the space available, and decide from that // whether the pop-up will go above or below the anchor. anchor.getLocationInWindow(mDrawingLocation); p.x = mDrawingLocation[0] + xoff; p.y = mDrawingLocation[1] + anchor.getHeight() + yoff; // determine whether there is more space above or below the anchor anchor.getLocationOnScreen(mScreenLocation); onTop = (displayFrame.bottom - mScreenLocation[1] - anchor.getHeight() - yoff) < (mScreenLocation[1] - yoff - displayFrame.top); if (onTop) { p.gravity = Gravity.LEFT | Gravity.BOTTOM; p.y = root.getHeight() - mDrawingLocation[1] + yoff; } else { p.y = mDrawingLocation[1] + anchor.getHeight() + yoff; } } p.gravity |= Gravity.DISPLAY_CLIP_VERTICAL; return onTop; } /** * Returns the maximum height that is available for the popup to be * completely shown. It is recommended that this height be the maximum for * the popup's height, otherwise it is possible that the popup will be * clipped. * * @param anchor The view on which the popup window must be anchored. * @return The maximum available height for the popup to be completely * shown. */ public int getMaxAvailableHeight(View anchor) { return getMaxAvailableHeight(anchor, 0); } /** * Returns the maximum height that is available for the popup to be * completely shown. It is recommended that this height be the maximum for * the popup's height, otherwise it is possible that the popup will be * clipped. * * @param anchor The view on which the popup window must be anchored. * @param yOffset y offset from the view's bottom edge * @return The maximum available height for the popup to be completely * shown. */ public int getMaxAvailableHeight(View anchor, int yOffset) { return getMaxAvailableHeight(anchor, yOffset, false); } /** * Returns the maximum height that is available for the popup to be * completely shown, optionally ignoring any bottom decorations such as * the input method. It is recommended that this height be the maximum for * the popup's height, otherwise it is possible that the popup will be * clipped. * * @param anchor The view on which the popup window must be anchored. * @param yOffset y offset from the view's bottom edge * @param ignoreBottomDecorations if true, the height returned will be * all the way to the bottom of the display, ignoring any * bottom decorations * @return The maximum available height for the popup to be completely * shown. * * @hide Pending API council approval. */ public int getMaxAvailableHeight(View anchor, int yOffset, boolean ignoreBottomDecorations) { final Rect displayFrame = new Rect(); anchor.getWindowVisibleDisplayFrame(displayFrame); final int[] anchorPos = mDrawingLocation; anchor.getLocationOnScreen(anchorPos); int bottomEdge = displayFrame.bottom; if (ignoreBottomDecorations) { bottomEdge = anchor.getContext().getResources().getDisplayMetrics().heightPixels; } final int distanceToBottom = bottomEdge - (anchorPos[1] + anchor.getHeight()) - yOffset; final int distanceToTop = anchorPos[1] - displayFrame.top + yOffset; // anchorPos[1] is distance from anchor to top of screen int returnedHeight = Math.max(distanceToBottom, distanceToTop); if (mBackground != null) { mBackground.getPadding(mTempRect); returnedHeight -= mTempRect.top + mTempRect.bottom; } return returnedHeight; } /** * <p>Dispose of the popup window. This method can be invoked only after * {@link #showAsDropDown(android.view.View)} has been executed. Failing that, calling * this method will have no effect.</p> * * @see #showAsDropDown(android.view.View) */ public void dismiss() { if (isShowing() && mPopupView != null) { unregisterForScrollChanged(); try { mWindowManager.removeView(mPopupView); } finally { if (mPopupView != mContentView && mPopupView instanceof ViewGroup) { ((ViewGroup) mPopupView).removeView(mContentView); } mPopupView = null; mIsShowing = false; if (mOnDismissListener != null) { mOnDismissListener.onDismiss(); } } } } /** * Sets the listener to be called when the window is dismissed. * * @param onDismissListener The listener. */ public void setOnDismissListener(OnDismissListener onDismissListener) { mOnDismissListener = onDismissListener; } /** * Updates the state of the popup window, if it is currently being displayed, * from the currently set state. This include: * {@link #setClippingEnabled(boolean)}, {@link #setFocusable(boolean)}, * {@link #setIgnoreCheekPress()}, {@link #setInputMethodMode(int)}, * {@link #setTouchable(boolean)}, and {@link #setAnimationStyle(int)}. */ public void update() { if (!isShowing() || mContentView == null) { return; } WindowManager.LayoutParams p = (WindowManager.LayoutParams) mPopupView.getLayoutParams(); boolean update = false; final int newAnim = computeAnimationResource(); if (newAnim != p.windowAnimations) { p.windowAnimations = newAnim; update = true; } final int newFlags = computeFlags(p.flags); if (newFlags != p.flags) { p.flags = newFlags; update = true; } if (update) { mWindowManager.updateViewLayout(mPopupView, p); } } /** * <p>Updates the dimension of the popup window. Calling this function * also updates the window with the current popup state as described * for {@link #update()}.</p> * * @param width the new width * @param height the new height */ public void update(int width, int height) { WindowManager.LayoutParams p = (WindowManager.LayoutParams) mPopupView.getLayoutParams(); update(p.x, p.y, width, height, false); } /** * <p>Updates the position and the dimension of the popup window. Width and * height can be set to -1 to update location only. Calling this function * also updates the window with the current popup state as * described for {@link #update()}.</p> * * @param x the new x location * @param y the new y location * @param width the new width, can be -1 to ignore * @param height the new height, can be -1 to ignore */ public void update(int x, int y, int width, int height) { update(x, y, width, height, false); } /** * <p>Updates the position and the dimension of the popup window. Width and * height can be set to -1 to update location only. Calling this function * also updates the window with the current popup state as * described for {@link #update()}.</p> * * @param x the new x location * @param y the new y location * @param width the new width, can be -1 to ignore * @param height the new height, can be -1 to ignore * @param force reposition the window even if the specified position * already seems to correspond to the LayoutParams */ public void update(int x, int y, int width, int height, boolean force) { if (width != -1) { mLastWidth = width; setWidth(width); } if (height != -1) { mLastHeight = height; setHeight(height); } if (!isShowing() || mContentView == null) { return; } WindowManager.LayoutParams p = (WindowManager.LayoutParams) mPopupView.getLayoutParams(); boolean update = force; final int finalWidth = mWidthMode < 0 ? mWidthMode : mLastWidth; if (width != -1 && p.width != finalWidth) { p.width = mLastWidth = finalWidth; update = true; } final int finalHeight = mHeightMode < 0 ? mHeightMode : mLastHeight; if (height != -1 && p.height != finalHeight) { p.height = mLastHeight = finalHeight; update = true; } if (p.x != x) { p.x = x; update = true; } if (p.y != y) { p.y = y; update = true; } final int newAnim = computeAnimationResource(); if (newAnim != p.windowAnimations) { p.windowAnimations = newAnim; update = true; } final int newFlags = computeFlags(p.flags); if (newFlags != p.flags) { p.flags = newFlags; update = true; } if (update) { mWindowManager.updateViewLayout(mPopupView, p); } } /** * <p>Updates the position and the dimension of the popup window. Calling this * function also updates the window with the current popup state as described * for {@link #update()}.</p> * * @param anchor the popup's anchor view * @param width the new width, can be -1 to ignore * @param height the new height, can be -1 to ignore */ public void update(View anchor, int width, int height) { update(anchor, false, 0, 0, true, width, height); } /** * <p>Updates the position and the dimension of the popup window. Width and * height can be set to -1 to update location only. Calling this function * also updates the window with the current popup state as * described for {@link #update()}.</p> * <p>If the view later scrolls to move <code>anchor</code> to a different * location, the popup will be moved correspondingly.</p> * * @param anchor the popup's anchor view * @param xoff x offset from the view's left edge * @param yoff y offset from the view's bottom edge * @param width the new width, can be -1 to ignore * @param height the new height, can be -1 to ignore */ public void update(View anchor, int xoff, int yoff, int width, int height) { update(anchor, true, xoff, yoff, true, width, height); } private void update(View anchor, boolean updateLocation, int xoff, int yoff, boolean updateDimension, int width, int height) { if (!isShowing() || mContentView == null) { return; } WeakReference<View> oldAnchor = mAnchor; if (oldAnchor == null || oldAnchor.get() != anchor || (updateLocation && (mAnchorXoff != xoff || mAnchorYoff != yoff))) { registerForScrollChanged(anchor, xoff, yoff); } WindowManager.LayoutParams p = (WindowManager.LayoutParams) mPopupView.getLayoutParams(); if (updateDimension) { if (width == -1) { width = mPopupWidth; } else { mPopupWidth = width; } if (height == -1) { height = mPopupHeight; } else { mPopupHeight = height; } } int x = p.x; int y = p.y; if (updateLocation) { updateAboveAnchor(findDropDownPosition(anchor, p, xoff, yoff)); } else { updateAboveAnchor(findDropDownPosition(anchor, p, mAnchorXoff, mAnchorYoff)); } update(p.x, p.y, width, height, x != p.x || y != p.y); } /** * Listener that is called when this popup window is dismissed. */ public interface OnDismissListener { /** * Called when this popup window is dismissed. */ public void onDismiss(); } private void unregisterForScrollChanged() { WeakReference<View> anchorRef = mAnchor; View anchor = null; if (anchorRef != null) { anchor = anchorRef.get(); } if (anchor != null) { ViewTreeObserver vto = anchor.getViewTreeObserver(); vto.removeOnScrollChangedListener(mOnScrollChangedListener); } mAnchor = null; } private void registerForScrollChanged(View anchor, int xoff, int yoff) { unregisterForScrollChanged(); mAnchor = new WeakReference<View>(anchor); ViewTreeObserver vto = anchor.getViewTreeObserver(); if (vto != null) { vto.addOnScrollChangedListener(mOnScrollChangedListener); } mAnchorXoff = xoff; mAnchorYoff = yoff; } private class PopupViewContainer extends FrameLayout { public PopupViewContainer(Context context) { super(context); } @Override protected int[] onCreateDrawableState(int extraSpace) { if (mAboveAnchor) { // 1 more needed for the above anchor state final int[] drawableState = super.onCreateDrawableState(extraSpace + 1); View.mergeDrawableStates(drawableState, ABOVE_ANCHOR_STATE_SET); return drawableState; } else { return super.onCreateDrawableState(extraSpace); } } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) { if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) { getKeyDispatcherState().startTracking(event, this); return true; } else if (event.getAction() == KeyEvent.ACTION_UP && getKeyDispatcherState().isTracking(event) && !event.isCanceled()) { dismiss(); return true; } return super.dispatchKeyEvent(event); } else { return super.dispatchKeyEvent(event); } } @Override public boolean dispatchTouchEvent(MotionEvent ev) { if (mTouchInterceptor != null && mTouchInterceptor.onTouch(this, ev)) { return true; } return super.dispatchTouchEvent(ev); } @Override public boolean onTouchEvent(MotionEvent event) { final int x = (int) event.getX(); final int y = (int) event.getY(); if ((event.getAction() == MotionEvent.ACTION_DOWN) && ((x < 0) || (x >= getWidth()) || (y < 0) || (y >= getHeight()))) { dismiss(); return true; } else if (event.getAction() == MotionEvent.ACTION_OUTSIDE) { dismiss(); return true; } else { return super.onTouchEvent(event); } } @Override public void sendAccessibilityEvent(int eventType) { // clinets are interested in the content not the container, make it event source if (mContentView != null) { mContentView.sendAccessibilityEvent(eventType); } else { super.sendAccessibilityEvent(eventType); } } } }
Java
package com.outsourcing.bottle.db; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import com.outsourcing.bottle.domain.LanguageConfig; /** * * @author 06peng * */ public class LanguageConfigTable { private final String TABLE_BOTTLE_LANGUAGE_CONFIG = "bottle_language_config"; private String bottle_throw_tips_en = "bottle_throw_tips_en"; private String bottle_throw_tips_2_en ="bottle_throw_tips_2_en"; private String bottle_gain_tips_en = "bottle_gain_tips_en"; private String bottle_gain_tips_2_en = "bottle_gain_tips_2_en"; private String exchange_profile_tip_en = "exchange_profile_tip_en"; private String exchange_profile_tip_2_en = "exchange_profile_tip_2_en"; private String exchange_profile_intro_en = "exchange_profile_intro_en"; private String exchange_photo_tip_en = "exchange_photo_tip_en"; private String exchange_photo_tip_2_en = "exchange_photo_tip_2_en"; private String exchange_photo_intro_en = "exchange_photo_intro_en"; private String without_btfriend_tip_en = "without_btfriend_tip_en"; private String without_btfriend_tip_2_en = "without_btfriend_tip_2_en"; private String without_friend_tip_en = "without_friend_tip_en"; private String without_friend_tip_2_en = "without_friend_tip_2_en"; private String without_maybeknow_tip_en = "without_maybeknow_tip_en"; private String without_maybeknow_tip_invite_en = "without_maybeknow_tip_invite_en"; private String without_maybeknow_tip_setup_en = "without_maybeknow_tip_setup_en"; private String without_maybeknow_tip_mobile_en = "without_maybeknow_tip_mobile_en"; private String bottle_throw_tips_cn = "bottle_throw_tips_cn"; private String bottle_throw_tips_2_cn ="bottle_throw_tips_2_cn"; private String bottle_gain_tips_cn = "bottle_gain_tips_cn"; private String bottle_gain_tips_2_cn ="bottle_gain_tips_2_cn"; private String exchange_profile_tip_cn = "exchange_profile_tip_cn"; private String exchange_profile_tip_2_cn = "exchange_profile_tip_2_cn"; private String exchange_profile_intro_cn ="exchange_profile_intro_cn"; private String exchange_photo_tip_cn ="exchange_photo_tip_cn"; private String exchange_photo_tip_2_cn = "exchange_photo_tip_2_cn"; private String exchange_photo_intro_cn = "exchange_photo_intro_cn"; private String without_btfriend_tip_cn ="without_btfriend_tip_cn"; private String without_btfriend_tip_2_cn = "without_btfriend_tip_2_cn"; private String without_friend_tip_cn = "without_friend_tip_cn"; private String without_friend_tip_2_cn = "without_friend_tip_2_cn"; private String without_maybeknow_tip_cn ="without_maybeknow_tip_cn"; private String without_maybeknow_tip_invite_cn ="without_maybeknow_tip_invite_cn"; private String without_maybeknow_tip_setup_cn ="without_maybeknow_tip_setup_cn"; private String without_maybeknow_tip_mobile_cn = "without_maybeknow_tip_mobile_cn"; private DBManagerImpl db = null; public LanguageConfigTable() { if (db == null) { db = DBManager.get(); } if (!db.isTableExits(db.getConnection(), TABLE_BOTTLE_LANGUAGE_CONFIG)) { createBottleNetType(); } } public LanguageConfigTable(Context context) { if (db == null) { db = DBManager.get(context); } if (!db.isTableExits(db.getConnection(), TABLE_BOTTLE_LANGUAGE_CONFIG)) { createBottleNetType(); } } private void createBottleNetType() { String createSql = "create table if not exists "+TABLE_BOTTLE_LANGUAGE_CONFIG+" (id integer primary key autoincrement, bottle_throw_tips_en varchar, bottle_throw_tips_2_en varchar, bottle_gain_tips_en varchar," + "bottle_gain_tips_2_en varchar, exchange_profile_tip_en varchar, exchange_profile_tip_2_en varchar, exchange_profile_intro_en varchar, exchange_photo_tip_en varchar, exchange_photo_tip_2_en varchar,exchange_photo_intro_en varchar,without_btfriend_tip_en varchar,"+ "without_btfriend_tip_2_en varchar,without_friend_tip_en varchar, without_friend_tip_2_en varchar,without_maybeknow_tip_en varchar,without_maybeknow_tip_invite_en varchar,without_maybeknow_tip_setup_en varchar,without_maybeknow_tip_mobile_en varchar,bottle_throw_tips_cn varchar,"+ "bottle_throw_tips_2_cn varchar,bottle_gain_tips_cn varchar,bottle_gain_tips_2_cn varchar,exchange_profile_tip_cn varchar,exchange_profile_tip_2_cn varchar,exchange_profile_intro_cn varchar, exchange_photo_tip_cn varchar,exchange_photo_tip_2_cn vrchar, exchange_photo_intro_cn varchar,"+ "without_btfriend_tip_cn varchar,without_btfriend_tip_2_cn varchar,"+ "without_friend_tip_cn varchar,without_friend_tip_2_cn varchar,without_maybeknow_tip_cn varchar,without_maybeknow_tip_invite_cn varchar,without_maybeknow_tip_setup_cn varchar,without_maybeknow_tip_mobile_cn varchar)"; db.creatTable(db.getConnection(), createSql, TABLE_BOTTLE_LANGUAGE_CONFIG); } public void saveBottleLanguageConfig(LanguageConfig entry) { try { ContentValues values = new ContentValues(); values.put(bottle_throw_tips_en, entry.getBottle_throw_tips_en()); values.put(bottle_throw_tips_2_en, entry.getBottle_throw_tips_2_en()); values.put(bottle_gain_tips_en, entry.getBottle_gain_tips_en()); values.put(bottle_gain_tips_2_en, entry.getBottle_gain_tips_2_en()); values.put(exchange_profile_tip_en, entry.getExchange_profile_tip_en()); values.put(exchange_profile_tip_2_en, entry.getExchange_profile_tip_2_en()); values.put(exchange_profile_intro_en, entry.getExchange_profile_intro_en()); values.put(exchange_photo_tip_en, entry.getExchange_photo_tip_en()); values.put(exchange_photo_tip_2_en, entry.getExchange_photo_tip_2_en()); values.put(exchange_photo_intro_en, entry.getExchange_profile_intro_en()); values.put(without_btfriend_tip_en, entry.getWithout_btfriend_tip_en()); values.put(without_btfriend_tip_2_en, entry.getWithout_btfriend_tip_2_en()); values.put(without_friend_tip_en, entry.getWithout_friend_tip_en()); values.put(without_friend_tip_2_en, entry.getWithout_friend_tip_2_en()); values.put(without_maybeknow_tip_en, entry.getWithout_maybeknow_tip_en()); values.put(without_maybeknow_tip_invite_en, entry.getWithout_maybeknow_tip_invite_en()); values.put(without_maybeknow_tip_setup_en, entry.getWithout_maybeknow_tip_setup_en()); values.put(without_maybeknow_tip_mobile_en, entry.getWithout_maybeknow_tip_mobile_en()); values.put(bottle_throw_tips_cn, entry.getBottle_throw_tips_cn()); values.put(bottle_throw_tips_2_cn, entry.getBottle_throw_tips_2_cn()); values.put(bottle_gain_tips_cn, entry.getBottle_gain_tips_cn()); values.put(bottle_gain_tips_2_cn, entry.getBottle_gain_tips_2_cn()); values.put(exchange_profile_tip_cn, entry.getExchange_profile_tip_cn()); values.put(exchange_profile_tip_2_cn, entry.getExchange_profile_tip_2_cn()); values.put(exchange_profile_intro_cn, entry.getExchange_profile_intro_cn()); values.put(exchange_photo_tip_cn, entry.getExchange_photo_tip_cn()); values.put(exchange_photo_tip_2_cn, entry.getExchange_photo_tip_2_cn()); values.put(exchange_photo_intro_cn, entry.getExchange_photo_intro_cn()); values.put(without_btfriend_tip_cn, entry.getWithout_btfriend_tip_cn()); values.put(without_btfriend_tip_2_cn, entry.getWithout_btfriend_tip_2_cn()); values.put(without_friend_tip_cn, entry.getWithout_friend_tip_cn()); values.put(without_friend_tip_2_cn, entry.getWithout_friend_tip_2_cn()); values.put(without_maybeknow_tip_cn, entry.getWithout_maybeknow_tip_cn()); values.put(without_maybeknow_tip_invite_cn, entry.getWithout_maybeknow_tip_invite_cn()); values.put(without_maybeknow_tip_setup_cn, entry.getWithout_maybeknow_tip_setup_cn()); values.put(without_maybeknow_tip_mobile_cn, entry.getWithout_maybeknow_tip_mobile_cn()); db.save(db.getConnection(), TABLE_BOTTLE_LANGUAGE_CONFIG, values); } catch (Exception e) { e.printStackTrace(); } finally{ db.closeConnection(); } } public LanguageConfig getBottleLanguageConfig() { Cursor cursor = null; LanguageConfig entry = null; try { cursor = db.find(db.getConnection(), "select * from " + TABLE_BOTTLE_LANGUAGE_CONFIG, null); if (cursor != null) { while (cursor.moveToNext()) { entry = new LanguageConfig(); entry.setBottle_throw_tips_en(cursor.getString(cursor.getColumnIndex(bottle_throw_tips_en))); entry.setBottle_throw_tips_2_en(cursor.getString(cursor.getColumnIndex(bottle_throw_tips_2_en))); entry.setBottle_gain_tips_en(cursor.getString(cursor.getColumnIndex(bottle_gain_tips_en))); entry.setBottle_gain_tips_2_en(cursor.getString(cursor.getColumnIndex(bottle_gain_tips_2_en))); entry.setExchange_profile_tip_en(cursor.getString(cursor.getColumnIndex(exchange_profile_tip_en))); entry.setExchange_profile_tip_2_en(cursor.getString(cursor.getColumnIndex(exchange_profile_tip_2_en))); entry.setExchange_profile_intro_en(cursor.getString(cursor.getColumnIndex(exchange_profile_intro_en))); entry.setExchange_photo_tip_en(cursor.getString(cursor.getColumnIndex(exchange_photo_tip_en))); entry.setExchange_photo_tip_2_en(cursor.getString(cursor.getColumnIndex(exchange_photo_tip_2_en))); entry.setExchange_profile_intro_en(cursor.getString(cursor.getColumnIndex(exchange_photo_intro_en))); entry.setWithout_btfriend_tip_en(cursor.getString(cursor.getColumnIndex(without_btfriend_tip_en))); entry.setWithout_btfriend_tip_2_en(cursor.getString(cursor.getColumnIndex(without_btfriend_tip_2_en))); entry.setWithout_friend_tip_en(cursor.getString(cursor.getColumnIndex(without_friend_tip_en))); entry.setWithout_friend_tip_2_en(cursor.getString(cursor.getColumnIndex(without_friend_tip_2_en))); entry.setWithout_maybeknow_tip_en(cursor.getString(cursor.getColumnIndex(without_maybeknow_tip_en))); entry.setWithout_maybeknow_tip_invite_en(cursor.getString(cursor.getColumnIndex(without_maybeknow_tip_invite_en))); entry.setWithout_maybeknow_tip_setup_en(cursor.getString(cursor.getColumnIndex(without_maybeknow_tip_setup_en))); entry.setWithout_maybeknow_tip_mobile_en(cursor.getString(cursor.getColumnIndex(without_maybeknow_tip_mobile_en))); entry.setBottle_throw_tips_cn(cursor.getString(cursor.getColumnIndex(bottle_throw_tips_cn))); entry.setBottle_throw_tips_2_cn(cursor.getString(cursor.getColumnIndex(bottle_throw_tips_2_cn))); entry.setBottle_gain_tips_cn(cursor.getString(cursor.getColumnIndex(bottle_gain_tips_cn))); entry.setBottle_gain_tips_2_cn(cursor.getString(cursor.getColumnIndex(bottle_gain_tips_2_cn))); entry.setExchange_profile_tip_cn(cursor.getString(cursor.getColumnIndex(exchange_profile_tip_cn))); entry.setExchange_profile_tip_2_cn(cursor.getString(cursor.getColumnIndex(exchange_profile_tip_2_cn))); entry.setExchange_profile_intro_cn(cursor.getString(cursor.getColumnIndex(exchange_profile_intro_cn))); entry.setExchange_photo_tip_cn(cursor.getString(cursor.getColumnIndex(exchange_photo_tip_cn))); entry.setExchange_photo_tip_2_cn(cursor.getString(cursor.getColumnIndex(exchange_photo_tip_2_cn))); entry.setExchange_photo_intro_cn(cursor.getString(cursor.getColumnIndex(exchange_photo_intro_cn))); entry.setWithout_btfriend_tip_cn(cursor.getString(cursor.getColumnIndex(without_btfriend_tip_cn))); entry.setWithout_btfriend_tip_2_cn(cursor.getString(cursor.getColumnIndex(without_btfriend_tip_2_cn))); entry.setWithout_friend_tip_cn(cursor.getString(cursor.getColumnIndex(without_friend_tip_cn))); entry.setWithout_friend_tip_2_cn(cursor.getString(cursor.getColumnIndex(without_friend_tip_2_cn))); entry.setWithout_maybeknow_tip_cn(cursor.getString(cursor.getColumnIndex(without_maybeknow_tip_cn))); entry.setWithout_maybeknow_tip_invite_cn(cursor.getString(cursor.getColumnIndex(without_maybeknow_tip_invite_cn))); entry.setWithout_maybeknow_tip_setup_cn(cursor.getString(cursor.getColumnIndex(without_maybeknow_tip_setup_cn))); entry.setWithout_maybeknow_tip_mobile_cn(cursor.getString(cursor.getColumnIndex(without_maybeknow_tip_mobile_cn))); } } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } return entry; } public void clearTable() { db.delete(db.getConnection(), TABLE_BOTTLE_LANGUAGE_CONFIG, null, null); } }
Java
package com.outsourcing.bottle.db; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.outsourcing.bottle.util.AppContext; /** * 数据库管理类 * @author 06peng * */ public class DBManager extends SQLiteOpenHelper implements DBManagerImpl { private static String DB_NAME = "mobi_bottle.db"; // 数据库名称 private static int DB_VERSION = 1; // 版本号 private SQLiteDatabase db; // private static DBManager dbManager = null; public static DBManager get() { if (null == dbManager) { dbManager = new DBManager(AppContext.getContext()); } dbManager.checkDb(); return dbManager; } public static DBManager get(Context conetxt) { if (null == dbManager) { dbManager = new DBManager(conetxt); } dbManager.checkDb(); return dbManager; } private void checkDb(){ if(null == db || !db.isOpen()){ db = getWritableDatabase(); //读写方式打开数据库 } } public DBManager(Context context) { super(context, DB_NAME, null, DB_VERSION); db = getWritableDatabase(); } /** * 添加操作 * @param db 数据库 提供操作者 * @param insertSql 对应插入字段 如:insert into person(name,age) values(?,?) * @param obj 对应值 如: new Object[]{person.getName(),person.getAge()}; * @return */ public boolean save(Object dbobj, String insertSql, Object obj[]) { try { SQLiteDatabase db = (SQLiteDatabase) dbobj; db.execSQL(insertSql, obj); } catch (Exception ex) { ex.printStackTrace(); return false; } finally { closeConnection(db); } return true; } /** * 添加操作 * @param db 数据库 提供操作者 * @param tableName 表名 * @param values 集合对象 * @return */ public boolean save(Object dbobj, String tableName, ContentValues values) { SQLiteDatabase db = (SQLiteDatabase) dbobj; try { db.insert(tableName, null, values); } catch (Exception ex) { ex.printStackTrace(); return false; } finally { closeConnection(db); } return true; } /** * 更新操作 * @param db 数据库 提供操作者 * @param updateSql 对应跟新字段 如: update person set name=?,age=? where personid=?" * @param obj 对应值 如: new Object[]{person.getName(),person.getAge(),person.getPersonid()}; */ public boolean update(SQLiteDatabase db, String updateSql, Object obj[]) { try { db.execSQL(updateSql, obj); } catch (Exception ex) { ex.printStackTrace(); return false; } finally { closeConnection(db); } return true; } /** * 更新操作 * @param db 数据库 提供操作者 * @param table * @param values * @param whereClause * @param whereArgs * @return */ public boolean update(Object dbobj, String table, ContentValues values, String whereClause, String[] whereArgs) { SQLiteDatabase db = (SQLiteDatabase) dbobj; try { db.update(table, values, whereClause, whereArgs); } catch (Exception ex) { ex.printStackTrace(); return false; } finally { closeConnection(db); } return true; } /** * 删除 * @param db 数据库 提供操作者 * @param deleteSql 对应跟新字段 如: "where personid=?" * @param obj[] 对应值 如: new Object[]{person.getPersonid()}; * @return */ public boolean delete(Object dbobj, String table, String deleteSql, String obj[]) { SQLiteDatabase db = (SQLiteDatabase) dbobj; try { db.delete(table, deleteSql, obj); } catch (Exception ex) { ex.printStackTrace(); return false; } finally { closeConnection(db); } return true; } /** * 查询操作 * @param db * @param findSql 对应查询字段 如: select * from person limit ?,? * @param obj 对应值 如: new String[]{String.valueOf(fristResult),String.valueOf(maxResult)} * @return */ public Cursor find(Object dbobj, String findSql, String obj[]) { SQLiteDatabase db = (SQLiteDatabase) dbobj; try { Cursor cursor = db.rawQuery(findSql, obj); return cursor; } catch (Exception ex) { ex.printStackTrace(); return null; } } public boolean execSQL(Object dbobj, String sql) { SQLiteDatabase db = (SQLiteDatabase) dbobj; try { db.execSQL(sql); } catch (Exception ex) { ex.printStackTrace(); return false; } return true; } /** * 创建表 * @param db * @param createTableSql * @return */ public boolean creatTable(SQLiteDatabase db, String createTableSql) { try { db.execSQL(createTableSql); } catch (Exception ex) { ex.printStackTrace(); return false; } finally { closeConnection(db); } return true; } public boolean creatTable(Object dbobj, String createTableSql, String tablename) { SQLiteDatabase db = (SQLiteDatabase) dbobj; try { db.execSQL(createTableSql); } catch (Exception ex) { ex.printStackTrace(); return false; } finally { closeConnection(db); } return true; } public boolean deleteTable(Object dbobj, String tableName) { SQLiteDatabase db = (SQLiteDatabase) dbobj; try { db.execSQL("DROP TABLE IF EXISTS " + tableName); } catch (Exception ex) { ex.printStackTrace(); return false; } finally { closeConnection(db); } return true; } public boolean deleteTable2(SQLiteDatabase db, String tableName) { try { db.execSQL("DROP TABLE IF EXISTS " + tableName); } catch (Exception ex) { ex.printStackTrace(); return false; } return true; } /** * 判断表是否存在 * @param tablename * @return */ public boolean isTableExits(Object dbobj, String tablename) { // boolean result=true;//表示不存在 SQLiteDatabase db = (SQLiteDatabase) dbobj; try { String str = "select count(*) xcount from " + tablename; db.rawQuery(str, null).close(); } catch (Exception ex) { return false; } finally { closeConnection(db); } return true; } public boolean isTableExits(DBManager edb, SQLiteDatabase db, String tablename) { if (null == edb) return false; try { String str = "select count(*) xcount from " + tablename; db.rawQuery(str, null).close(); } catch (Exception ex) { return false; } return true; } /*** * 关闭 获取SQLite数据库连接 * @return SQLiteDatabase */ public SQLiteDatabase getConnection() { if (!db.isOpen()) { db = getWritableDatabase(); // 读写方式获取SQLiteDatabase } return db; } /*** * 关闭 SQLite数据库连接 * @return */ public void closeConnection(SQLiteDatabase db) { try { if (db != null && db.isOpen()) db.close(); } catch (Exception e) { e.printStackTrace(); } } public void closeConnection() { try { if (db != null && db.isOpen()) db.close(); } catch (Exception e) { e.printStackTrace(); } } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub } @Override public boolean saveAll(Object dbobj, String tableName, List<ContentValues> values) { SQLiteDatabase db = (SQLiteDatabase) dbobj; try { db.beginTransaction(); for (ContentValues value : values) { db.insert(tableName, null, value); } db.setTransactionSuccessful(); db.endTransaction(); } catch (Exception ex) { ex.printStackTrace(); return false; } finally { closeConnection(db); } return true; } }
Java
package com.outsourcing.bottle.db; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import com.outsourcing.bottle.domain.PushNoticeInfo; /** * 推送信息表 * * @author 06peng * */ public class PushNoticeInfoTable { private final String PUSH_NOTICE_TABLE = "push_notice_info"; private final String LOGIN_UID = "login_uid"; private DBManager db = null; public PushNoticeInfoTable() { if (db == null) { db = DBManager.get(); } if (!db.isTableExits(db.getConnection(), PUSH_NOTICE_TABLE)) { createBottleType(); } } public PushNoticeInfoTable(Context context) { if (db == null) { db = DBManager.get(context); } if (!db.isTableExits(db.getConnection(), PUSH_NOTICE_TABLE)) { createBottleType(); } } private void createBottleType() { String createSql = "create table if not exists " + PUSH_NOTICE_TABLE + " (id integer primary key autoincrement," + LOGIN_UID + " integer, new_notice_count integer, message_content varchar, message_avatar varchar," + " new_message_count integer, new_btfeed_count integer, new_exfeed_count integer, new_maybeknow_count integer)"; db.creatTable(db.getConnection(), createSql, PUSH_NOTICE_TABLE); } public void savePushNoticeInfo(PushNoticeInfo pushInfo, int login_uid) { ContentValues values = new ContentValues(); values.put(LOGIN_UID, login_uid); values.put("new_notice_count", pushInfo.getNew_notice_count()); values.put("message_content", pushInfo.getMessage_content()); values.put("message_avatar", pushInfo.getMessage_avatar()); values.put("new_message_count", pushInfo.getNew_message_count()); values.put("new_btfeed_count", pushInfo.getNew_btfeed_count()); values.put("new_exfeed_count", pushInfo.getNew_exfeed_count()); values.put("new_maybeknow_count", pushInfo.getNew_maybeknow_count()); db.save(db.getConnection(), PUSH_NOTICE_TABLE, values); } /** * 根据ID删除 * */ public void deletePushNoticeByLoginUid(int login_uid) { String deleteSql = LOGIN_UID + "=? "; db.delete(db.getConnection(), PUSH_NOTICE_TABLE, deleteSql, new String[] { String.valueOf(login_uid) }); db.closeConnection(db.getConnection()); } public PushNoticeInfo getPushNoticeInfo(int login_uid) { Cursor cursor = null; PushNoticeInfo pushInfo = null; try { cursor = db.find(db.getConnection(), "select * from " + PUSH_NOTICE_TABLE + " where " + LOGIN_UID + "=?", new String[] { String.valueOf(login_uid) }); if (cursor != null) { while (cursor.moveToNext()) { pushInfo = new PushNoticeInfo(); pushInfo.setMessage_avatar(cursor.getString(cursor.getColumnIndex("message_avatar"))); pushInfo.setMessage_content(cursor.getString(cursor.getColumnIndex("message_content"))); pushInfo.setNew_btfeed_count(cursor.getInt(cursor.getColumnIndex("new_btfeed_count"))); pushInfo.setNew_exfeed_count(cursor.getInt(cursor.getColumnIndex("new_exfeed_count"))); pushInfo.setNew_message_count(cursor.getInt(cursor.getColumnIndex("new_message_count"))); pushInfo.setNew_notice_count(cursor.getInt(cursor.getColumnIndex("new_notice_count"))); pushInfo.setNew_maybeknow_count(cursor.getInt(cursor.getColumnIndex("new_maybeknow_count"))); } } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } return pushInfo; } public void clearTable() { db.delete(db.getConnection(), PUSH_NOTICE_TABLE, null, null); } public void updatePushInfo(String type, String value, String login_uid) { try { String sql = "update table "+PUSH_NOTICE_TABLE+" set "+type+" = "+value+" where "+LOGIN_UID+" = ?"; db.update(db.getConnection(), sql, new String[] {login_uid} ); } catch (Exception e) { e.printStackTrace(); } } }
Java
package com.outsourcing.bottle.db; import java.util.Calendar; import java.util.TimeZone; import android.database.Cursor; /** * * @author 06peng * */ public class TimeTable { private static final String TAB_TIME = "timetab";// 表名 private static final String COL_TIME = "first_time";// 时间 private static TimeTable timeDALEx = null; private TimeTable() { } /** * 获取实例 * @return */ public static TimeTable get() { if (null == timeDALEx) { timeDALEx = new TimeTable(); DBManager db = DBManager.get(); db.creatTable(db.getConnection(), "CREATE TABLE IF NOT EXISTS " + TAB_TIME + " (id integer primary key autoincrement, " + COL_TIME + " LONG)"); } return timeDALEx; } /** * 获得时间 * * @param type * @return */ public long getFirstTime() { long downloadlength = 0; try { DBManager db = DBManager.get(); Cursor cursor = db.find(db.getConnection(), "select " + COL_TIME + " from " + TAB_TIME, null); if (null != cursor) { if (cursor.moveToFirst()) downloadlength = cursor.getLong(0); cursor.close(); } } catch (Exception e) { e.printStackTrace(); } return downloadlength; } /** * 保存 * * @param type * @param firstTime * @return */ private boolean save(long firstTime) { DBManager db = DBManager.get(); db.getConnection().beginTransaction(); try { db.getConnection().execSQL("insert into " + TAB_TIME + "(" + COL_TIME + " ) values(?)", new Object[] { firstTime }); db.getConnection().setTransactionSuccessful(); } catch (Exception e) { e.printStackTrace(); return false; } finally { db.getConnection().endTransaction(); db = null; } return true; } /** * 更新 * * @param type * @param firstTime * @return */ private boolean update(long firstTime) { DBManager db = DBManager.get(); db.getConnection().beginTransaction(); try { db.getConnection().execSQL("update " + TAB_TIME + " set " + COL_TIME + "=?", new Object[] { firstTime }); db.getConnection().setTransactionSuccessful(); } catch (Exception e) { e.printStackTrace(); return false; } finally { db.getConnection().endTransaction(); db = null; } return true; } /** * 保存或更新 * * @param type * @param firstTime * @return */ public boolean saveOrUpdate(long firstTime) { DBManager db = DBManager.get(); Cursor cursor = db.find(db.getConnection(), "select * from " + TAB_TIME, null); try { if (null != cursor) { if (cursor.moveToFirst()) { update(firstTime); } else { save(firstTime); } } else return false; } catch (Exception e) { e.printStackTrace(); return false; } finally { cursor.close(); db = null; } return true; } /** * 删除字段 * * @param type */ public boolean delete() { DBManager db = DBManager.get(); return db.delete(db.getConnection(), TAB_TIME, null, null); } /** * 检测是否需更新 * * @param type * @return */ public boolean check() { try { long time = getFirstTime(); TimeZone t = TimeZone.getTimeZone("GMT+08:00");// 获取东8区TimeZone Calendar calendar = Calendar.getInstance(t); calendar.setTimeInMillis(System.currentTimeMillis()); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); int hour = calendar.get(Calendar.HOUR_OF_DAY); if (time > 0 && hour > 4) { Calendar calendar2 = Calendar.getInstance(t); calendar2.setTimeInMillis(time); int year2 = calendar2.get(Calendar.YEAR); int month2 = calendar2.get(Calendar.MONTH); int day2 = calendar2.get(Calendar.DAY_OF_MONTH); if (calendar.compareTo(calendar2) > 0) { if (year == year2 && month == month2 && day == day2) { return false; } saveOrUpdate(calendar.getTimeInMillis()); return true; } } else { saveOrUpdate(calendar.getTimeInMillis()); return true; } } catch (Exception e) { e.printStackTrace(); } return false; } }
Java
package com.outsourcing.bottle.db; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import com.outsourcing.bottle.domain.OtherConfigEntry; /** * * @author 06peng * */ public class OtherConfigTable { private final String TABLE_BOTTLE_OTHER_CONFIG = "bottle_other_config"; private DBManagerImpl db = null; public OtherConfigTable() { if (db == null) { db = DBManager.get(); } if (!db.isTableExits(db.getConnection(), TABLE_BOTTLE_OTHER_CONFIG)) { createBottleNetType(); } } public OtherConfigTable(Context context) { if (db == null) { db = DBManager.get(context); } if (!db.isTableExits(db.getConnection(), TABLE_BOTTLE_OTHER_CONFIG)) { createBottleNetType(); } } private void createBottleNetType() { String createSql = "create table if not exists "+TABLE_BOTTLE_OTHER_CONFIG+" (id integer primary key autoincrement, feedback_uid integer, qq_enable integer, weibo_enable integer," + "tencent_enable integer, renren_enable integer, douban_enable integer, twitter_enable integer, facebook_enable integer, register_enable integer, last_android_version varchar)"; db.creatTable(db.getConnection(), createSql, TABLE_BOTTLE_OTHER_CONFIG); } public void saveBottleOtherConfig(OtherConfigEntry entry) { ContentValues values = new ContentValues(); values.put("feedback_uid", entry.getFeedback_uid()); values.put("qq_enable", entry.getQq_enable()); values.put("weibo_enable", entry.getWeibo_enable()); values.put("tencent_enable", entry.getTencent_enable()); values.put("renren_enable", entry.getRenren_enable()); values.put("douban_enable", entry.getDouban_enable()); values.put("twitter_enable", entry.getTwitter_enable()); values.put("facebook_enable", entry.getFacebook_enable()); values.put("register_enable", entry.getRegister_enable()); values.put("last_android_version", entry.getLast_android_version()); db.save(db.getConnection(), TABLE_BOTTLE_OTHER_CONFIG, values); } public OtherConfigEntry getBottleOtherConfig() { Cursor cursor = null; OtherConfigEntry entry = null; try { cursor = db.find(db.getConnection(), "select * from " + TABLE_BOTTLE_OTHER_CONFIG, null); if (cursor != null) { while (cursor.moveToNext()) { entry = new OtherConfigEntry(); entry.setFeedback_uid(cursor.getInt(cursor.getColumnIndex("feedback_uid"))); entry.setDouban_enable(cursor.getInt(cursor.getColumnIndex("douban_enable"))); entry.setFacebook_enable(cursor.getInt(cursor.getColumnIndex("facebook_enable"))); entry.setQq_enable(cursor.getInt(cursor.getColumnIndex("qq_enable"))); entry.setRenren_enable(cursor.getInt(cursor.getColumnIndex("renren_enable"))); entry.setTencent_enable(cursor.getInt(cursor.getColumnIndex("tencent_enable"))); entry.setTwitter_enable(cursor.getInt(cursor.getColumnIndex("twitter_enable"))); entry.setWeibo_enable(cursor.getInt(cursor.getColumnIndex("weibo_enable"))); entry.setRegister_enable(cursor.getInt(cursor.getColumnIndex("register_enable"))); entry.setLast_android_version(cursor.getString(cursor.getColumnIndex("last_android_version"))); } } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } return entry; } public void clearTable() { db.delete(db.getConnection(), TABLE_BOTTLE_OTHER_CONFIG, null, null); } }
Java
package com.outsourcing.bottle.db; import java.util.List; import android.content.ContentValues; import android.database.Cursor; /** * * @author 06peng * */ public interface DBManagerImpl { public boolean save(Object db, String tableName, ContentValues values); public boolean update(Object db, String table, ContentValues values, String whereClause, String[] whereArgs); public boolean deleteTable(Object dbobj, String tableName); public boolean delete(Object db, String table, String deleteSql, String obj[]); public Cursor find(Object db, String findSql, String obj[]); public boolean execSQL(Object db, String sql); public boolean creatTable(Object db, String createTableSql, String tablename); public void closeConnection(); public Object getConnection(); public boolean isTableExits(Object dbobj, String tablename); public boolean saveAll(Object db, String tableName, List<ContentValues> values); }
Java
package com.outsourcing.bottle.db; import java.util.ArrayList; import android.content.ContentValues; import android.database.Cursor; import com.outsourcing.bottle.domain.FriendLevelEntry; /** * 瓶友等级表 * @author 06peng * */ public class FriendLevelTable { private final String TABLE_FRIENDLEVEL = "friend_level"; private DBManagerImpl db = null; public FriendLevelTable() { if (db == null) { db = DBManager.get(); } if (!db.isTableExits(db.getConnection(), TABLE_FRIENDLEVEL)) { createFriendLevel(); } } private void createFriendLevel() { String createSql = "create table if not exists " + TABLE_FRIENDLEVEL + " (id integer primary key autoincrement, flevel_id integer, flevel_name_cn varchar, " + "flevel_name_en varchar, flevel_level integer, flevel_credit integer, flevel_ttcredit integer, " + "flevel_cron varchar)"; db.creatTable(db.getConnection(), createSql, TABLE_FRIENDLEVEL); } public ArrayList<FriendLevelEntry> getFriendLevels() { Cursor cursor = null; ArrayList<FriendLevelEntry> friendLevels = null; try { cursor = db.find(db.getConnection(), "select * from " + TABLE_FRIENDLEVEL, null); if (cursor != null) { friendLevels = new ArrayList<FriendLevelEntry>(); while (cursor.moveToNext()) { FriendLevelEntry friendLevel = new FriendLevelEntry(); friendLevel.setFlevel_id(cursor.getInt(cursor.getColumnIndex("flevel_id"))); friendLevel.setFlevel_level(cursor.getInt(cursor.getColumnIndex("flevel_level"))); friendLevel.setFlevel_credit(cursor.getInt(cursor.getColumnIndex("flevel_credit"))); friendLevel.setFlevel_ttcredit(cursor.getInt(cursor.getColumnIndex("flevel_ttcredit"))); friendLevel.setFlevel_cron(cursor.getString(cursor.getColumnIndex("flevel_cron"))); friendLevel.setFlevel_name_cn(cursor.getString(cursor.getColumnIndex("flevel_name_cn"))); friendLevel.setFlevel_name_en(cursor.getString(cursor.getColumnIndex("flevel_name_en"))); friendLevels.add(friendLevel); } } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } return friendLevels; } public void saveFriendLevel(FriendLevelEntry friendLevel) { ContentValues values = new ContentValues(); values.put("flevel_id", friendLevel.getFlevel_id()); values.put("flevel_name_cn", friendLevel.getFlevel_name_cn()); values.put("flevel_name_en", friendLevel.getFlevel_name_en()); values.put("flevel_level", friendLevel.getFlevel_level()); values.put("flevel_credit", friendLevel.getFlevel_credit()); values.put("flevel_ttcredit", friendLevel.getFlevel_ttcredit()); values.put("flevel_cron", friendLevel.getFlevel_cron()); db.save(db.getConnection(), TABLE_FRIENDLEVEL, values); } public void clearTable() { db.delete(db.getConnection(), TABLE_FRIENDLEVEL, null, null); } }
Java
package com.outsourcing.bottle.db; import java.util.ArrayList; import android.content.ContentValues; import android.database.Cursor; import com.outsourcing.bottle.domain.BottleNetTypeEntry; /** * 捞网类型表 * @author 06peng * */ public class BottleNetTypeTable { private final String TABLE_BOTTLE_NET_TYPE = "bottle_net_type"; private DBManagerImpl db = null; public BottleNetTypeTable() { if (db == null) { db = DBManager.get(); } if (!db.isTableExits(db.getConnection(), TABLE_BOTTLE_NET_TYPE)) { createBottleNetType(); } } private void createBottleNetType() { String createSql = "create table if not exists "+TABLE_BOTTLE_NET_TYPE+" (id integer primary key autoincrement, nettypeid integer, nettype_name_cn varchar, nettype_name_en varchar, nettype_desc_cn varchar," + "nettype_desc_en varchar, nettype_sjwicon varchar, nettype_isshow integer, nettype_location_select integer)"; db.creatTable(db.getConnection(), createSql, TABLE_BOTTLE_NET_TYPE); } public ArrayList<BottleNetTypeEntry> getBottleNetTypes() { Cursor cursor = null; ArrayList<BottleNetTypeEntry> bottleNetTypes = null; try { cursor = db.find(db.getConnection(), "select * from " + TABLE_BOTTLE_NET_TYPE + " where nettype_isshow = 1", null); if (cursor != null) { bottleNetTypes = new ArrayList<BottleNetTypeEntry>(); while (cursor.moveToNext()) { BottleNetTypeEntry bottleNetType = new BottleNetTypeEntry(); bottleNetType.setNettypeid(cursor.getInt(cursor.getColumnIndex("nettypeid"))); bottleNetType.setNettype_name_cn(cursor.getString(cursor.getColumnIndex("nettype_name_cn"))); bottleNetType.setNettype_name_en(cursor.getString(cursor.getColumnIndex("nettype_name_en"))); bottleNetType.setNettype_desc_cn(cursor.getString(cursor.getColumnIndex("nettype_desc_cn"))); bottleNetType.setNettype_desc_en(cursor.getString(cursor.getColumnIndex("nettype_desc_en"))); bottleNetType.setNettype_sjwicon(cursor.getString(cursor.getColumnIndex("nettype_sjwicon"))); bottleNetType.setNettype_isshow(cursor.getInt(cursor.getColumnIndex("nettype_isshow"))); bottleNetType.setNettype_location_select(cursor.getInt(cursor.getColumnIndex("nettype_location_select"))); bottleNetTypes.add(bottleNetType); } } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } return bottleNetTypes; } public void saveBottleNetType(BottleNetTypeEntry bottleNetType) { ContentValues values = new ContentValues(); values.put("nettypeid", bottleNetType.getNettypeid()); values.put("nettype_name_cn", bottleNetType.getNettype_name_cn()); values.put("nettype_name_en", bottleNetType.getNettype_name_en()); values.put("nettype_desc_cn", bottleNetType.getNettype_desc_cn()); values.put("nettype_desc_en", bottleNetType.getNettype_desc_en()); values.put("nettype_sjwicon", bottleNetType.getNettype_sjwicon()); values.put("nettype_isshow", bottleNetType.getNettype_isshow()); values.put("nettype_location_select", bottleNetType.getNettype_location_select()); db.save(db.getConnection(), TABLE_BOTTLE_NET_TYPE, values); } public BottleNetTypeEntry getBottleNetType(int bottleId) { Cursor cursor = null; BottleNetTypeEntry bottleNetType = null; try { cursor = db.find(db.getConnection(), "select * from " + TABLE_BOTTLE_NET_TYPE + " where nettypeid=?", new String[] { String.valueOf(bottleId) }); if (cursor != null) { while (cursor.moveToNext()) { bottleNetType = new BottleNetTypeEntry(); bottleNetType.setNettypeid(cursor.getInt(cursor.getColumnIndex("nettypeid"))); bottleNetType.setNettype_name_cn(cursor.getString(cursor.getColumnIndex("nettype_name_cn"))); bottleNetType.setNettype_name_en(cursor.getString(cursor.getColumnIndex("nettype_name_en"))); bottleNetType.setNettype_desc_cn(cursor.getString(cursor.getColumnIndex("nettype_desc_cn"))); bottleNetType.setNettype_desc_en(cursor.getString(cursor.getColumnIndex("nettype_desc_en"))); bottleNetType.setNettype_sjwicon(cursor.getString(cursor.getColumnIndex("nettype_sjwicon"))); bottleNetType.setNettype_isshow(cursor.getInt(cursor.getColumnIndex("nettype_isshow"))); bottleNetType.setNettype_location_select(cursor.getInt(cursor.getColumnIndex("nettype_location_select"))); } } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } return bottleNetType; } public void clearTalbe() { db.delete(db.getConnection(), TABLE_BOTTLE_NET_TYPE, null, null); } }
Java
package com.outsourcing.bottle.db; import java.util.ArrayList; import android.content.ContentValues; import android.database.Cursor; import com.outsourcing.bottle.domain.StickEntry; /** * 贴纸详情 * @author ting * */ public class StickersTable { private final String TABLE_STICK_LIST = "stick_list"; private static final String DIR_ID = "pasterdir_id"; private static final String PASTER_ID = "paster_id"; private static final String PASTER_URL= "paster_url"; private DBManagerImpl db = null; public StickersTable() { if (db == null) { db = DBManager.get(); } if (!db.isTableExits(db.getConnection(), TABLE_STICK_LIST)) { createStickers(); } } private void createStickers() { String createSql = "create table if not exists "+TABLE_STICK_LIST+" (id integer primary key autoincrement, "+DIR_ID+" integer, "+PASTER_ID+" integer,"+PASTER_URL+" varchar)"; db.creatTable(db.getConnection(), createSql, TABLE_STICK_LIST); } public ArrayList<StickEntry> getStickList(int dirId) { Cursor cursor = null; ArrayList<StickEntry> stickList = null; try { cursor = db.find(db.getConnection(), "select * from " + TABLE_STICK_LIST +" where "+DIR_ID+"=?", new String[] { String.valueOf(dirId)}); if (cursor != null) { stickList = new ArrayList<StickEntry>(); while (cursor.moveToNext()) { StickEntry stickEntry = new StickEntry(); stickEntry.setPaster_id(cursor.getInt(cursor.getColumnIndex(PASTER_ID))); stickEntry.setPaster_url(cursor.getString(cursor.getColumnIndex(PASTER_URL))); stickList.add(stickEntry); } } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } return stickList; } public void saveStickList(int dirId,StickEntry stickEntry) { ContentValues values = new ContentValues(); values.put(DIR_ID, dirId); values.put(PASTER_ID, stickEntry.getPaster_id()); values.put(PASTER_URL, stickEntry.getPaster_url()); db.save(db.getConnection(), TABLE_STICK_LIST, values); } public void clearTalbe() { db.delete(db.getConnection(), TABLE_STICK_LIST, null, null); } }
Java
package com.outsourcing.bottle.db; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import com.outsourcing.bottle.domain.BottleTypeEntry; /** * 瓶子类型表 * @author 06peng * */ public class BottleTypeTable { private final String TABLE_BOTTLE_TYPE = "bottle_type"; private DBManagerImpl db = null; public BottleTypeTable() { if (db == null) { db = DBManager.get(); } if (!db.isTableExits(db.getConnection(), TABLE_BOTTLE_TYPE)) { createBottleType(); } } public BottleTypeTable(Context context) { if (db == null) { db = DBManager.get(context); } if (!db.isTableExits(db.getConnection(), TABLE_BOTTLE_TYPE)) { createBottleType(); } } private void createBottleType() { String createSql = "create table if not exists "+TABLE_BOTTLE_TYPE+" (id integer primary key autoincrement,bttypeid integer, bttype_name_cn varchar, bttype_name_en varchar," + "bttype_desc_cn varchar, bttype_desc_en varchar, bttype_tips_cn varchar, bttype_tips_en varchar, bttype_sjdicon varchar," + "bttype_sjwicon varchar, bttype_samecity integer, bttype_samecity_show integer, bttype_samearea integer, bttype_samearea_show integer," + "bttype_needsex integer, bttype_needsex_show integer, bttype_needage integer, bttype_needage_show integer, bttype_allow_sendfriend integer, bttype_allow_pick integer," + "bttype_pick_show integer, bttype_allow_spread integer, bttype_spread_show integer, bttype_message_show integer, bttype_message_must integer, bttype_pic_show integer," + "bttype_pic_must integer, bttype_doing_show integer, bttype_doing_must integer, bttype_poll_show integer, bttype_poll_must integer, bttype_otheruserfeed integer, bttype_otheruserfeed_show integer," + "bttype_otheruserreply integer, bttype_otheruserreply_show integer, bttype_isshow integer, bttype_location_select integer)"; db.creatTable(db.getConnection(), createSql, TABLE_BOTTLE_TYPE); } public ArrayList<BottleTypeEntry> getBottleTypes() { Cursor cursor = null; ArrayList<BottleTypeEntry> bottleTypes = null; try { cursor = db.find(db.getConnection(), "select * from " + TABLE_BOTTLE_TYPE + " where bttype_isshow = 1", null); if (cursor != null) { bottleTypes = new ArrayList<BottleTypeEntry>(); while (cursor.moveToNext()) { BottleTypeEntry bottleType = new BottleTypeEntry(); bottleType.setBttypeid(cursor.getInt(cursor.getColumnIndex("bttypeid"))); bottleType.setBttype_name_cn(cursor.getString(cursor.getColumnIndex("bttype_name_cn"))); bottleType.setBttype_name_en(cursor.getString(cursor.getColumnIndex("bttype_name_en"))); bottleType.setBttype_desc_cn(cursor.getString(cursor.getColumnIndex("bttype_desc_cn"))); bottleType.setBttype_desc_en(cursor.getString(cursor.getColumnIndex("bttype_desc_en"))); bottleType.setBttype_tips_cn(cursor.getString(cursor.getColumnIndex("bttype_tips_cn"))); bottleType.setBttype_tips_en(cursor.getString(cursor.getColumnIndex("bttype_tips_en"))); bottleType.setBttype_sjdicon(cursor.getString(cursor.getColumnIndex("bttype_sjdicon"))); bottleType.setBttype_sjwicon(cursor.getString(cursor.getColumnIndex("bttype_sjwicon"))); bottleType.setBttype_samecity(cursor.getInt(cursor.getColumnIndex("bttype_samecity"))); bottleType.setBttype_samecity_show(cursor.getInt(cursor.getColumnIndex("bttype_samecity_show"))); bottleType.setBttype_samearea(cursor.getInt(cursor.getColumnIndex("bttype_samearea"))); bottleType.setBttype_samearea_show(cursor.getInt(cursor.getColumnIndex("bttype_samearea_show"))); bottleType.setBttype_needsex(cursor.getInt(cursor.getColumnIndex("bttype_needsex"))); bottleType.setBttype_needsex_show(cursor.getInt(cursor.getColumnIndex("bttype_needsex_show"))); bottleType.setBttype_needage(cursor.getInt(cursor.getColumnIndex("bttype_needage"))); bottleType.setBttype_needage_show(cursor.getInt(cursor.getColumnIndex("bttype_needage_show"))); bottleType.setBttype_allow_sendfriend(cursor.getInt(cursor.getColumnIndex("bttype_allow_sendfriend"))); bottleType.setBttype_allow_pick(cursor.getInt(cursor.getColumnIndex("bttype_allow_pick"))); bottleType.setBttype_pick_show(cursor.getInt(cursor.getColumnIndex("bttype_pick_show"))); bottleType.setBttype_allow_spread(cursor.getInt(cursor.getColumnIndex("bttype_allow_spread"))); bottleType.setBttype_spread_show(cursor.getInt(cursor.getColumnIndex("bttype_spread_show"))); bottleType.setBttype_message_show(cursor.getInt(cursor.getColumnIndex("bttype_message_show"))); bottleType.setBttype_message_must(cursor.getInt(cursor.getColumnIndex("bttype_message_must"))); bottleType.setBttype_pic_show(cursor.getInt(cursor.getColumnIndex("bttype_pic_show"))); bottleType.setBttype_pic_must(cursor.getInt(cursor.getColumnIndex("bttype_pic_must"))); bottleType.setBttype_doing_show(cursor.getInt(cursor.getColumnIndex("bttype_doing_show"))); bottleType.setBttype_doing_must(cursor.getInt(cursor.getColumnIndex("bttype_doing_must"))); bottleType.setBttype_poll_show(cursor.getInt(cursor.getColumnIndex("bttype_poll_show"))); bottleType.setBttype_poll_must(cursor.getInt(cursor.getColumnIndex("bttype_poll_must"))); bottleType.setBttype_otheruserfeed(cursor.getInt(cursor.getColumnIndex("bttype_otheruserfeed"))); bottleType.setBttype_otheruserfeed_show(cursor.getInt(cursor.getColumnIndex("bttype_otheruserfeed_show"))); bottleType.setBttype_otheruserreply(cursor.getInt(cursor.getColumnIndex("bttype_otheruserreply"))); bottleType.setBttype_otheruserreply_show(cursor.getInt(cursor.getColumnIndex("bttype_otheruserreply_show"))); bottleType.setBttype_isshow(cursor.getInt(cursor.getColumnIndex("bttype_isshow"))); bottleType.setBttype_location_select(cursor.getInt(cursor.getColumnIndex("bttype_location_select"))); bottleTypes.add(bottleType); } } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } return bottleTypes; } public void saveBottleType(BottleTypeEntry bottleType) { ContentValues values = new ContentValues(); values.put("bttypeid", bottleType.getBttypeid()); values.put("bttype_name_cn", bottleType.getBttype_name_cn()); values.put("bttype_name_en", bottleType.getBttype_name_en()); values.put("bttype_desc_cn", bottleType.getBttype_desc_cn()); values.put("bttype_desc_en", bottleType.getBttype_desc_en()); values.put("bttype_tips_cn", bottleType.getBttype_tips_cn()); values.put("bttype_tips_en", bottleType.getBttype_tips_en()); values.put("bttype_sjdicon", bottleType.getBttype_sjdicon()); values.put("bttype_sjwicon", bottleType.getBttype_sjwicon()); values.put("bttype_samecity", bottleType.getBttype_samecity()); values.put("bttype_samecity_show", bottleType.getBttype_samecity_show()); values.put("bttype_samearea", bottleType.getBttype_samearea()); values.put("bttype_samearea_show", bottleType.getBttype_samearea_show()); values.put("bttype_needsex", bottleType.getBttype_needsex()); values.put("bttype_needsex_show", bottleType.getBttype_needsex_show()); values.put("bttype_needage", bottleType.getBttype_needage()); values.put("bttype_needage_show", bottleType.getBttype_needage_show()); values.put("bttype_allow_sendfriend", bottleType.getBttype_allow_sendfriend()); values.put("bttype_allow_pick", bottleType.getBttype_allow_pick()); values.put("bttype_pick_show", bottleType.getBttype_pick_show()); values.put("bttype_allow_spread", bottleType.getBttype_allow_spread()); values.put("bttype_spread_show", bottleType.getBttype_spread_show()); values.put("bttype_message_show", bottleType.getBttype_message_show()); values.put("bttype_message_must", bottleType.getBttype_message_must()); values.put("bttype_pic_show", bottleType.getBttype_pic_show()); values.put("bttype_pic_must", bottleType.getBttype_pic_must()); values.put("bttype_doing_show", bottleType.getBttype_doing_show()); values.put("bttype_doing_must", bottleType.getBttype_doing_must()); values.put("bttype_poll_show", bottleType.getBttype_poll_show()); values.put("bttype_poll_must", bottleType.getBttype_poll_must()); values.put("bttype_otheruserfeed", bottleType.getBttype_otheruserfeed()); values.put("bttype_otheruserfeed_show", bottleType.getBttype_otheruserfeed_show()); values.put("bttype_otheruserreply", bottleType.getBttype_otheruserreply()); values.put("bttype_otheruserreply_show", bottleType.getBttype_otheruserreply_show()); values.put("bttype_isshow", bottleType.getBttype_isshow()); values.put("bttype_location_select", bottleType.getBttype_location_select()); db.save(db.getConnection(), TABLE_BOTTLE_TYPE, values); } public void saveBottleType(List<BottleTypeEntry> bottleTypes) { List<ContentValues> valueList = new ArrayList<ContentValues>(); for(BottleTypeEntry bottleType : bottleTypes) { ContentValues values = new ContentValues(); values.put("bttypeid", bottleType.getBttypeid()); values.put("bttype_name_cn", bottleType.getBttype_name_cn()); values.put("bttype_name_en", bottleType.getBttype_name_en()); values.put("bttype_desc_cn", bottleType.getBttype_desc_cn()); values.put("bttype_desc_en", bottleType.getBttype_desc_en()); values.put("bttype_tips_cn", bottleType.getBttype_tips_cn()); values.put("bttype_tips_en", bottleType.getBttype_tips_en()); values.put("bttype_sjdicon", bottleType.getBttype_sjdicon()); values.put("bttype_sjwicon", bottleType.getBttype_sjwicon()); values.put("bttype_samecity", bottleType.getBttype_samecity()); values.put("bttype_samecity_show", bottleType.getBttype_samecity_show()); values.put("bttype_samearea", bottleType.getBttype_samearea()); values.put("bttype_samearea_show", bottleType.getBttype_samearea_show()); values.put("bttype_needsex", bottleType.getBttype_needsex()); values.put("bttype_needsex_show", bottleType.getBttype_needsex_show()); values.put("bttype_needage", bottleType.getBttype_needage()); values.put("bttype_needage_show", bottleType.getBttype_needage_show()); values.put("bttype_allow_sendfriend", bottleType.getBttype_allow_sendfriend()); values.put("bttype_allow_pick", bottleType.getBttype_allow_pick()); values.put("bttype_pick_show", bottleType.getBttype_pick_show()); values.put("bttype_allow_spread", bottleType.getBttype_allow_spread()); values.put("bttype_spread_show", bottleType.getBttype_spread_show()); values.put("bttype_message_show", bottleType.getBttype_message_show()); values.put("bttype_message_must", bottleType.getBttype_message_must()); values.put("bttype_pic_show", bottleType.getBttype_pic_show()); values.put("bttype_pic_must", bottleType.getBttype_pic_must()); values.put("bttype_doing_show", bottleType.getBttype_doing_show()); values.put("bttype_doing_must", bottleType.getBttype_doing_must()); values.put("bttype_poll_show", bottleType.getBttype_poll_show()); values.put("bttype_poll_must", bottleType.getBttype_poll_must()); values.put("bttype_otheruserfeed", bottleType.getBttype_otheruserfeed()); values.put("bttype_otheruserfeed_show", bottleType.getBttype_otheruserfeed_show()); values.put("bttype_otheruserreply", bottleType.getBttype_otheruserreply()); values.put("bttype_otheruserreply_show", bottleType.getBttype_otheruserreply_show()); values.put("bttype_isshow", bottleType.getBttype_isshow()); values.put("bttype_location_select", bottleType.getBttype_location_select()); valueList.add(values); } db.saveAll(db.getConnection(), TABLE_BOTTLE_TYPE, valueList); } public BottleTypeEntry getBottleType(int bottleId) { Cursor cursor = null; BottleTypeEntry bottleType = null; try { cursor = db.find(db.getConnection(), "select * from " + TABLE_BOTTLE_TYPE + " where bttypeid=?", new String[] { String.valueOf(bottleId) }); if (cursor != null) { while (cursor.moveToNext()) { bottleType = new BottleTypeEntry(); bottleType.setBttypeid(cursor.getInt(cursor.getColumnIndex("bttypeid"))); bottleType.setBttype_name_cn(cursor.getString(cursor.getColumnIndex("bttype_name_cn"))); bottleType.setBttype_name_en(cursor.getString(cursor.getColumnIndex("bttype_name_en"))); bottleType.setBttype_desc_cn(cursor.getString(cursor.getColumnIndex("bttype_desc_cn"))); bottleType.setBttype_desc_en(cursor.getString(cursor.getColumnIndex("bttype_desc_en"))); bottleType.setBttype_tips_cn(cursor.getString(cursor.getColumnIndex("bttype_tips_cn"))); bottleType.setBttype_tips_en(cursor.getString(cursor.getColumnIndex("bttype_tips_en"))); bottleType.setBttype_sjdicon(cursor.getString(cursor.getColumnIndex("bttype_sjdicon"))); bottleType.setBttype_sjwicon(cursor.getString(cursor.getColumnIndex("bttype_sjwicon"))); bottleType.setBttype_samecity(cursor.getInt(cursor.getColumnIndex("bttype_samecity"))); bottleType.setBttype_samecity_show(cursor.getInt(cursor.getColumnIndex("bttype_samecity_show"))); bottleType.setBttype_samearea(cursor.getInt(cursor.getColumnIndex("bttype_samearea"))); bottleType.setBttype_samearea_show(cursor.getInt(cursor.getColumnIndex("bttype_samearea_show"))); bottleType.setBttype_needsex(cursor.getInt(cursor.getColumnIndex("bttype_needsex"))); bottleType.setBttype_needsex_show(cursor.getInt(cursor.getColumnIndex("bttype_needsex_show"))); bottleType.setBttype_needage(cursor.getInt(cursor.getColumnIndex("bttype_needage"))); bottleType.setBttype_needage_show(cursor.getInt(cursor.getColumnIndex("bttype_needage_show"))); bottleType.setBttype_allow_sendfriend(cursor.getInt(cursor.getColumnIndex("bttype_allow_sendfriend"))); bottleType.setBttype_allow_pick(cursor.getInt(cursor.getColumnIndex("bttype_allow_pick"))); bottleType.setBttype_pick_show(cursor.getInt(cursor.getColumnIndex("bttype_pick_show"))); bottleType.setBttype_allow_spread(cursor.getInt(cursor.getColumnIndex("bttype_allow_spread"))); bottleType.setBttype_spread_show(cursor.getInt(cursor.getColumnIndex("bttype_spread_show"))); bottleType.setBttype_message_show(cursor.getInt(cursor.getColumnIndex("bttype_message_show"))); bottleType.setBttype_message_must(cursor.getInt(cursor.getColumnIndex("bttype_message_must"))); bottleType.setBttype_pic_show(cursor.getInt(cursor.getColumnIndex("bttype_pic_show"))); bottleType.setBttype_pic_must(cursor.getInt(cursor.getColumnIndex("bttype_pic_must"))); bottleType.setBttype_doing_show(cursor.getInt(cursor.getColumnIndex("bttype_doing_show"))); bottleType.setBttype_doing_must(cursor.getInt(cursor.getColumnIndex("bttype_doing_must"))); bottleType.setBttype_poll_show(cursor.getInt(cursor.getColumnIndex("bttype_poll_show"))); bottleType.setBttype_poll_must(cursor.getInt(cursor.getColumnIndex("bttype_poll_must"))); bottleType.setBttype_otheruserfeed(cursor.getInt(cursor.getColumnIndex("bttype_otheruserfeed"))); bottleType.setBttype_otheruserfeed_show(cursor.getInt(cursor.getColumnIndex("bttype_otheruserfeed_show"))); bottleType.setBttype_otheruserreply(cursor.getInt(cursor.getColumnIndex("bttype_otheruserreply"))); bottleType.setBttype_otheruserreply_show(cursor.getInt(cursor.getColumnIndex("bttype_otheruserreply_show"))); bottleType.setBttype_isshow(cursor.getInt(cursor.getColumnIndex("bttype_isshow"))); bottleType.setBttype_location_select(cursor.getInt(cursor.getColumnIndex("bttype_location_select"))); } } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } return bottleType; } public void clearTable() { db.delete(db.getConnection(), TABLE_BOTTLE_TYPE, null, null); } }
Java
package com.outsourcing.bottle.db; import java.util.ArrayList; import android.content.ContentValues; import android.database.Cursor; import com.outsourcing.bottle.domain.PasterDirConfigEntry; import com.outsourcing.bottle.util.AppContext; /** * 贴纸目录 * @author ting * */ public class StickersPackTable { private final String TABLE_STICK_DIR = "stick_dir"; private DBManager db = null; public StickersPackTable() { if (db == null) { db = DBManager.get(); } if (!db.isTableExits(db.getConnection(), TABLE_STICK_DIR)) { createStickersPack(); } } private void createStickersPack() { String createSql = "create table if not exists "+TABLE_STICK_DIR+" (id integer primary key autoincrement,login_uid integer, pasterdir_id integer, pasterdir_name_cn varchar, pasterdir_name_en varchar, pasterdir_coverurl varchar,credit integer,ttcredit integer,btf_level integer,useterm varchar,unlocked integer)"; db.creatTable(db.getConnection(), createSql, TABLE_STICK_DIR); } public ArrayList<PasterDirConfigEntry> getStickDir() { Cursor cursor = null; ArrayList<PasterDirConfigEntry> stickDirConfigEntries = null; try { cursor = db.find(db.getConnection(), "select * from " + TABLE_STICK_DIR +" where login_uid =?", new String[]{AppContext.getInstance().getLogin_uid()+""}); if (cursor != null) { stickDirConfigEntries = new ArrayList<PasterDirConfigEntry>(); while (cursor.moveToNext()) { PasterDirConfigEntry stickDirConfigEntry = new PasterDirConfigEntry(); stickDirConfigEntry.setPasterdir_id(cursor.getInt(cursor.getColumnIndex("pasterdir_id"))); stickDirConfigEntry.setPasterdir_name_cn(cursor.getString(cursor.getColumnIndex("pasterdir_name_cn"))); stickDirConfigEntry.setPasterdir_name_en(cursor.getString(cursor.getColumnIndex("pasterdir_name_en"))); stickDirConfigEntry.setPasterdir_coverurl(cursor.getString(cursor.getColumnIndex("pasterdir_coverurl"))); stickDirConfigEntry.setCredit(cursor.getInt(cursor.getColumnIndex("credit"))); stickDirConfigEntry.setTtcredit(cursor.getInt(cursor.getColumnIndex("ttcredit"))); stickDirConfigEntry.setBtf_level(cursor.getInt(cursor.getColumnIndex("btf_level"))); stickDirConfigEntry.setUseterm(cursor.getString(cursor.getColumnIndex("useterm"))); stickDirConfigEntry.setUnlocked(cursor.getInt(cursor.getColumnIndex("unlocked"))); stickDirConfigEntries.add(stickDirConfigEntry); } } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } return stickDirConfigEntries; } public void upStickDirlocked(int pasterdir_id){ // try { // String sql = "update table "+TABLE_STICK_DIR+" set unlocked=? where pasterdir_id=?"; // db.update(db.getConnection(), sql, new String[] {String.valueOf(1),String.valueOf(pasterdir_id)} ); // } catch (Exception e) { // e.printStackTrace(); // } db.getConnection().beginTransaction(); try{ db.getConnection().execSQL("update "+TABLE_STICK_DIR+" set unlocked=? where pasterdir_id=? and login_uid=?", new Object[]{1,pasterdir_id,AppContext.getInstance().getLogin_uid()}); db.getConnection().setTransactionSuccessful(); }catch (Exception e) { e.printStackTrace(); }finally{ db.getConnection().endTransaction(); } } public void saveStickDir(PasterDirConfigEntry stickDirConfigEntry) { ContentValues values = new ContentValues(); values.put("login_uid", AppContext.getInstance().getLogin_uid()); values.put("pasterdir_id", stickDirConfigEntry.getPasterdir_id()); values.put("pasterdir_name_cn", stickDirConfigEntry.getPasterdir_name_cn()); values.put("pasterdir_name_en", stickDirConfigEntry.getPasterdir_name_en()); values.put("pasterdir_coverurl", stickDirConfigEntry.getPasterdir_coverurl()); values.put("credit", stickDirConfigEntry.getCredit()); values.put("ttcredit", stickDirConfigEntry.getTtcredit()); values.put("btf_level", stickDirConfigEntry.getBtf_level()); values.put("useterm", stickDirConfigEntry.getUseterm()); values.put("unlocked", stickDirConfigEntry.getUnlocked()); db.save(db.getConnection(), TABLE_STICK_DIR, values); } public void clearTalbe() { db.delete(db.getConnection(), TABLE_STICK_DIR, null, null); } }
Java
package com.outsourcing.bottle.db; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import com.outsourcing.bottle.domain.LoginUserInfoEntry; /** * 瓶子类型表 * * @author 06peng * */ public class LoginUserInfoTable { private final String TABLE_BOTTLE_TYPE = "loginuser_info"; private final String LOGIN_UID = "login_uid"; private DBManager db = null; public LoginUserInfoTable() { if (db == null) { db = DBManager.get(); } if (!db.isTableExits(db.getConnection(), TABLE_BOTTLE_TYPE)) { createBottleType(); } } public LoginUserInfoTable(Context context) { if (db == null) { db = DBManager.get(context); } if (!db.isTableExits(db.getConnection(), TABLE_BOTTLE_TYPE)) { createBottleType(); } } private void createBottleType() { String createSql = "create table if not exists " + TABLE_BOTTLE_TYPE + " (id integer primary key autoincrement," + LOGIN_UID + " integer, basicinfo_fullfill integer, basicinfo_tip varchar, avatar varchar," + "nickname varchar, doing varchar, facebookok integer, twitterok integer, qqok integer," + "sinaok integer, tqqok integer, renrenok integer, doubanok integer)"; db.creatTable(db.getConnection(), createSql, TABLE_BOTTLE_TYPE); } public void saveLoginUserInfo(LoginUserInfoEntry loginUserInfo, int login_uid) { ContentValues values = new ContentValues(); values.put(LOGIN_UID, login_uid); values.put("basicinfo_fullfill", loginUserInfo.getBasicinfo_fullfill()); values.put("basicinfo_tip", loginUserInfo.getBasicinfo_tip()); values.put("avatar", loginUserInfo.getAvatar()); values.put("nickname", loginUserInfo.getNickname()); values.put("doing", loginUserInfo.getDoing()); values.put("facebookok", loginUserInfo.getFacebookok()); values.put("twitterok", loginUserInfo.getTwitterok()); values.put("qqok", loginUserInfo.getQqok()); values.put("sinaok", loginUserInfo.getSinaok()); values.put("tqqok", loginUserInfo.getTqqok()); values.put("renrenok", loginUserInfo.getRenrenok()); values.put("doubanok", loginUserInfo.getDoubanok()); db.save(db.getConnection(), TABLE_BOTTLE_TYPE, values); } /** * 根据ID删除 * */ public void deleteLoginUserInfoById(int login_uid) { String deleteSql = LOGIN_UID + "=? "; db.delete(db.getConnection(), TABLE_BOTTLE_TYPE, deleteSql, new String[] { String.valueOf(login_uid) }); db.closeConnection(db.getConnection()); } public LoginUserInfoEntry getLoginUserInfo(int login_uid) { Cursor cursor = null; LoginUserInfoEntry loginUserInfo = null; try { cursor = db.find(db.getConnection(), "select * from " + TABLE_BOTTLE_TYPE + " where " + LOGIN_UID + "=?", new String[] { String.valueOf(login_uid) }); if (cursor != null) { while (cursor.moveToNext()) { loginUserInfo = new LoginUserInfoEntry(); loginUserInfo.setBasicinfo_fullfill(cursor.getInt(cursor .getColumnIndex("basicinfo_fullfill"))); loginUserInfo.setBasicinfo_tip((cursor.getString(cursor .getColumnIndex("basicinfo_tip")))); loginUserInfo.setAvatar((cursor.getString(cursor .getColumnIndex("avatar")))); loginUserInfo.setNickname((cursor.getString(cursor .getColumnIndex("nickname")))); loginUserInfo.setDoing((cursor.getString(cursor .getColumnIndex("doing")))); loginUserInfo.setFacebookok((cursor.getInt(cursor .getColumnIndex("facebookok")))); loginUserInfo.setTwitterok((cursor.getInt(cursor .getColumnIndex("twitterok")))); loginUserInfo.setQqok((cursor.getInt(cursor .getColumnIndex("qqok")))); loginUserInfo.setSinaok((cursor.getInt(cursor .getColumnIndex("sinaok")))); loginUserInfo.setTqqok((cursor.getInt(cursor .getColumnIndex("tqqok")))); loginUserInfo.setRenrenok((cursor.getInt(cursor .getColumnIndex("renrenok")))); loginUserInfo.setDoubanok((cursor.getInt(cursor .getColumnIndex("doubanok")))); } } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } return loginUserInfo; } public void clearTable() { db.delete(db.getConnection(), TABLE_BOTTLE_TYPE, null, null); } }
Java
package com.outsourcing.bottle.db; import android.content.ContentValues; import android.database.Cursor; import com.outsourcing.bottle.domain.PlatformAccount; /** * 开放平台表 * @author 06peng * */ public class PlatformAccountTable { public static final String TABLE_NAME = "platform_account"; public static final String ID = "_id"; public static final String OPEN_TYPE = "open_type"; public static final String ACCESS_TOKEN = "access_Token"; public static final String TOKEN_SECRET = "token_secret"; public static final String NICK_NAME = "nickname"; public static final String OPEN_UID = "open_uid"; public static final String OPEN_SEX = "open_sex"; public static final String OPEN_EXPIRE = "open_expire"; public static final String OPEN_AVATAR = "open_avatar"; private DBManagerImpl db = null; public PlatformAccountTable() { if (db == null) { db = DBManager.get(); } if (!db.isTableExits(db.getConnection(), TABLE_NAME)) { createTable(); } } private void createTable() { String createSql = "create table if not exists " + TABLE_NAME + " (" + ID + " int primary key," + OPEN_TYPE + " int, "+NICK_NAME+" varchar, " + ACCESS_TOKEN + " varchar," + TOKEN_SECRET + " varchar," + OPEN_UID + " varchar," + OPEN_SEX + " int," + OPEN_EXPIRE + " varchar," + OPEN_AVATAR + " varchar)"; db.creatTable(db.getConnection(), createSql, TABLE_NAME); } public void save(PlatformAccount account) { db.delete(db.getConnection(), TABLE_NAME, OPEN_TYPE + "=? and " + OPEN_UID + " = ?", new String[] { String.valueOf(account.getOpenType()), account.getOpenUid() }); ContentValues values = new ContentValues(); values.put(OPEN_TYPE, account.getOpenType()); values.put(OPEN_UID, account.getOpenUid()); values.put(OPEN_EXPIRE, account.getOpenExpire()); values.put(OPEN_AVATAR, account.getOpenAvatar()); values.put(OPEN_SEX, account.getOpenSex()); values.put(NICK_NAME, account.getNickName()); values.put(ACCESS_TOKEN, account.getAccessToken()); values.put(TOKEN_SECRET, account.getTokenSecret()); db.save(db.getConnection(), TABLE_NAME, values); } public PlatformAccount getPlatformAccount(int openType, String openUid) { Cursor cursor = db.find(db.getConnection(), "select * from " + TABLE_NAME + " where " + OPEN_TYPE + "=? and " + OPEN_UID + "=?", new String[] { String.valueOf(openType), openUid }); if (cursor == null) return null; PlatformAccount account = null; try { while (cursor.moveToNext()) { account = new PlatformAccount(); account.setAccessToken(cursor.getString(cursor.getColumnIndex(ACCESS_TOKEN))); account.setNickName(cursor.getString(cursor.getColumnIndex(NICK_NAME))); account.setOpenAvatar(cursor.getString(cursor.getColumnIndex(OPEN_AVATAR))); account.setOpenExpire(cursor.getString(cursor.getColumnIndex(OPEN_EXPIRE))); account.setOpenSex(cursor.getInt(cursor.getColumnIndex(OPEN_SEX))); account.setOpenType(cursor.getInt(cursor.getColumnIndex(OPEN_TYPE))); account.setOpenUid(cursor.getString(cursor.getColumnIndex(OPEN_UID))); account.setTokenSecret(cursor.getString(cursor.getColumnIndex(TOKEN_SECRET))); } } catch (Exception e) { e.printStackTrace(); } finally { if (cursor != null && !cursor.isClosed()) { cursor.close(); } } return account; } }
Java
package com.outsourcing.bottle.adapter; import java.util.List; import android.content.Context; import android.content.Intent; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.outsourcing.bottle.R; import com.outsourcing.bottle.domain.MaybeFriendEntry; import com.outsourcing.bottle.remoteimage.RemoteImageView; import com.outsourcing.bottle.ui.UserSpaceActivity; import com.outsourcing.bottle.ui.fragment.FriendFragment; import com.outsourcing.bottle.util.TextUtil; public class MaybeKnowFriendListAdapter extends BaseAdapter { private Context context = null; private List<MaybeFriendEntry> mbtfriendList = null; private FriendFragment fragment; public MaybeKnowFriendListAdapter(Context context, FriendFragment fragment, List<MaybeFriendEntry> mbtfriendList) { this.context = context; this.fragment = fragment; this.mbtfriendList = mbtfriendList; } @Override public int getCount() { return mbtfriendList.size(); } @Override public Object getItem(int position) { return mbtfriendList.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { BTFriendViewHolder holder = null; if (convertView == null || ((BTFriendViewHolder) convertView.getTag()).flag != position) { holder = new BTFriendViewHolder(); convertView = LayoutInflater.from(context).inflate( R.layout.bottle_list_avatar_item, null); holder.flag = position; holder.mAuthorView = (RemoteImageView) convertView.findViewById(R.id.iv_author_photo); // content layout LinearLayout contentLayout = (LinearLayout) convertView .findViewById(R.id.feed_post_body); View view = LayoutInflater.from(context).inflate( R.layout.myfriend_list_item, null); holder.mNickName = (TextView) view.findViewById(R.id.tv_onickname); holder.mSex = (ImageView)view.findViewById(R.id.bt_sex); holder.mDoing = (TextView) view.findViewById(R.id.tv_odoing); holder.mLocation = (TextView) view.findViewById(R.id.tv_olocation); holder.mAddFriend = (Button) view.findViewById(R.id.bt_add_friend); holder.twitter_layout = (LinearLayout) view .findViewById(R.id.user_space_relation_twitter_layout); holder.facebook_layout = (LinearLayout) view .findViewById(R.id.user_space_relation_facebook_layout); holder.weibo_layout = (LinearLayout) view .findViewById(R.id.user_space_relation_weibo_layout); holder.tencent_layout = (LinearLayout) view .findViewById(R.id.user_space_relation_tencent_layout); holder.renren_layout = (LinearLayout) view .findViewById(R.id.user_space_relation_renren_layout); holder.douban_layout = (LinearLayout) view .findViewById(R.id.user_space_relation_douban_layout); holder.qq_layout = (LinearLayout) view .findViewById(R.id.user_space_relation_qq_layout); holder.twitter_textview = (TextView) view .findViewById(R.id.user_space_relation_twitter_textview); holder.facebook_textview = (TextView) view .findViewById(R.id.user_space_relation_facebook_textview); holder.weibo_textview = (TextView) view .findViewById(R.id.user_space_relation_weibo_textview); holder.tencent_textview = (TextView) view .findViewById(R.id.user_space_relation_tencent_textview); holder.renren_textview = (TextView) view .findViewById(R.id.user_space_relation_renren_textview); holder.douban_textview = (TextView) view .findViewById(R.id.user_space_relation_douban_textview); holder.qq_textview = (TextView) view .findViewById(R.id.user_space_relation_qq_textview); contentLayout.addView(view); final MaybeFriendEntry maybeFriendEntry = (MaybeFriendEntry) getItem(position); try { holder.mAuthorView.setDefaultImage(R.drawable.avatar_default_big); holder.mAuthorView.setImageUrl(maybeFriendEntry.getMkavatar()); } catch (Exception e) { e.printStackTrace(); holder.mAuthorView .setImageResource(R.drawable.avatar_default_big); } holder.mAuthorView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent spaceIntent = new Intent(context, UserSpaceActivity.class); spaceIntent.putExtra("ouid", maybeFriendEntry.getMkuid()); context.startActivity(spaceIntent); } }); holder.mAddFriend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fragment.doCheckApplyFriend(maybeFriendEntry.getMkuid()); } }); String nickName = null; if (maybeFriendEntry.getIsnew() == 1) { nickName = "<font color='#DA4A37'>" + maybeFriendEntry.getMknickname() + "</font>"; }else { nickName = "<font color='#3F99D8'>" + maybeFriendEntry.getMknickname() + "</font>"; } // String sex = (((maybeFriendEntry.getMksex()) == 1) ? ("(" // + TextUtil.R("login_txt_register_male") + ")") : ("(" // + TextUtil.R("login_txt_register_female") + ")")); holder.mNickName.setText(Html.fromHtml(nickName)); int sex_res = maybeFriendEntry.getMksex() == 1 ? R.drawable.male:R.drawable.female; holder.mSex.setBackgroundResource(sex_res); if (null != maybeFriendEntry.getMkdoing() && maybeFriendEntry.getMkdoing().length() > 0) { holder.mDoing.setVisibility(View.VISIBLE); String doingTips = "<font color='#000000'>" + TextUtil.R("friend_doing_tips") + "</font>"; holder.mDoing.setText(Html.fromHtml(doingTips + maybeFriendEntry.getMkdoing())); } else { holder.mDoing.setVisibility(View.GONE); } if ((null != maybeFriendEntry.getMkcountry() && maybeFriendEntry .getMkcountry().length() > 0) || (null != maybeFriendEntry.getMkcity() && maybeFriendEntry .getMkcity().length() > 0)) { holder.mLocation.setVisibility(View.VISIBLE); String fromTips = TextUtil.R("friend_comfrom_tips"); holder.mLocation.setText(fromTips + maybeFriendEntry.getMkcity() + " " + maybeFriendEntry.getMkcountry()); } else { holder.mLocation.setVisibility(View.GONE); } if (null != maybeFriendEntry.getRelation_twitter() && maybeFriendEntry.getRelation_twitter().length() > 0) { holder.twitter_layout.setVisibility(View.VISIBLE); holder.twitter_textview.setText(maybeFriendEntry .getRelation_twitter()); } else { holder.twitter_layout.setVisibility(View.GONE); } if (null != maybeFriendEntry.getRelation_facebook() && maybeFriendEntry.getRelation_facebook().length() > 0) { holder.facebook_layout.setVisibility(View.VISIBLE); holder.facebook_textview.setText(maybeFriendEntry .getRelation_facebook()); } else { holder.facebook_layout.setVisibility(View.GONE); } if (null != maybeFriendEntry.getRelation_sina() && maybeFriendEntry.getRelation_sina().length() > 0) { holder.weibo_layout.setVisibility(View.VISIBLE); holder.weibo_textview.setText(maybeFriendEntry .getRelation_sina()); } else { holder.weibo_layout.setVisibility(View.GONE); } if (null != maybeFriendEntry.getRelation_tqq() && maybeFriendEntry.getRelation_tqq().length() > 0) { holder.tencent_layout.setVisibility(View.VISIBLE); holder.tencent_textview.setText(maybeFriendEntry .getRelation_tqq()); } else { holder.tencent_layout.setVisibility(View.GONE); } if (null != maybeFriendEntry.getRelation_renren() && maybeFriendEntry.getRelation_renren().length() > 0) { holder.renren_layout.setVisibility(View.VISIBLE); holder.renren_textview.setText(maybeFriendEntry .getRelation_renren()); } else { holder.renren_layout.setVisibility(View.GONE); } if (null != maybeFriendEntry.getRelation_douban() && maybeFriendEntry.getRelation_douban().length() > 0) { holder.douban_layout.setVisibility(View.VISIBLE); holder.douban_textview.setText(maybeFriendEntry .getRelation_douban()); } else { holder.douban_layout.setVisibility(View.GONE); } if (null != maybeFriendEntry.getRelation_qq() && maybeFriendEntry.getRelation_qq().length() > 0) { holder.qq_layout.setVisibility(View.VISIBLE); holder.qq_textview.setText(maybeFriendEntry.getRelation_qq()); } else { holder.qq_layout.setVisibility(View.GONE); } convertView.setTag(holder); } else { holder = (BTFriendViewHolder) convertView.getTag(); } return convertView; } public static class BTFriendViewHolder { public ImageView mSex; RemoteImageView mAuthorView; ImageView mExType; TextView mNickName; TextView mDoing; TextView mLocation; Button mAddFriend; LinearLayout twitter_layout; LinearLayout facebook_layout; LinearLayout weibo_layout; LinearLayout tencent_layout; LinearLayout renren_layout; LinearLayout douban_layout; LinearLayout qq_layout; TextView twitter_textview; TextView facebook_textview; TextView weibo_textview; TextView tencent_textview; TextView renren_textview; TextView douban_textview; TextView qq_textview; TextView mTag; TextView mCommentLocation; Button mbtExPhoto; Button mbtExProfile; LinearLayout mFriendLocation; int flag; } }
Java
package com.outsourcing.bottle.adapter; import java.io.File; import java.io.FileInputStream; import java.util.List; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.text.Html; import android.text.TextUtils; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.RelativeLayout; import android.widget.TextView; import com.outsourcing.bottle.R; import com.outsourcing.bottle.domain.ExFeedEntry; import com.outsourcing.bottle.domain.ExPicFeedEntry; import com.outsourcing.bottle.domain.ExsessionsEntry; import com.outsourcing.bottle.remoteimage.RemoteImageView; import com.outsourcing.bottle.ui.ChooseFriendActivity; import com.outsourcing.bottle.ui.ExchangeInfoDetailActivity; import com.outsourcing.bottle.ui.ExchangePicDetailActivity; import com.outsourcing.bottle.ui.ExchangePicFeedDetailActivity; import com.outsourcing.bottle.ui.ExpandEditActivity; import com.outsourcing.bottle.ui.MapViewActivity; import com.outsourcing.bottle.ui.PhotoDetailActivity; import com.outsourcing.bottle.ui.UserSpaceActivity; import com.outsourcing.bottle.ui.fragment.ExchangeFragment; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.ImageLoader; import com.outsourcing.bottle.util.ServiceUtils; import com.outsourcing.bottle.util.TextUtil; public class ExchangeTimeLineAdapter extends BaseAdapter { private Context context; private List<ExsessionsEntry> mExList = null; private ImageLoader imageLoader = null; private ExchangeFragment fragment = null; public ExchangeTimeLineAdapter(Context context, ExchangeFragment fragment, List<ExsessionsEntry> mExList) { this.context = context; this.mExList = mExList; this.fragment = fragment; imageLoader = new ImageLoader(context, AppContext.BottleTimelineIcon); } @Override public int getCount() { return mExList.size(); } @Override public Object getItem(int position) { return mExList.get(position); } @Override public long getItemId(int position) { return 0; } ExchangeBottleHolder holder = null; @Override public View getView(final int position, View convertView, ViewGroup parent) { if (convertView == null) { holder = new ExchangeBottleHolder(); convertView = LayoutInflater.from(context).inflate( R.layout.bottle_list_avatar_item, null); holder.flag = position; holder.mAuthorView = (RemoteImageView) convertView .findViewById(R.id.iv_author_photo); holder.mExType = (ImageView) convertView .findViewById(R.id.iv_bottle_type); // content layout LinearLayout contentLayout = (LinearLayout) convertView .findViewById(R.id.feed_post_body); View view = LayoutInflater.from(context).inflate( R.layout.exchange_list_detail_item, null); holder.mNickName = (TextView) view.findViewById(R.id.tv_nickname); holder.mTime = (TextView) view.findViewById(R.id.tv_time); holder.mExAvatar = (RemoteImageView) view .findViewById(R.id.iv_author_photo); holder.mComment = (Button) view .findViewById(R.id.bt_exchange_comment); holder.mReject = (Button) view .findViewById(R.id.bt_exchange_reject); holder.mAccept = (Button) view .findViewById(R.id.bt_exchange_accept); holder.mVisiable = (Button) view .findViewById(R.id.bt_exchange_visible); holder.mInvisiable = (Button) view .findViewById(R.id.bt_exchange_invisible); holder.mfeedMoreComment = (RelativeLayout) view .findViewById(R.id.feed_comments_more); holder.mfeedNum = (TextView) view .findViewById(R.id.comments_ellipsis_text); holder.mfeedComment = (LinearLayout) view .findViewById(R.id.ll_feed_comment_layout); holder.mfeedComment.removeAllViews(); contentLayout.addView(view); convertView.setTag(holder); } else { holder = (ExchangeBottleHolder) convertView.getTag(); holder.mfeedComment.removeAllViews(); } final ExsessionsEntry exsessionsEntry = (ExsessionsEntry) getItem(position); try { holder.mAuthorView.setDefaultImage(R.drawable.avatar_default_big); holder.mAuthorView.setImageUrl(exsessionsEntry.getExs_avatar()); } catch (Exception e) { e.printStackTrace(); holder.mAuthorView.setImageResource(R.drawable.avatar_default_big); } holder.mAuthorView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent spaceIntent = new Intent(context, UserSpaceActivity.class); spaceIntent.putExtra("ouid", exsessionsEntry.getExs_uid()); context.startActivity(spaceIntent); } }); holder.mComment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent commentIntent = new Intent(context, ExpandEditActivity.class); Bundle commentBundle = new Bundle(); fragment.position = position; fragment.exsid = exsessionsEntry.getExsid(); if (exsessionsEntry.getExs_type() == 1) { commentBundle.putString("from_type", AppContext.REPLY_INFOEX); int ouid = (exsessionsEntry.getExs_ouid() != AppContext .getInstance().getLogin_uid()) ? exsessionsEntry .getExs_ouid() : ((exsessionsEntry.getExs_uid() != AppContext .getInstance().getLogin_uid()) ? exsessionsEntry .getExs_uid() : AppContext.getInstance() .getLogin_uid()); commentBundle.putInt("ouid", ouid); commentBundle.putString("reply_infoex_type", "replay"); commentIntent.putExtras(commentBundle); } else { AppContext.getInstance().setFromExchangeTime(true); commentBundle .putString("from_type", AppContext.REPLY_PICEX); int ouid = (exsessionsEntry.getExs_ouid() != AppContext .getInstance().getLogin_uid()) ? exsessionsEntry .getExs_ouid() : ((exsessionsEntry.getExs_uid() != AppContext .getInstance().getLogin_uid()) ? exsessionsEntry .getExs_uid() : AppContext.getInstance() .getLogin_uid()); commentBundle.putInt("ouid", ouid); commentBundle.putString("reply_picex_type", "reply"); commentIntent.putExtras(commentBundle); } context.startActivity(commentIntent); } }); if (exsessionsEntry.getExs_type() == 1) { holder.mExType.setImageResource(R.drawable.btn_exprofile); holder.mExType.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int ouid = (exsessionsEntry.getExs_ouid() != AppContext .getInstance().getLogin_uid()) ? exsessionsEntry .getExs_ouid() : ((exsessionsEntry.getExs_uid() != AppContext .getInstance().getLogin_uid()) ? exsessionsEntry .getExs_uid() : AppContext.getInstance() .getLogin_uid()); fragment.doExchange( AppContext.CHOOSE_FRIEND_EXCHANGE_INFO_TYPE, ouid); } }); if (exsessionsEntry.getExs_infoex_rejectshow() == 1) { holder.mReject.setVisibility(View.VISIBLE); holder.mReject.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int ouid = (exsessionsEntry.getExs_ouid() != AppContext .getInstance().getLogin_uid()) ? exsessionsEntry .getExs_ouid() : ((exsessionsEntry.getExs_uid() != AppContext .getInstance().getLogin_uid()) ? exsessionsEntry .getExs_uid() : AppContext .getInstance().getLogin_uid()); fragment.doRejectInfoex(ouid, position, exsessionsEntry.getExsid()); } }); } else { holder.mReject.setVisibility(View.INVISIBLE); } if (exsessionsEntry.getExs_infoex_acceptshow() == 1) { holder.mAccept.setVisibility(View.VISIBLE); holder.mAccept.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int ouid = (exsessionsEntry.getExs_ouid() != AppContext .getInstance().getLogin_uid()) ? exsessionsEntry .getExs_ouid() : ((exsessionsEntry.getExs_uid() != AppContext .getInstance().getLogin_uid()) ? exsessionsEntry .getExs_uid() : AppContext .getInstance().getLogin_uid()); fragment.doAcceptInfoex(ouid, position, exsessionsEntry.getExsid()); } }); } else { holder.mAccept.setVisibility(View.GONE); } if (exsessionsEntry.getExs_infoex_visibleshow() == 1) { holder.mVisiable.setVisibility(View.VISIBLE); holder.mVisiable.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int ouid = (exsessionsEntry.getExs_ouid() != AppContext .getInstance().getLogin_uid()) ? exsessionsEntry .getExs_ouid() : ((exsessionsEntry.getExs_uid() != AppContext .getInstance().getLogin_uid()) ? exsessionsEntry .getExs_uid() : AppContext .getInstance().getLogin_uid()); fragment.doVisibleInfoex(ouid, position, exsessionsEntry.getExsid()); } }); } else { holder.mVisiable.setVisibility(View.GONE); } if (exsessionsEntry.getExs_infoex_invisibleshow() == 1) { holder.mInvisiable.setVisibility(View.VISIBLE); holder.mInvisiable .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int ouid = (exsessionsEntry.getExs_ouid() != AppContext .getInstance().getLogin_uid()) ? exsessionsEntry .getExs_ouid() : ((exsessionsEntry.getExs_uid() != AppContext .getInstance().getLogin_uid()) ? exsessionsEntry .getExs_uid() : AppContext .getInstance().getLogin_uid()); fragment.doInvisibleInfoex(ouid, position, exsessionsEntry.getExsid()); } }); } else { holder.mInvisiable.setVisibility(View.GONE); } } else { holder.mExType.setImageResource(R.drawable.btn_exphoto); holder.mExType.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int ouid = (exsessionsEntry.getExs_ouid() != AppContext .getInstance().getLogin_uid()) ? exsessionsEntry .getExs_ouid() : ((exsessionsEntry.getExs_uid() != AppContext .getInstance().getLogin_uid()) ? exsessionsEntry .getExs_uid() : AppContext.getInstance() .getLogin_uid()); fragment.doExchange( AppContext.CHOOSE_FRIEND_EXCHANGE_PHOTO_TYPE, ouid); } }); if (exsessionsEntry.getExs_picex_rejectshow() == 1) { holder.mReject.setVisibility(View.VISIBLE); holder.mReject.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int ouid = (exsessionsEntry.getExs_ouid() != AppContext .getInstance().getLogin_uid()) ? exsessionsEntry .getExs_ouid() : ((exsessionsEntry.getExs_uid() != AppContext .getInstance().getLogin_uid()) ? exsessionsEntry .getExs_uid() : AppContext .getInstance().getLogin_uid()); fragment.doRejectPicex(ouid, position, exsessionsEntry.getExsid()); } }); } else { holder.mReject.setVisibility(View.INVISIBLE); } if (exsessionsEntry.getExs_picex_visibleshow() == 1) { holder.mVisiable.setVisibility(View.VISIBLE); holder.mVisiable.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int ouid = (exsessionsEntry.getExs_ouid() != AppContext .getInstance().getLogin_uid()) ? exsessionsEntry .getExs_ouid() : ((exsessionsEntry.getExs_uid() != AppContext .getInstance().getLogin_uid()) ? exsessionsEntry .getExs_uid() : AppContext .getInstance().getLogin_uid()); fragment.doVisiblePicex(ouid, position, exsessionsEntry.getExsid()); } }); } else { holder.mVisiable.setVisibility(View.GONE); } if (exsessionsEntry.getExs_picex_invisibleshow() == 1) { holder.mInvisiable.setVisibility(View.VISIBLE); holder.mInvisiable .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int ouid = (exsessionsEntry.getExs_ouid() != AppContext .getInstance().getLogin_uid()) ? exsessionsEntry .getExs_ouid() : ((exsessionsEntry.getExs_uid() != AppContext .getInstance().getLogin_uid()) ? exsessionsEntry .getExs_uid() : AppContext .getInstance().getLogin_uid()); fragment.doInvisiblePicex(ouid, position, exsessionsEntry.getExsid()); } }); } else { holder.mInvisiable.setVisibility(View.GONE); } } try { holder.mExAvatar.setDefaultImage(R.drawable.avatar_default_big); holder.mExAvatar.setImageUrl(exsessionsEntry.getExs_oavatar()); } catch (Exception e) { e.printStackTrace(); holder.mExAvatar.setImageResource(R.drawable.avatar_default_big); } holder.mExAvatar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent spaceIntent = new Intent(context, UserSpaceActivity.class); spaceIntent.putExtra("ouid", exsessionsEntry.getExs_ouid()); context.startActivity(spaceIntent); } }); String nickName = null; if (exsessionsEntry.getExs_uid() != AppContext.getInstance() .getLogin_uid()) { nickName = "<font color='#DA4A37'>" + exsessionsEntry.getExs_nickname() + "</font>"; } else { nickName = "<font color='#3F99D8'>" + exsessionsEntry.getExs_nickname() + "</font>"; } String mFirstFeed = (exsessionsEntry.getExs_firstfeed() != null && exsessionsEntry .getExs_firstfeed().length() > 0) ? " " + exsessionsEntry.getExs_firstfeed() : ""; String mSuccess = (exsessionsEntry.getExs_success() == 1) ? ("<font color='#DA4A37'>" + TextUtil.R("exchange_success") + "</font>") : ("<font color='#DA4A37'>" + TextUtil.R("exchange_failed") + "</font>"); String time = (exsessionsEntry.getExs_firstfeedtime() != null && exsessionsEntry .getExs_firstfeedtime().length() > 0) ? ("<font color='#666666'>" + "#" + exsessionsEntry.getExs_firstfeedtime() + "</font>") : ""; holder.mNickName.setText(Html.fromHtml(nickName + mFirstFeed + " " + mSuccess)); if (time.length() > 0) { holder.mTime.setVisibility(View.VISIBLE); holder.mTime.setText(Html.fromHtml(time)); } else { holder.mTime.setVisibility(View.GONE); } List<ExFeedEntry> mExFeedEntries = null; if (null != exsessionsEntry.getExfeeds_list() && exsessionsEntry.getExfeeds_list().size() > 0) { holder.mfeedMoreComment.setVisibility(View.VISIBLE); holder.mfeedMoreComment .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int ouid = (exsessionsEntry.getExs_ouid() != AppContext .getInstance().getLogin_uid()) ? exsessionsEntry .getExs_ouid() : ((exsessionsEntry .getExs_uid() != AppContext.getInstance() .getLogin_uid()) ? exsessionsEntry .getExs_uid() : AppContext.getInstance() .getLogin_uid()); if (exsessionsEntry.getExs_type() == 1) { fragment.doExchange( AppContext.CHOOSE_FRIEND_EXCHANGE_INFO_TYPE, ouid); } else { fragment.doExchange( AppContext.CHOOSE_FRIEND_EXCHANGE_PHOTO_TYPE, ouid); } } }); holder.mfeedNum.setText(exsessionsEntry.getExfeeds_count() + " " + TextUtil.R("bottle_txt_comment_more")); mExFeedEntries = exsessionsEntry.getExfeeds_list(); for (int i = 0; i < mExFeedEntries.size(); i++) { final ExFeedEntry exfeedEntry = mExFeedEntries.get(i); View mCommentView = LayoutInflater.from(context).inflate( R.layout.exchange_comments_item, null); if (i == (mExFeedEntries.size()-1)) { View feed_avatar = (View) mCommentView .findViewById(R.id.line_exchange_feed); feed_avatar.setVisibility(View.INVISIBLE); } TextView mFeedAvatar = (TextView) mCommentView .findViewById(R.id.tv_feed_comment_nickname); String feed_name = null; if (exfeedEntry.getExfeed_uid() != AppContext.getInstance() .getLogin_uid()) { feed_name = "<font color='#DA4A37'>" + exfeedEntry.getExfeed_nickname() + "</font>"; } else { feed_name = "<font color='#3F99D8'>" + exfeedEntry.getExfeed_nickname() + "</font>"; } mFeedAvatar .setText(Html.fromHtml(feed_name + " " + TextUtil.htmlEncode(exfeedEntry .getExfeed_content()))); TextView mFeedComment = (TextView) mCommentView .findViewById(R.id.tv_feed_comment_content); if (!TextUtils.isEmpty(exfeedEntry.getExfeed_comment())) { mFeedComment.setVisibility(View.VISIBLE); String commentTips = "<font color='#000000'>" + TextUtil.R("exchange_feed_comment_title") + "</font>"; String feed_content = exfeedEntry.getExfeed_isnew() == 1 ? ("<font color='#DA4A37'>" + TextUtil.htmlEncode(exfeedEntry .getExfeed_comment()) + "</font>") : TextUtil.htmlEncode(exfeedEntry .getExfeed_comment()); mFeedComment.setText(Html.fromHtml(commentTips + feed_content)); } else { mFeedComment.setVisibility(View.GONE); } TextView mFeedTime = (TextView) mCommentView .findViewById(R.id.tv_feed_comment_time); if (!TextUtils.isEmpty(exfeedEntry.getExfeed_location()) || !TextUtils.isEmpty(exfeedEntry.getExfeed_time())) { mFeedTime.setVisibility(View.VISIBLE); String commentTime = TextUtils.isEmpty(exfeedEntry .getExfeed_time()) ? "" : ("#" + exfeedEntry .getExfeed_time()); String commentLocation = TextUtils.isEmpty(exfeedEntry .getExfeed_location()) ? "" : ("@" + exfeedEntry .getExfeed_location()); mFeedTime.setText(commentTime + " " + commentLocation); mFeedTime.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final Context dialogContext = new ContextThemeWrapper( context, android.R.style.Theme_Light); String[] choices = new String[1]; choices[0] = context .getString(R.string.bottle_txt_check_location); final ListAdapter adapter = new ArrayAdapter<String>( dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { dialog.dismiss(); Intent intent = new Intent(context, MapViewActivity.class); intent.putExtra("longitude", exfeedEntry.getExfeed_lng()); intent.putExtra("latidute", exfeedEntry.getExfeed_lat()); intent.putExtra( "location", exfeedEntry .getExfeed_location()); context.startActivity(intent); } }); builder.create().show(); } }); } else { mFeedTime.setVisibility(View.GONE); } RemoteImageView mFeedCommentAvatar = (RemoteImageView) mCommentView .findViewById(R.id.comment_profile_photo); try { mFeedCommentAvatar.setDefaultImage(R.drawable.avatar_default_small); mFeedCommentAvatar.setImageUrl(exfeedEntry.getExfeed_avatar()); } catch (Exception e) { e.printStackTrace(); mFeedCommentAvatar .setImageResource(R.drawable.avatar_default_small); } mFeedCommentAvatar .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent spaceIntent = new Intent(context, UserSpaceActivity.class); spaceIntent.putExtra("ouid", exfeedEntry.getExfeed_uid()); context.startActivity(spaceIntent); } }); RelativeLayout exFeedPicContent = (RelativeLayout) mCommentView .findViewById(R.id.rl_exchange_feed_type); if (exfeedEntry.getExfeed_type() == 1) { exFeedPicContent.setVisibility(View.GONE); } else { if (!TextUtils.isEmpty(exfeedEntry.getExfeed_pic())) { exFeedPicContent.setVisibility(View.VISIBLE); RelativeLayout rl_bottle_content_photo = (RelativeLayout) mCommentView .findViewById(R.id.rl_bottle_content_photo); LinearLayout ll_bottle_photo_locked = (LinearLayout) mCommentView .findViewById(R.id.ll_bottle_photo_locked); Button comment_button_exchange = (Button) mCommentView .findViewById(R.id.comment_button_exchange); LinearLayout comment_button_like = (LinearLayout) mCommentView .findViewById(R.id.comment_button_like); if (exfeedEntry.getExfeed_pic_locked() == 1) { comment_button_like.setVisibility(View.GONE); rl_bottle_content_photo.setVisibility(View.GONE); ll_bottle_photo_locked.setVisibility(View.VISIBLE); comment_button_exchange.setVisibility(View.VISIBLE); comment_button_exchange .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fragment.position = position; AppContext.getInstance() .setFromExchangeTime(true); fragment.exsid = exsessionsEntry .getExsid(); Intent intentPhoto = new Intent( context, ExpandEditActivity.class); Bundle bundlePhoto = new Bundle(); bundlePhoto.putString("from_type", AppContext.REPLY_PICEX); bundlePhoto.putString( "reply_picex_type", "accept"); bundlePhoto .putInt("ouid", exfeedEntry .getExfeed_uid()); intentPhoto.putExtras(bundlePhoto); context.startActivity(intentPhoto); } }); } else { ll_bottle_photo_locked.setVisibility(View.GONE); comment_button_exchange.setVisibility(View.GONE); rl_bottle_content_photo.setVisibility(View.VISIBLE); comment_button_like.setVisibility(View.VISIBLE); ImageView exFeedPicView = (ImageView) mCommentView .findViewById(R.id.photo); imageLoader.DisplayImage( exfeedEntry.getExfeed_pic(), exFeedPicView, R.drawable.album_nophoto); exFeedPicView .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int ouid = (exsessionsEntry .getExs_ouid() != AppContext .getInstance() .getLogin_uid()) ? exsessionsEntry .getExs_ouid() : ((exsessionsEntry .getExs_uid() != AppContext .getInstance() .getLogin_uid()) ? exsessionsEntry .getExs_uid() : AppContext .getInstance() .getLogin_uid()); Status status = null; if (exfeedEntry.getExfeed_uid() == AppContext.getInstance().getLogin_uid()) { //自己的照片 if (exfeedEntry.getExfeed_pic_enabletuya() == 1 && exfeedEntry.getExfeed_pic_allowtuya() == 1) { status = Status.exchange_pic_feed_my_allowtuya_and_enabletuya; } else if (exfeedEntry.getExfeed_pic_enabletuya() == 2 && exfeedEntry.getExfeed_pic_allowtuya() == 1 ) { status = Status.exchange_pic_feed_my_allowtuya_and_not_enabletuya; } else { status = Status.exchange_pic_feed; } doPhotoAction(ouid,exfeedEntry, status, position, exsessionsEntry.getExsid()); } else { if (exfeedEntry.getExfeed_pic_allowtuya() == 1) { status = Status.exchange_pic_feed_other_allowtuya; } else { status = Status.exchange_pic_feed_other; } //别人的照片 doPhotoAction(ouid,exfeedEntry, status, position, exsessionsEntry.getExsid()); } } }); if (exfeedEntry.getExfeed_like_enable() == 1) { comment_button_like.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.photo_pill)); comment_button_like .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int ouid = (exsessionsEntry .getExs_ouid() != AppContext .getInstance() .getLogin_uid()) ? exsessionsEntry .getExs_ouid() : ((exsessionsEntry .getExs_uid() != AppContext .getInstance() .getLogin_uid()) ? exsessionsEntry .getExs_uid() : 0); fragment.showInfoPopupWindow( v, exfeedEntry .getExfeed_picid(), ouid, exsessionsEntry .getExsid(), position); } }); } else { comment_button_like .setBackgroundDrawable(context.getResources().getDrawable(R.drawable.photo_pill_dark)); } ImageView mLikeIcon = (ImageView) mCommentView .findViewById(R.id.comment_button_like_icon); switch (exfeedEntry.getExfeed_pic_liked()) { case 0: mLikeIcon .setImageResource(R.drawable.like_gray2); break; case 1: mLikeIcon .setImageResource(R.drawable.like_red2); break; case 2: mLikeIcon .setImageResource(R.drawable.like_black2); break; default: break; } } } else { exFeedPicContent.setVisibility(View.GONE); } List<ExPicFeedEntry> picFeedEntries = exfeedEntry .getExpicfeeds_list(); if (null != picFeedEntries && picFeedEntries.size() > 0) { LinearLayout mCommentItemLayout = (LinearLayout) mCommentView .findViewById(R.id.ll_exchange_feed_comment); // ExPicFeedEntry exPicFeedEntry = null; for (int j = 0; j < picFeedEntries.size(); j++) { final ExPicFeedEntry exPicFeedEntry = picFeedEntries.get(j); View picFeedItem = LayoutInflater .from(context) .inflate( R.layout.exchange_pic_comments_item, null); ImageView mLink = (ImageView) picFeedItem .findViewById(R.id.iv_feed_comment_white); switch (exPicFeedEntry.getExpicfeed_type()) { case 0: mLink.setImageResource(R.drawable.feed_white); break; case 1: mLink.setImageResource(R.drawable.feed_white); break; case 2: mLink.setImageResource(R.drawable.like_red3); break; case 3: mLink.setImageResource(R.drawable.like_black3); break; default: mLink.setImageResource(R.drawable.feed_white); break; } TextView picFeedNickname = (TextView) picFeedItem .findViewById(R.id.tv_feed_comment_nickname); String feedex_content = exPicFeedEntry.getExpicfeed_isnew() == 1 ? ("<font color='#DA4A37'>" + TextUtil.htmlEncode(exPicFeedEntry.getExpicfeed_content()) + "</font>") : TextUtil.htmlEncode(exPicFeedEntry.getExpicfeed_content()); String picFeedNameStr = null; if (exPicFeedEntry.getExpicfeed_uid() != AppContext.getInstance() .getLogin_uid()) { picFeedNameStr = (!TextUtils.isEmpty(exPicFeedEntry.getExpicfeed_nickname())) ? ("<font color='#DA4A37'>" + exPicFeedEntry.getExpicfeed_nickname() + "</font>"): ""; } else { picFeedNameStr = (!TextUtils.isEmpty(exPicFeedEntry.getExpicfeed_nickname())) ? ("<font color='#3F99D8'>" + exPicFeedEntry.getExpicfeed_nickname() + "</font>"): ""; } picFeedNickname.setText(Html.fromHtml(picFeedNameStr+ " "+ feedex_content)); TextView picComment = (TextView) picFeedItem .findViewById(R.id.tv_feed_comment_content); if (!TextUtils.isEmpty(exPicFeedEntry.getExpicfeed_comment())) { picComment.setVisibility(View.VISIBLE); String commentTips = "<font color='#000000'>" + TextUtil .R("exchange_feed_comment_title") + "</font>"; picComment.setText(Html.fromHtml(commentTips + TextUtil.htmlEncode(exPicFeedEntry .getExpicfeed_comment()))); } else { picComment.setVisibility(View.GONE); } TextView picCommentTime = (TextView) picFeedItem .findViewById(R.id.tv_feed_comment_time); String picCommentLocation = TextUtils.isEmpty(exPicFeedEntry.getExpicfeed_location()) ? "" : ("@" + exPicFeedEntry.getExpicfeed_location()); if (null != exPicFeedEntry.getExpicfeed_time() && exPicFeedEntry.getExpicfeed_time() .length() > 0) { picCommentTime.setVisibility(View.VISIBLE); picCommentTime.setText("#"+exPicFeedEntry .getExpicfeed_time()+picCommentLocation); if (picCommentLocation.length()>0) { picCommentTime.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final Context dialogContext = new ContextThemeWrapper(context, android.R.style.Theme_Light); String[] choices = new String[1]; choices[0] = context.getString(R.string.bottle_txt_check_location); final ListAdapter adapter = new ArrayAdapter<String>( dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { dialog.dismiss(); Intent intent = new Intent(context, MapViewActivity.class); intent.putExtra("longitude",exPicFeedEntry.getExpicfeed_lng()); intent.putExtra("latidute",exPicFeedEntry.getExpicfeed_lat()); intent.putExtra("location",exPicFeedEntry.getExpicfeed_location()); context.startActivity(intent); } }); builder.create().show(); } }); } }else { picCommentTime.setVisibility(View.INVISIBLE); } mCommentItemLayout.addView(picFeedItem); } } } holder.mfeedComment.addView(mCommentView); holder.mfeedComment .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int ouid = (exsessionsEntry.getExs_ouid() != AppContext .getInstance().getLogin_uid()) ? exsessionsEntry .getExs_ouid() : ((exsessionsEntry.getExs_uid() != AppContext .getInstance().getLogin_uid()) ? exsessionsEntry .getExs_uid() : AppContext .getInstance().getLogin_uid()); if (exsessionsEntry.getExs_type() == 1) { Intent intent = new Intent(context, ExchangeInfoDetailActivity.class); intent.putExtra("ouid", ouid); intent.putExtra("page", 1); context.startActivity(intent); } else { Intent intent = new Intent(context, ExchangePicDetailActivity.class); intent.putExtra("ouid", ouid); intent.putExtra("page", 1); context.startActivity(intent); } } }); } } else { holder.mfeedMoreComment.setVisibility(View.GONE); } return convertView; } /*** */ public void doPhotoAction(final int ouid, final ExFeedEntry exfeedEntry , Status status, final int position, final int exsid) { Context dialogContext = null; ListAdapter adapter = null; String[] choices = null; AlertDialog.Builder builder = null; switch (status) { case exchange_pic_feed: dialogContext = new ContextThemeWrapper(context, android.R.style.Theme_Light); choices = context.getResources().getStringArray( R.array.exchange_pic_feed); adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices); builder = new AlertDialog.Builder(dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); switch (which) { case 0:// View Comment Intent intent = new Intent(context, ExchangePicFeedDetailActivity.class); intent.putExtra("ouid", ouid); intent.putExtra("picid", exfeedEntry.getExfeed_picid()); context.startActivity(intent); break; case 1:// Comment fragment.position = position; fragment.exsid = exsid; Intent commentIntent = new Intent(context, ExpandEditActivity.class); AppContext.getInstance().setFromExchangeTime( true); Bundle commentBundle = new Bundle(); commentBundle.putString("from_type", AppContext.REPLYPIC_PICEX); commentBundle.putInt("ouid", ouid); commentBundle.putInt("picid", exfeedEntry.getExfeed_picid()); commentIntent.putExtras(commentBundle); context.startActivity(commentIntent); break; case 2:// Cancel break; default: break; } } }); builder.create().show(); break; case exchange_pic_feed_my_allowtuya_and_enabletuya: dialogContext = new ContextThemeWrapper(context, android.R.style.Theme_Light); choices = context.getResources().getStringArray( R.array.exchange_pic_feed_my_allowtuya_and_enabletuya); adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices); builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); switch (which) { case 0:// View Comment Intent intent = new Intent(context, ExchangePicFeedDetailActivity.class); intent.putExtra("ouid", ouid); intent.putExtra("picid", exfeedEntry.getExfeed_picid()); context.startActivity(intent); break; case 1:// Comment fragment.position = position; fragment.exsid = exsid; Intent commentIntent = new Intent(context, ExpandEditActivity.class); AppContext.getInstance().setFromExchangeTime(true); Bundle commentBundle = new Bundle(); commentBundle.putString("from_type", AppContext.REPLYPIC_PICEX); commentBundle.putInt("ouid", ouid); commentBundle.putInt("picid", exfeedEntry.getExfeed_picid()); commentIntent.putExtras(commentBundle); context.startActivity(commentIntent); break; case 2://涂鸦照片 byte[] tempBytes = null; try { String filename = ServiceUtils.convertUrlToFileName(exfeedEntry.getExfeed_pic()); tempBytes = ServiceUtils.readStream(new FileInputStream(new File( android.os.Environment.getExternalStorageDirectory() + "/" + AppContext.BottleTimelineIcon + "/" + filename))); } catch (Exception e) { e.printStackTrace(); } fragment.position = position; fragment.exsid = exsid; Intent bigPicIntent = new Intent(context, PhotoDetailActivity.class); bigPicIntent.putExtra("pic_big", exfeedEntry.getExfeed_pic_big()); bigPicIntent.putExtra("thumbnail", tempBytes); bigPicIntent.putExtra("paintType", AppContext.PAINT_PICEX); bigPicIntent.putExtra("ouid", ouid); bigPicIntent.putExtra("picid", exfeedEntry.getExfeed_picid()); bigPicIntent.putExtra("return_type",ExchangeFragment.class.getSimpleName()); bigPicIntent.putExtra("isToDraw", true); context.startActivity(bigPicIntent); break; case 3://允许涂鸦 fragment.doExpicPaint(ouid, exfeedEntry.getExfeed_picid(), 1, exsid, position); break; case 4:// Cancel break; default: break; } } }); builder.create().show(); break; case exchange_pic_feed_my_allowtuya_and_not_enabletuya: dialogContext = new ContextThemeWrapper(context, android.R.style.Theme_Light); choices = context.getResources().getStringArray( R.array.exchange_pic_feed_my_allowtuya_and_not_enabletuya); adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices); builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); switch (which) { case 0:// View Comment Intent intent = new Intent(context, ExchangePicFeedDetailActivity.class); intent.putExtra("ouid", ouid); intent.putExtra("picid", exfeedEntry.getExfeed_picid()); context.startActivity(intent); break; case 1:// Comment fragment.position = position; fragment.exsid = exsid; Intent commentIntent = new Intent(context, ExpandEditActivity.class); AppContext.getInstance().setFromExchangeTime(true); Bundle commentBundle = new Bundle(); commentBundle.putString("from_type", AppContext.REPLYPIC_PICEX); commentBundle.putInt("ouid", ouid); commentBundle.putInt("picid", exfeedEntry.getExfeed_picid()); commentIntent.putExtras(commentBundle); context.startActivity(commentIntent); break; case 2://涂鸦照片 byte[] tempBytes = null; try { String filename = ServiceUtils.convertUrlToFileName(exfeedEntry.getExfeed_pic()); tempBytes = ServiceUtils.readStream(new FileInputStream(new File( android.os.Environment.getExternalStorageDirectory() + "/" + AppContext.BottleTimelineIcon + "/" + filename))); } catch (Exception e) { e.printStackTrace(); } fragment.position = position; fragment.exsid = exsid; Intent bigPicIntent = new Intent(context, PhotoDetailActivity.class); bigPicIntent.putExtra("pic_big", exfeedEntry.getExfeed_pic_big()); bigPicIntent.putExtra("thumbnail", tempBytes); bigPicIntent.putExtra("paintType", AppContext.PAINT_PICEX); bigPicIntent.putExtra("ouid", ouid); bigPicIntent.putExtra("picid", exfeedEntry.getExfeed_picid()); bigPicIntent.putExtra("return_type",ExchangeFragment.class.getSimpleName()); bigPicIntent.putExtra("isToDraw", true); context.startActivity(bigPicIntent); break; case 3://不允许涂鸦 fragment.doExpicPaint(ouid, exfeedEntry.getExfeed_picid(), 0, exsid, position); break; case 4:// Cancel break; default: break; } } }); builder.create().show(); break; case exchange_pic_feed_other: dialogContext = new ContextThemeWrapper(context, android.R.style.Theme_Light); choices = context.getResources().getStringArray( R.array.exchange_pic_feed_other); adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices); builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); switch (which) { case 0:// View Comment Intent intent = new Intent(context, ExchangePicFeedDetailActivity.class); intent.putExtra("ouid", ouid); intent.putExtra("picid", exfeedEntry.getExfeed_picid()); context.startActivity(intent); break; case 1:// Comment fragment.position = position; fragment.exsid = exsid; Intent commentIntent = new Intent(context, ExpandEditActivity.class); AppContext.getInstance().setFromExchangeTime(true); Bundle commentBundle = new Bundle(); commentBundle.putString("from_type", AppContext.REPLYPIC_PICEX); commentBundle.putInt("ouid", ouid); commentBundle.putInt("picid", exfeedEntry.getExfeed_picid()); commentIntent.putExtras(commentBundle); context.startActivity(commentIntent); break; case 2: fragment.position = position; fragment.exsid = exsid; AppContext.getInstance().setFromExchangeTime(true); Intent friendIntent = new Intent(context, ChooseFriendActivity.class); friendIntent.putExtra("choose_friend_type", AppContext.CHOOSE_FRIEND_FORWARD_PHOTO_TYPE); friendIntent.putExtra("picid", exfeedEntry.getExfeed_picid()); friendIntent.putExtra("pic_uid", ouid); context.startActivity(friendIntent); break; case 3:// Cancel break; default: break; } } }); builder.create().show(); break; case exchange_pic_feed_other_allowtuya: dialogContext = new ContextThemeWrapper(context, android.R.style.Theme_Light); choices = context.getResources().getStringArray( R.array.exchange_pic_feed_other_allowtuya); adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices); builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); switch (which) { case 0:// View Comment Intent intent = new Intent(context, ExchangePicFeedDetailActivity.class); intent.putExtra("ouid", ouid); intent.putExtra("picid", exfeedEntry.getExfeed_picid()); context.startActivity(intent); break; case 1:// Comment fragment.position = position; fragment.exsid = exsid; Intent commentIntent = new Intent(context, ExpandEditActivity.class); AppContext.getInstance().setFromExchangeTime(true); Bundle commentBundle = new Bundle(); commentBundle.putString("from_type", AppContext.REPLYPIC_PICEX); commentBundle.putInt("ouid", ouid); commentBundle.putInt("picid", exfeedEntry.getExfeed_picid()); commentIntent.putExtras(commentBundle); context.startActivity(commentIntent); break; case 2://涂鸦照片 byte[] tempBytes = null; try { String filename = ServiceUtils.convertUrlToFileName(exfeedEntry.getExfeed_pic()); tempBytes = ServiceUtils.readStream(new FileInputStream(new File( android.os.Environment.getExternalStorageDirectory() + "/" + AppContext.BottleTimelineIcon + "/" + filename))); } catch (Exception e) { e.printStackTrace(); } fragment.position = position; fragment.exsid = exsid; Intent bigPicIntent = new Intent(context, PhotoDetailActivity.class); bigPicIntent.putExtra("pic_big", exfeedEntry.getExfeed_pic_big()); bigPicIntent.putExtra("thumbnail", tempBytes); bigPicIntent.putExtra("paintType", AppContext.PAINT_PICEX); bigPicIntent.putExtra("ouid", exfeedEntry.getExfeed_uid()); bigPicIntent.putExtra("picid", exfeedEntry.getExfeed_picid()); bigPicIntent.putExtra("return_type",ExchangeFragment.class.getSimpleName()); bigPicIntent.putExtra("isToDraw", true); context.startActivity(bigPicIntent); break; case 3: fragment.position = position; fragment.exsid = exsid; AppContext.getInstance().setFromExchangeTime(true); Intent friendIntent = new Intent(context, ChooseFriendActivity.class); friendIntent.putExtra("choose_friend_type", AppContext.CHOOSE_FRIEND_FORWARD_PHOTO_TYPE); friendIntent.putExtra("picid", exfeedEntry.getExfeed_picid()); friendIntent.putExtra("pic_uid", ouid); context.startActivity(friendIntent); break; case 4:// Cancel break; default: break; } } }); builder.create().show(); break; default: break; } } private static enum Status{ exchange_pic_feed, exchange_pic_feed_my_allowtuya_and_not_enabletuya, exchange_pic_feed_my_allowtuya_and_enabletuya, exchange_pic_feed_other, exchange_pic_feed_other_allowtuya, } public class ExchangeBottleHolder { RemoteImageView mAuthorView; ImageView mExType; TextView mNickName; TextView mTime; RemoteImageView mExAvatar; Button mComment; Button mReject; Button mAccept; Button mVisiable; Button mInvisiable; RelativeLayout mfeedMoreComment; TextView mfeedNum; LinearLayout mfeedComment; int flag; } }
Java
package com.outsourcing.bottle.adapter; import java.util.List; import android.content.Context; import android.content.Intent; import android.text.Html; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.outsourcing.bottle.R; import com.outsourcing.bottle.domain.MyFriendEntry; import com.outsourcing.bottle.remoteimage.RemoteImageView; import com.outsourcing.bottle.ui.UserSpaceActivity; import com.outsourcing.bottle.ui.fragment.FriendFragment; import com.outsourcing.bottle.util.TextUtil; public class MyFriendListAdapter extends BaseAdapter { private Context context = null; private List<MyFriendEntry> mbtfriendList = null; public MyFriendListAdapter(Context context, FriendFragment fragment, List<MyFriendEntry> mbtfriendList) { this.context = context; this.mbtfriendList = mbtfriendList; } @Override public int getCount() { return mbtfriendList.size(); } @Override public Object getItem(int position) { return mbtfriendList.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { BTFriendViewHolder holder = null; if (convertView == null || ((BTFriendViewHolder) convertView.getTag()).flag != position) { holder = new BTFriendViewHolder(); convertView = LayoutInflater.from(context).inflate( R.layout.bottle_list_avatar_item, null); holder.flag = position; holder.mAuthorView = (RemoteImageView) convertView.findViewById(R.id.iv_author_photo); holder.mExType = (ImageView)convertView.findViewById(R.id.iv_bottle_type); holder.mExType.setVisibility(View.GONE); // content layout LinearLayout contentLayout = (LinearLayout) convertView .findViewById(R.id.feed_post_body); View view = LayoutInflater.from(context).inflate( R.layout.mygroupfriend_list_item, null); holder.mNickName = (TextView) view.findViewById(R.id.tv_onickname); holder.mSex = (ImageView)view.findViewById(R.id.bt_sex); holder.mDoing = (TextView) view.findViewById(R.id.tv_odoing); holder.mLocation = (TextView) view.findViewById(R.id.tv_olocation); contentLayout.addView(view); final MyFriendEntry myFriendEntry = (MyFriendEntry) getItem(position); try { holder.mAuthorView.setDefaultImage(R.drawable.avatar_default_big); holder.mAuthorView.setImageUrl(myFriendEntry.getFavatar()); } catch (Exception e) { e.printStackTrace(); holder.mAuthorView.setImageResource(R.drawable.avatar_default_big); } holder.mAuthorView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent spaceIntent = new Intent(context, UserSpaceActivity.class); spaceIntent.putExtra("ouid", myFriendEntry.getFuid()); context.startActivity(spaceIntent); } }); String nickName = "<font color='#0099FF'>" + myFriendEntry.getFnickname() + "</font>"; // String sex = (((myFriendEntry.getFsex()) == 1) ? ("(" // + TextUtil.R("login_txt_register_male") + ")") : ("(" // + TextUtil.R("login_txt_register_female") + ")")); holder.mNickName.setText(Html.fromHtml(nickName)); int sex_res = myFriendEntry.getFsex()== 1 ? R.drawable.male:R.drawable.female; holder.mSex.setBackgroundResource(sex_res); if (null != myFriendEntry.getFdoing() && myFriendEntry.getFdoing().length() > 0) { holder.mDoing.setVisibility(View.VISIBLE); String doingTips = "<font color='#000000'>" + TextUtil.R("friend_doing_tips") + "</font>"; holder.mDoing.setText(Html.fromHtml(doingTips + myFriendEntry.getFdoing())); } else { holder.mDoing.setVisibility(View.GONE); } if ((null != myFriendEntry.getFcountry() && myFriendEntry .getFcountry().length() > 0) || (null != myFriendEntry.getFcity() && myFriendEntry .getFcity().length() > 0)) { holder.mLocation.setVisibility(View.VISIBLE); String fromTips = "<font color='#000000'>" + TextUtil.R("friend_comfrom_tips") + "</font>"; holder.mLocation.setText(Html.fromHtml(fromTips + myFriendEntry.getFcity() + " " + myFriendEntry.getFcountry())); } else { holder.mLocation.setVisibility(View.GONE); } convertView.setTag(holder); } else { holder = (BTFriendViewHolder) convertView.getTag(); } return convertView; } public static class BTFriendViewHolder { public ImageView mSex; RemoteImageView mAuthorView; ImageView mExType; TextView mNickName; TextView mDoing; TextView mLocation; int flag; } }
Java
package com.outsourcing.bottle.adapter; import java.util.Collections; import java.util.List; import android.content.Context; import android.content.res.Resources.Theme; import android.content.res.TypedArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Gallery; import android.widget.ImageView; import android.widget.TextView; import com.outsourcing.bottle.R; public class TabAdapter extends BaseAdapter { private Context mContext; private List<String> mList; private int mSelectedTab; public TabAdapter(Context context, List<String> list) { mContext = context; /* attrs.xml <declare-styleable> */ Theme theme = mContext.getTheme(); TypedArray a = theme.obtainStyledAttributes(R.styleable.Gallery); a.recycle(); // styleable if (list == null) list = Collections.emptyList(); mList = list; } public void setSelectedTab(int tab) { if (tab != mSelectedTab) { mSelectedTab = tab; notifyDataSetChanged(); } } public int getSelectedTab() { return mSelectedTab; } public int getCount() { return Integer.MAX_VALUE; } public Object getItem(int position) { return mList.get(position); } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder = null; // TextView text = null; if (convertView == null) { viewHolder = new ViewHolder(); convertView = LayoutInflater.from(mContext).inflate(R.layout.gallery_item, null); viewHolder.tView = (TextView)convertView.findViewById(R.id.tv_title); viewHolder.iVMenu = (ImageView)convertView.findViewById(R.id.iv_menu); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.tView.setText(mList.get(position%mList.size())); convertView.setLayoutParams(new Gallery.LayoutParams(130, 40)); // text.setTextColor(Color.WHITE); // text.setText(mList.get(position % mList.size())); // text.setLayoutParams(new Gallery.LayoutParams(130, 40)); // text.setGravity(Gravity.CENTER); // if (position == mSelectedTab) { // text.setBackgroundResource(R.drawable.tab_button_select); // } else { // text.setBackgroundResource(R.drawable.tab_button_unselect); // } return convertView; } static class ViewHolder { public TextView tView; public ImageView iVMenu; } }
Java
package com.outsourcing.bottle.adapter; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.BaseAdapter; import android.widget.ImageView; import com.outsourcing.bottle.R; import com.outsourcing.bottle.domain.BottleLikeEntry; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.ImageLoader; public class GridLikeAdapter extends BaseAdapter{ private Context context; private List<BottleLikeEntry> arrayList; private ImageLoader imageLoader; public GridLikeAdapter(Context context, List<BottleLikeEntry> arrayList, AbsListView like_grid) { this.context = context; this.arrayList = arrayList; imageLoader = new ImageLoader(context, AppContext.BottleTimelineIcon); } @Override public int getCount() { return (null != arrayList && arrayList.size() > 0) ? arrayList .size() : 0; } @Override public Object getItem(int position) { return (null != arrayList && arrayList.size() > 0) ? arrayList .get(position) : null; } @Override public long getItemId(int position) { return 0; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView == null) { holder = new ViewHolder(); convertView = LayoutInflater.from(context).inflate( R.layout.bottle_like_avatar_listitem, null); holder.mheadView = (ImageView) convertView .findViewById(R.id.head_photo); holder.mLikeView = (ImageView) convertView .findViewById(R.id.like_photo); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } BottleLikeEntry item = (BottleLikeEntry) getItem(position); // holder.mheadView.setDefaultImage(R.drawable.avatar_default_small); // holder.mheadView.setImageUrl(item.getLike_avatar(), // AppContext.BottleTimelineIcon, position, like_grid); imageLoader.DisplayImage(item.getLike_avatar(), holder.mheadView, R.drawable.avatar_default_small); switch (item.getLike_type()) { case 1:// 喜欢 holder.mLikeView.setImageResource(R.drawable.like_red2); break; case 2:// 不喜欢 holder.mLikeView.setImageResource(R.drawable.like_black2); break; default: holder.mLikeView.setVisibility(View.GONE); break; } return convertView; } class ViewHolder { ImageView mheadView; ImageView mLikeView; } }
Java
package com.outsourcing.bottle.adapter; import java.io.File; import java.io.FileInputStream; import java.util.List; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.text.Html; import android.text.TextUtils; import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.RelativeLayout; import android.widget.TextView; import com.outsourcing.bottle.R; import com.outsourcing.bottle.db.BottleTypeTable; import com.outsourcing.bottle.domain.BottleEntry; import com.outsourcing.bottle.domain.BottleFeedEntry; import com.outsourcing.bottle.domain.BottleLikeEntry; import com.outsourcing.bottle.domain.BottleTypeEntry; import com.outsourcing.bottle.remoteimage.RemoteImageView; import com.outsourcing.bottle.ui.BottleDetailActivity; import com.outsourcing.bottle.ui.ChooseFriendActivity; import com.outsourcing.bottle.ui.ExpandEditActivity; import com.outsourcing.bottle.ui.HomeActivity; import com.outsourcing.bottle.ui.MapViewActivity; import com.outsourcing.bottle.ui.PhotoDetailActivity; import com.outsourcing.bottle.ui.UserSpaceActivity; import com.outsourcing.bottle.ui.fragment.BottleFragment; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.ImageLoader; import com.outsourcing.bottle.util.ServiceUtils; import com.outsourcing.bottle.util.TextUtil; import com.outsourcing.bottle.widget.CustomGridView; public class PublicActivityAdapter extends BaseAdapter { protected static final String TAG = "PublicActivityAdapter"; private HomeActivity context; private BottleFragment bottleFragment; private BottleTypeEntry entry = null; public static final String TEXT_FORMAT = "<font color='#1479ad'>%s</font> use Common net to gain Ms.faith's Memory Bottle <font color='#000'># 9 minutes ago</font>"; public static final String TEXT_THROW_TIPS = "<font color='#1479ad'>Tips:</font>"; public static final String TEXT_ADDFRD_FORMAT_WITHFROM = "<font color='#1479ad'>%s</font> 与 <font color='#1479ad'>%s</font> 成为了好友"; public static final String TEXT_ADDFRD_NOFROM = "与 <font color='#1479ad'><b>%s</b></font> 成为了好友"; private BottleTypeTable btt = null; private List<BottleEntry> msgs; // private BottleTimelineInfo bottleTimelineInfo; public ImageLoader imageLoader; private ImageLoader btConfigLoader; public boolean isHasHeader; public PublicActivityAdapter(HomeActivity context, BottleFragment bottleFragment, List<BottleEntry> msgs, boolean isHasHeader) { super(); this.isHasHeader = isHasHeader; this.context = context; this.bottleFragment = bottleFragment; this.msgs = msgs; imageLoader = new ImageLoader(context, AppContext.BottleTimelineIcon); btConfigLoader = new ImageLoader(context, AppContext.BOTTLE_CONFIG); btt = new BottleTypeTable(); } @Override public int getCount() { return msgs.size(); } @Override public Object getItem(int position) { return msgs.get(position); } @Override public long getItemId(int position) { return position; } ViewHolder holder = null; @Override public View getView(final int position, View convertView, ViewGroup parent) { if (convertView == null || ((ViewHolder) convertView.getTag()).flag != position) { holder = new ViewHolder(); holder.flag = position; // Item layout convertView = LayoutInflater.from(context).inflate(R.layout.bottle_list_avatar_item, null); // author img holder.mAuthorView = (RemoteImageView) convertView.findViewById(R.id.iv_author_photo); // bottle img holder.mBottleType = (ImageView) convertView.findViewById(R.id.iv_bottle_type); // content layout LinearLayout contentLayout = (LinearLayout) convertView.findViewById(R.id.feed_post_body); View view = LayoutInflater.from(context).inflate( R.layout.bottle_list_detail_item, null); holder.mNickname = (TextView) view.findViewById(R.id.tv_nickname); holder.mLocation = (TextView) view.findViewById(R.id.tv_location); holder.mTag = (TextView) view.findViewById(R.id.tv_tag); holder.mCopyTips = (TextView) view.findViewById(R.id.tv_copy_info); holder.mood = (TextView) view.findViewById(R.id.tv_mood); holder.mBottleContent = (RelativeLayout) view.findViewById(R.id.rl_bottle_content); holder.mMessage = (TextView) view.findViewById(R.id.tv_doing); // photo holder.mPhotoWrapper = (LinearLayout) view.findViewById(R.id.rl_bottle_content_photo); holder.mPhotoView = (ImageView) view.findViewById(R.id.photo); holder.bt_drawing = (Button)view.findViewById(R.id.bt_drawing); holder.bt_allow_draw = (Button)view.findViewById(R.id.bt_allow_draw); holder.mLockedPhotoLayout = (LinearLayout) view.findViewById(R.id.ll_bottle_photo_locked); holder.mLockedPhoto = (ImageView) view.findViewById(R.id.iv_locked_photo); holder.mLockedPhotoTip = (Button) view.findViewById(R.id.bt_locked_photo_tips); // 喜欢popup holder.mLikeLayout = (RelativeLayout) view.findViewById(R.id.comment_button_like); holder.mLikeIcon = (ImageView) view.findViewById(R.id.comment_button_like_icon); holder.mLikeText = (TextView) view.findViewById(R.id.comment_button_like_text); // 瓶子没打开的区域 holder.mUnopened_content = (LinearLayout) view.findViewById(R.id.ll_bottle_unopened_content); holder.mOpen_tips = (TextView) view.findViewById(R.id.tv_bottle_open_tips); holder.mOpen = (Button) view.findViewById(R.id.bt_bottle_open); holder.mDrop = (Button) view.findViewById(R.id.bt_bottle_drop); holder.mFeedComment = (RelativeLayout) view.findViewById(R.id.feed_comments); holder.mComment = (Button) view.findViewById(R.id.bt_bottle_comment); holder.mCopy = (Button) view.findViewById(R.id.bt_bottle_copy); holder.mForward = (Button) view.findViewById(R.id.bt_bottle_forward); holder.mLikeGrid = (CustomGridView) view.findViewById(R.id.ll_comment_like_grid); holder.line_grid = (View) view.findViewById(R.id.line_like_grid); holder.line_bt_comment = (View) view.findViewById(R.id.line_bt_comment); holder.mfeed_item_comment_more = (RelativeLayout) view.findViewById(R.id.feed_comments_more); holder.comments_ellipsis_text = (TextView) view.findViewById(R.id.comments_ellipsis_text); holder.mfeed_comment_layout = (LinearLayout) view.findViewById(R.id.ll_feed_comment_layout); holder.mOp_layout = (LinearLayout) view.findViewById(R.id.ll_botle_op); holder.mOpAvatar = (RemoteImageView)view.findViewById(R.id.bt_opavatar); holder.mOp_location = (LinearLayout) view.findViewById(R.id.ll_botle_op_location); holder.mFeedContent = (TextView) view.findViewById(R.id.tv_feed_content); holder.mOplocation = (TextView) view.findViewById(R.id.tv_oplocation); holder.mOpDistance = (TextView) view.findViewById(R.id.tv_distance); contentLayout.addView(view); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } try { final BottleEntry message = (BottleEntry) getItem(position); try { holder.mAuthorView.setDefaultImage(R.drawable.avatar_default_big); holder.mAuthorView.setImageUrl(message.getBt_avatar()); entry = btt.getBottleType(message.getBttypeid()); btConfigLoader.DisplayImage(entry.getBttype_sjdicon(), holder.mBottleType, R.drawable.bottle_type_1); } catch (Exception e) { e.printStackTrace(); holder.mAuthorView.setImageResource(R.drawable.avatar_default_big); } holder.mAuthorView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int ouid = message.getBt_uid(); Intent spaceIntent = new Intent(context, UserSpaceActivity.class); spaceIntent.putExtra("ouid", ouid); context.startActivity(spaceIntent); } }); holder.mBottleType.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bottleFragment.doSendSingleBtPri(message.getBttypeid(), message.getBtid()); } }); String nickName = null; String feed = (message.getBt_feed() != null && message.getBt_feed() .length() > 0) ? ("<font color='#000000'>" + message.getBt_feed() + "</font>") : ""; if (message.getBt_uid() != AppContext.getInstance().getLogin_uid()) { nickName = (message.getBt_nickname() != null && message .getBt_nickname().length() > 0) ? ("<font color='#DA4A37'>" + message.getBt_nickname() + "</font>") : ""; } else { nickName = (message.getBt_nickname() != null && message .getBt_nickname().length() > 0) ? ("<font color='#3F99D8'>" + message.getBt_nickname() + "</font>") : ""; } // holder.mNickname.setText(Html.fromHtml(nickName) + " " // + message.getBt_feed() + " " + Html.fromHtml(time)); holder.mNickname.setText(Html.fromHtml(nickName + feed)); if (!TextUtils.isEmpty(message.getBt_location())&& message.getBt_location().trim().length()>0) { holder.mLocation.setVisibility(View.VISIBLE); String time = (!TextUtils.isEmpty(message.getBt_time())) ? ("<font color='#666666'>"+ "#"+message.getBt_time() + "</font>") : ""; holder.mLocation.setText(Html.fromHtml(time+" @"+message.getBt_location())); if (message.getBt_showaddress() == 1 && message.getBt_open_drop_show() != 1) { holder.mLocation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent bottleDetailIntent = new Intent(context, BottleDetailActivity.class); bottleDetailIntent.putExtra("btid", message.getBtid()); bottleDetailIntent.putExtra("type", 2);// 1,LikeList2,location context.startActivity(bottleDetailIntent); } }); } } else { holder.mLocation.setVisibility(View.GONE); } if (!TextUtils.isEmpty(message.getBt_tag())) { holder.mTag.setVisibility(View.VISIBLE); String locationTips = "<font color='#DA4A37'>" + TextUtil.R("bottle_txt_location_tips") + "</font>"; holder.mTag.setText(Html.fromHtml(locationTips + TextUtil.htmlEncode(message.getBt_tag()))); } else { holder.mTag.setVisibility(View.GONE); } if (!TextUtils.isEmpty(message.getBt_copy_info())) { holder.mCopyTips.setVisibility(View.VISIBLE); String commentTips = "<font color='#DA4A37'>" + TextUtil.R("bottle_txt_forward_tips") + "</font>"; holder.mCopyTips.setText(Html.fromHtml(commentTips + TextUtil.htmlEncode(message.getBt_copy_info()))); } else { holder.mCopyTips.setVisibility(View.GONE); } if (!TextUtils.isEmpty(message.getBt_doing())) { holder.mood.setVisibility(View.VISIBLE); String moodTips = "<font color='#DA4A37'>" + TextUtil.R("bottle_txt_mood_tips") + "</font>"; holder.mood.setText(Html.fromHtml(moodTips + TextUtil.htmlEncode(message.getBt_doing()))); } else { holder.mood.setVisibility(View.GONE); } if (!TextUtils.isEmpty(message.getBt_content())) { String messageTips = "<font color='#DA4A37'>" + TextUtil.R("bottle_txt_copy_tips") + "</font>"; holder.mMessage.setVisibility(View.VISIBLE); holder.mMessage.setText(Html.fromHtml(messageTips + TextUtil.htmlEncode(message.getBt_content()))); } else { holder.mMessage.setVisibility(View.GONE); } if (!TextUtils.isEmpty(message.getBt_opfeed())) { holder.mOp_layout.setVisibility(View.VISIBLE); if (message.getBt_open_drop_show() != 1) { holder.mOp_layout .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent bottleDetailIntent = new Intent(context, BottleDetailActivity.class); bottleDetailIntent.putExtra("btid", message.getBtid()); bottleDetailIntent.putExtra("type", 2);// 1,LikeList2,location context.startActivity(bottleDetailIntent); } }); } try { holder.mOpAvatar.setDefaultImage(R.drawable.avatar_default_small); holder.mOpAvatar.setImageUrl(message.getBt_opavatar()); holder.mOpAvatar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent spaceIntent = new Intent(context, UserSpaceActivity.class); spaceIntent.putExtra("ouid", message.getBt_opuid()); context.startActivity(spaceIntent); } }); } catch (Exception e) { e.printStackTrace(); holder.mOpAvatar.setImageResource(R.drawable.avatar_default_small); } String onickName = (!TextUtils.isEmpty(message.getBt_opnickname())) ? ("<font color='#3F99D8'>" + message.getBt_opnickname() + "</font>") : ""; String otime = (!TextUtils.isEmpty(message.getBt_optime())) ? ( "#" + message.getBt_optime()) : ""; holder.mFeedContent.setText(Html.fromHtml(onickName + TextUtil.htmlEncode(message.getBt_opfeed()))); if (!TextUtils.isEmpty(message.getBt_oplocation())) { holder.mOp_location.setVisibility(View.VISIBLE); holder.mOplocation.setText(otime + " @"+message.getBt_oplocation()); holder.mOpDistance.setText(TextUtil.R("bottle_txt_comment_distance")+" "+message.getBt_opdistance()); } else { holder.mOp_location.setVisibility(View.GONE); } } else { holder.mOp_layout.setVisibility(View.GONE); } if (message.getBt_open_drop_show() == 1) { holder.mood.setVisibility(View.GONE); holder.mMessage.setVisibility(View.GONE); holder.mLikeLayout.setVisibility(View.GONE); holder.mBottleContent.setVisibility(View.GONE); holder.mUnopened_content.setVisibility(View.VISIBLE); holder.mOpen_tips.setText(TextUtil.R("bottle_txt_open_tips") + " " + message.getBt_nickname()); holder.mOpen.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bottleFragment.doOpenBottle(message.getBtid(), position); } }); holder.mDrop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bottleFragment.doDropBottle(message.getBtid(), position); } }); } else { if (message.getBt_showaddress() == 1) { holder.mTag.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent bottleDetailIntent = new Intent(context, BottleDetailActivity.class); bottleDetailIntent.putExtra("btid", message.getBtid()); bottleDetailIntent.putExtra("type", 2);// 1,LikeList2,location context.startActivity(bottleDetailIntent); } }); } holder.mood.setVisibility(View.VISIBLE); holder.mMessage.setVisibility(View.VISIBLE); holder.mLikeLayout.setVisibility(View.VISIBLE); holder.mUnopened_content.setVisibility(View.GONE); holder.mBottleContent.setVisibility(View.VISIBLE); if (!TextUtils.isEmpty(message.getBt_smallpic())) { if (message.getBt_pic_locked() == 0) { holder.mPhotoWrapper.setVisibility(View.VISIBLE); holder.mPhotoView.setVisibility(View.VISIBLE); holder.mLockedPhotoLayout.setVisibility(View.GONE); try { imageLoader.DisplayImage(message.getBt_smallpic(), holder.mPhotoView, R.drawable.album_nophoto); } catch (Exception e) { e.printStackTrace(); holder.mPhotoView.setImageResource(R.drawable.album_nophoto); } holder.mPhotoView .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { byte[] tempBytes = null; try { String filename = ServiceUtils.convertUrlToFileName(message.getBt_smallpic()); tempBytes = ServiceUtils.readStream(new FileInputStream(new File( android.os.Environment.getExternalStorageDirectory() + "/" + AppContext.BottleTimelineIcon + "/" + filename))); } catch (Exception e) { e.printStackTrace(); } Intent bigPicIntent = new Intent(context, PhotoDetailActivity.class); bigPicIntent.putExtra("pic_big", message.getBt_bigpic()); bigPicIntent.putExtra("thumbnail", tempBytes); context.startActivity(bigPicIntent); } }); if (message.getBt_allow_tuya() == 1) { holder.bt_drawing.setVisibility(View.VISIBLE); holder.bt_drawing.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bottleFragment.position = position; bottleFragment.btId = message.getBtid(); byte[] tempBytes = null; try { String filename = ServiceUtils.convertUrlToFileName(message.getBt_smallpic()); tempBytes = ServiceUtils.readStream(new FileInputStream(new File( android.os.Environment.getExternalStorageDirectory() + "/" + AppContext.BottleTimelineIcon + "/" + filename))); } catch (Exception e) { e.printStackTrace(); } Intent bigPicIntent = new Intent(context, PhotoDetailActivity.class); bigPicIntent.putExtra("pic_big", message.getBt_bigpic()); bigPicIntent.putExtra("thumbnail", tempBytes); bigPicIntent.putExtra("paintType", AppContext.PAINT_BT); bigPicIntent.putExtra("btid", message.getBtid()); bigPicIntent.putExtra("return_type",BottleFragment.class.getSimpleName()); bigPicIntent.putExtra("isToDraw", true); context.startActivity(bigPicIntent); } }); }else { holder.bt_drawing.setVisibility(View.GONE); } if (message.getBt_enable_tuya()== 0) { holder.bt_allow_draw.setVisibility(View.GONE); }else { holder.bt_allow_draw.setVisibility(View.VISIBLE); if (message.getBt_enable_tuya()== 1) { holder.bt_allow_draw.setBackgroundResource(R.drawable.btn_red_try); holder.bt_allow_draw.setText(TextUtil.R("bottle_txt_allow_draw")); holder.bt_allow_draw.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bottleFragment.doPicPaint(message.getBtid(), 1); } }); }else { holder.bt_allow_draw.setBackgroundResource(R.drawable.btn_gray_try); holder.bt_allow_draw.setText(TextUtil.R("bottle_txt_not_allow_draw")); holder.bt_allow_draw.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bottleFragment.doPicPaint(message.getBtid(), 0); } }); } } } else { holder.mLockedPhotoLayout.setVisibility(View.VISIBLE); holder.mPhotoWrapper.setVisibility(View.GONE); holder.mPhotoView.setVisibility(View.GONE); holder.mLockedPhotoTip .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent unLockPhotoIntent = new Intent(context, ExpandEditActivity.class); AppContext.getInstance().setFromBottleTime(true); Bundle unLockBundle = new Bundle(); unLockBundle.putString("from_type", AppContext.REPLY_BT); unLockBundle.putInt("bttype_id", message.getBtid()); unLockPhotoIntent.putExtras(unLockBundle); context.startActivity(unLockPhotoIntent); } }); } } else { holder.mPhotoWrapper.setVisibility(View.GONE); holder.mPhotoView.setVisibility(View.GONE); holder.mLockedPhotoLayout.setVisibility(View.GONE); } if (null != message.getBtlikes_list()) { holder.mLikeLayout.setVisibility(View.VISIBLE); if (message.getBt_liked() == 0) { holder.mLikeText.setTextColor(context.getResources().getColor(R.color.gray)); holder.mLikeLayout.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.photo_pill)); holder.mLikeIcon.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.like_gray2)); // .setBackgroundResource(R.drawable.like_gray2); } else if (message.getBt_liked() == 1) { holder.mLikeText.setTextColor(context.getResources().getColor(R.color.gray)); holder.mLikeLayout.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.photo_pill)); holder.mLikeIcon.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.like_red2)); // .setBackgroundResource(R.drawable.like_red2); } else if (message.getBt_liked() == 2) { holder.mLikeText.setTextColor(context.getResources().getColor(R.color.gray)); holder.mLikeLayout.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.photo_pill)); holder.mLikeIcon.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.like_black2)); // .setBackgroundResource(R.drawable.like_black2); } if (message.getBt_like_enable() == 1) { holder.mLikeText.setTextColor(context.getResources().getColor(R.color.gray)); holder.mLikeLayout.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.photo_pill)); holder.mLikeLayout .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bottleFragment.showInfoPopupWindow(v, message.getBtid(), holder, position); } }); } else { holder.mLikeText.setTextColor(context.getResources().getColor(R.color.white)); holder.mLikeLayout.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.photo_pill_dark)); } if (message.getBtlikes_count() == 0) { holder.mLikeText.setVisibility(View.GONE); } else { holder.mLikeText.setVisibility(View.VISIBLE); holder.mLikeText.setText(message.getBtlikes_count() + ""); } } else { holder.mLikeLayout.setVisibility(View.GONE); } holder.mComment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bottleFragment.position = position; bottleFragment.btId = message.getBtid(); Intent commentIntent = new Intent(context, ExpandEditActivity.class); AppContext.getInstance().setFromBottleTime(true); Bundle commentBundle = new Bundle(); commentBundle.putString("from_type", AppContext.REPLY_BT); commentBundle.putInt("bttype_id", message.getBtid()); commentIntent.putExtras(commentBundle); context.startActivity(commentIntent); } }); if (message.getBt_copy_enable() == 1) { holder.mCopy.setVisibility(View.VISIBLE); holder.mCopy.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { bottleFragment.position = position; bottleFragment.btId = message.getBtid(); Intent copyIntent = new Intent(context, ExpandEditActivity.class); AppContext.getInstance().setFromBottleTime(true); Bundle copyBundle = new Bundle(); copyBundle.putString("from_type", AppContext.COPYMANUAL_BT); copyBundle.putInt("bttype_id", message.getBtid()); copyIntent.putExtras(copyBundle); context.startActivity(copyIntent); } }); } else { holder.mCopy.setVisibility(View.INVISIBLE); } if (message.getBt_allow_spread() == 1) { holder.mForward.setVisibility(View.VISIBLE); holder.mForward.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final Context dialogContext = new ContextThemeWrapper(context, android.R.style.Theme_Light); bottleFragment.position = position; bottleFragment.btId = message.getBtid(); String[] choices = new String[2]; choices[0] = context.getString(R.string.bottle_txt_forward_to_friend); choices[1] = context.getString(R.string.bottle_txt_forward_to_platform); final ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (which == 0) { Intent forwardIntent = new Intent(context, ChooseFriendActivity.class); Bundle forwardBundle = new Bundle(); forwardBundle.putInt("choose_friend_type", AppContext.CHOOSE_FRIEND_FORWARD_BOTTLE_TYPE); forwardBundle.putInt("bttype_id", message.getBtid()); forwardBundle.putString("return_type", BottleFragment.class.getSimpleName()); forwardIntent.putExtras(forwardBundle); context.startActivity(forwardIntent); } else { Intent forwardIntent = new Intent(context, ExpandEditActivity.class); AppContext.getInstance().setFromBottleTime(true); Bundle forwardBundle = new Bundle(); forwardBundle.putString("from_type", AppContext.TRANSMIT_BT); forwardBundle.putInt("bttype_id", message.getBtid()); forwardIntent.putExtras(forwardBundle); context.startActivity(forwardIntent); } } }); builder.create().show(); } }); } else { holder.mForward.setVisibility(View.INVISIBLE); } if (null != message.getBtlikes_list() && message.getBtlikes_list().size() > 0) { holder.mLikeGrid.setVisibility(View.VISIBLE); holder.line_grid.setVisibility(View.VISIBLE); final GridLikeAdapter gridAdapter = new GridLikeAdapter( context, message.getBtlikes_list(), holder.mLikeGrid); holder.mLikeGrid.setAdapter(gridAdapter); holder.mLikeGrid .setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { BottleLikeEntry btLike = (BottleLikeEntry) gridAdapter.getItem(position); Intent spaceIntent = new Intent(context, UserSpaceActivity.class); spaceIntent.putExtra("ouid", btLike.getLike_uid()); context.startActivity(spaceIntent); } }); } else { holder.mLikeGrid.setVisibility(View.GONE); holder.line_grid.setVisibility(View.GONE); } if (message.getBtfeeds_count() > 0) { holder.line_bt_comment.setVisibility(View.VISIBLE); holder.mfeed_item_comment_more.setVisibility(View.VISIBLE); holder.mfeed_item_comment_more .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent bottleDetailIntent = new Intent(context, BottleDetailActivity.class); bottleDetailIntent.putExtra("btid", message.getBtid()); bottleDetailIntent.putExtra("type", 1);// 2,location context.startActivity(bottleDetailIntent); } }); holder.comments_ellipsis_text.setText(message .getBtfeeds_count()+" " + TextUtil.R("bottle_txt_comment_more")); } else { holder.mfeed_item_comment_more.setVisibility(View.GONE); holder.line_bt_comment.setVisibility(View.INVISIBLE); } if (message.getBtfeeds_count() > 0) { holder.mfeed_comment_layout.setVisibility(View.VISIBLE); holder.mfeed_comment_layout.removeAllViews(); for (int i = 0; i < message.getBtfeeds_list().size(); i++) { final BottleFeedEntry btFeedEntry = message.getBtfeeds_list().get(i); View mCommentView = LayoutInflater.from(context).inflate( R.layout.feed_comments_item, null); if (i == (message.getBtfeeds_list().size()-1)) { View feed_avatar = (View) mCommentView .findViewById(R.id.line_bttimeline_feed); feed_avatar.setVisibility(View.INVISIBLE); } mCommentView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent bottleDetailIntent = new Intent(context, BottleDetailActivity.class); bottleDetailIntent.putExtra("btid", message.getBtid()); bottleDetailIntent.putExtra("type", 1);// 1,LikeList2,location context.startActivity(bottleDetailIntent); } }); RemoteImageView feed_avatar = (RemoteImageView) mCommentView.findViewById(R.id.comment_profile_photo); if (!TextUtils.isEmpty(btFeedEntry.getFeed_avatar())) { try { feed_avatar.setDefaultImage(R.drawable.avatar_default_small); feed_avatar.setImageUrl(btFeedEntry.getFeed_avatar()); feed_avatar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent spaceIntent = new Intent(context, UserSpaceActivity.class); spaceIntent.putExtra("ouid", btFeedEntry.getFeed_uid()); context.startActivity(spaceIntent); } }); } catch (Exception e) { e.printStackTrace(); feed_avatar.setImageResource(R.drawable.avatar_default_small); } } // ImageView comment_link = (ImageView) mCommentView // .findViewById(R.id.iv_feed_comment_white); // if (btFeedEntry.getFeed_type() == 0) { // comment_link.setVisibility(View.VISIBLE); // } else { // comment_link.setVisibility(View.GONE); // } TextView comment_nickname = (TextView) mCommentView .findViewById(R.id.tv_feed_comment_nickname); String feed_name = null; if ((!TextUtils.isEmpty(btFeedEntry.getFeed_nickname()))|| (!TextUtils.isEmpty(btFeedEntry.getFeed_content()))) { if (btFeedEntry.getFeed_uid() != AppContext.getInstance() .getLogin_uid()) { feed_name = "<font color='#DA4A37'>" + btFeedEntry.getFeed_nickname() + "</font>"; } else { feed_name = "<font color='#3F99D8'>" + btFeedEntry.getFeed_nickname() + "</font>"; } String feed_content = btFeedEntry.getFeed_isnew()==1?("<font color='#DA4A37'>" + TextUtil.htmlEncode(btFeedEntry.getFeed_content()) + "</font>"):TextUtil.htmlEncode(btFeedEntry.getFeed_content()); try { comment_nickname.setText(Html.fromHtml(feed_name + " " + feed_content)); } catch (Exception e) { e.printStackTrace(); } } TextView comment_time = (TextView) mCommentView .findViewById(R.id.tv_feed_comment_time); if ((!TextUtils.isEmpty(btFeedEntry.getFeed_time())) || (!TextUtils.isEmpty(btFeedEntry.getFeed_location()))) { String timeComent = (!TextUtils.isEmpty(btFeedEntry.getFeed_time())) ? ("#" + btFeedEntry.getFeed_time()): ""; String location = (!TextUtils.isEmpty(btFeedEntry.getFeed_location())) ? ("@" + btFeedEntry.getFeed_location()): ""; comment_time.setText(timeComent+" "+location); if (!TextUtils.isEmpty(location)) { comment_time.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { final Context dialogContext = new ContextThemeWrapper(context, android.R.style.Theme_Light); String[] choices = new String[1]; choices[0] = context.getString(R.string.bottle_txt_check_location); final ListAdapter adapter = new ArrayAdapter<String>( dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems( adapter, -1, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { dialog.dismiss(); if (which == 0) { Intent intent = new Intent(context,MapViewActivity.class); intent.putExtra( "longitude",btFeedEntry.getFeed_lng()); intent.putExtra( "latidute",btFeedEntry.getFeed_lat()); intent.putExtra( "location",btFeedEntry.getFeed_location()); context.startActivity(intent); } } }); builder.create().show(); } }); } } RelativeLayout rl_bottle_comment_photo = (RelativeLayout)mCommentView.findViewById(R.id.rl_bottle_comment_photo); if (!TextUtils.isEmpty(btFeedEntry.getFeed_commentpic())) { rl_bottle_comment_photo.setVisibility(View.VISIBLE); ImageView feed_commentpic = (ImageView)mCommentView.findViewById(R.id.feed_comment_pic); try { imageLoader.DisplayImage(btFeedEntry.getFeed_commentpic(),feed_commentpic, R.drawable.album_nophoto); feed_commentpic .setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!TextUtils.isEmpty(btFeedEntry .getFeed_commentpic_tuya())) { showCommentPicFeedDialog(btFeedEntry); } else { byte[] tempBytes = null; try { String filename = ServiceUtils .convertUrlToFileName(btFeedEntry .getFeed_commentpic()); tempBytes = ServiceUtils .readStream(new FileInputStream( new File( android.os.Environment .getExternalStorageDirectory() + "/" + AppContext.BottleTimelineIcon + "/" + filename))); } catch (Exception e) { e.printStackTrace(); } Intent bigPicIntent = new Intent(context, PhotoDetailActivity.class); bigPicIntent.putExtra("pic_big",btFeedEntry.getFeed_commentpic_big()); bigPicIntent.putExtra("thumbnail", tempBytes); context.startActivity(bigPicIntent); } } }); } catch (Exception e) { e.printStackTrace(); feed_commentpic.setImageResource(R.drawable.album_nophoto); } }else { rl_bottle_comment_photo.setVisibility(View.GONE); } TextView tv_feed_replycomment = (TextView)mCommentView.findViewById(R.id.tv_feed_replycomment); if (!TextUtils.isEmpty(btFeedEntry.getFeed_replycomment())) { tv_feed_replycomment.setVisibility(View.VISIBLE); tv_feed_replycomment.setText(btFeedEntry.getFeed_replycomment()); } else { tv_feed_replycomment.setVisibility(View.GONE); } holder.mfeed_comment_layout.addView(mCommentView); } } else { holder.mfeed_comment_layout.setVisibility(View.GONE); } } } catch (Exception e) { e.printStackTrace(); } return convertView; } private void showCommentPicFeedDialog(final BottleFeedEntry message) { String[] choices = new String[]{TextUtil.R("bottle_txt_feed_comment_pic"),TextUtil.R("bottle_txt_feed_comment_tuya")}; final Context dialogContext = new ContextThemeWrapper(context, android.R.style.Theme_Light); final ListAdapter adapter = new ArrayAdapter<String>(dialogContext, android.R.layout.simple_list_item_1, choices); final AlertDialog.Builder builder = new AlertDialog.Builder( dialogContext); builder.setTitle(R.string.system_info); builder.setSingleChoiceItems(adapter, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (which == 0) { byte[] tempBytes = null; try { String filename = ServiceUtils.convertUrlToFileName(message.getFeed_commentpic()); tempBytes = ServiceUtils.readStream(new FileInputStream(new File( android.os.Environment.getExternalStorageDirectory() + "/" + AppContext.BottleTimelineIcon + "/" + filename))); } catch (Exception e) { e.printStackTrace(); } Intent bigPicIntent = new Intent(context, PhotoDetailActivity.class); bigPicIntent.putExtra("pic_big", message.getFeed_commentpic_big()); bigPicIntent.putExtra("thumbnail", tempBytes); context.startActivity(bigPicIntent); } else { Intent bigPicIntent = new Intent(context, PhotoDetailActivity.class); bigPicIntent.putExtra("pic_big", message.getFeed_commentpic_tuya()); context.startActivity(bigPicIntent); } } }); builder.create().show(); } public static class ViewHolder { public View line_grid; public View line_bt_comment; TextView text; TextView time; TextView status; int btId; int btTypeId; String btBigPic; int ouid; String nickname; public RemoteImageView mAuthorView;// 用户头像 public ImageView mBottleType;// 瓶子类型 public TextView mNickname;// 扔瓶子用户昵称 // public TextView mFeed;// 扔瓶子、传递瓶子动态 // public TextView mTime;// 扔瓶子时间 public TextView mLocation;// 瓶子地点 public TextView mDistance;// 瓶子距离 public TextView mTag;// 瓶子标签 public TextView mCopyTips;// 传递信息(显示在瓶子标签下边) public TextView mood;// 瓶子心情 public RelativeLayout mBottleContent;// 显示瓶子的内容 public TextView mMessage;// public LinearLayout mPhotoWrapper;// photo外套 public ImageView mPhotoView;// 瓶子内涵图 public LinearLayout mLockedPhotoLayout;// 被锁图片内容区 public ImageView mLockedPhoto;// 上锁的瓶子图 public Button mLockedPhotoTip;// 上传图片解锁 public Button bt_drawing;//涂鸦 public Button bt_allow_draw;//允许涂鸦 public LinearLayout mUnopened_content;// 瓶子没打开时 public TextView mOpen_tips; public Button mOpen; public Button mDrop; public RelativeLayout mLikeLayout; public ImageView mLikeIcon;// 喜欢 public TextView mLikeText;// 喜欢数量 public CustomGridView mLikeGrid;// 喜欢头像区域 public RelativeLayout mFeedComment;// 回复区域 public Button mComment;// public Button mCopy;// public Button mForward;// public RelativeLayout mfeed_item_comment_more;// 查看更多留言 public TextView comments_ellipsis_text;// public LinearLayout mfeed_comment_layout;// 留言 public RelativeLayout rl_bottle_comment_photo; public ImageView feed_comment_pic; public LinearLayout mOp_layout;// 我收到的这个瓶子的动态,不是我收到的瓶子不显示 public RemoteImageView mOpAvatar; public LinearLayout mOp_location; public TextView mFeedContent; public TextView mOplocation; public TextView mOpDistance; int flag = -1; } }
Java
package com.outsourcing.bottle.adapter; import java.util.List; import android.content.Context; import android.content.Intent; import android.text.Html; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.outsourcing.bottle.R; import com.outsourcing.bottle.db.BottleTypeTable; import com.outsourcing.bottle.domain.BottleFriendEntry; import com.outsourcing.bottle.domain.BottleTypeEntry; import com.outsourcing.bottle.remoteimage.RemoteImageView; import com.outsourcing.bottle.ui.BottleDetailActivity; import com.outsourcing.bottle.ui.UserSpaceActivity; import com.outsourcing.bottle.ui.fragment.FriendFragment; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.ImageLoader; import com.outsourcing.bottle.util.TextUtil; public class BTFriendListAdapter extends BaseAdapter { private Context context = null; private List<BottleFriendEntry> mbtfriendList = null; private BottleTypeEntry entry = null; private BottleTypeTable btt = null; private FriendFragment fragment; private ImageLoader btConfigLoader; public BTFriendListAdapter(Context context,FriendFragment fragment, List<BottleFriendEntry> mbtfriendList) { this.context = context; this.fragment = fragment; this.mbtfriendList = mbtfriendList; btConfigLoader = new ImageLoader(context, AppContext.BOTTLE_CONFIG); btt = new BottleTypeTable(); } @Override public int getCount() { return mbtfriendList==null?0:mbtfriendList.size(); } @Override public Object getItem(int position) { return mbtfriendList==null?null:mbtfriendList.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { BTFriendViewHolder holder = null; if (convertView == null || ((BTFriendViewHolder) convertView.getTag()).flag != position) { holder = new BTFriendViewHolder(); convertView = LayoutInflater.from(context).inflate( R.layout.bottle_list_avatar_item, null); holder.flag = position; holder.mAuthorView = (RemoteImageView) convertView .findViewById(R.id.iv_author_photo); holder.mBtType = (ImageView)convertView.findViewById(R.id.iv_bottle_type); // content layout LinearLayout contentLayout = (LinearLayout) convertView .findViewById(R.id.feed_post_body); View view = LayoutInflater.from(context).inflate( R.layout.friend_list_detail_item, null); holder.mNickName = (TextView) view.findViewById(R.id.tv_nickname); holder.mSex = (ImageView)view.findViewById(R.id.bt_sex); holder.mDoing = (TextView) view.findViewById(R.id.tv_doing); holder.mLocation = (TextView) view.findViewById(R.id.tv_location); holder.mTag = (TextView) view.findViewById(R.id.tv_tag); holder.mDistance = (TextView)view.findViewById(R.id.tv_distance); holder.mFriendLocation = (LinearLayout)view.findViewById(R.id.ll_friend_location); holder.mCommentLocation = (TextView) view .findViewById(R.id.tv_comment_location); holder.mbtExPhoto = (Button) view .findViewById(R.id.bt_exchange_photo); holder.mbtExProfile = (Button) view .findViewById(R.id.bt_exchange_profile); contentLayout.addView(view); convertView.setTag(holder); } else { holder = (BTFriendViewHolder) convertView.getTag(); } final BottleFriendEntry btFriendEntry = (BottleFriendEntry) getItem(position); try { holder.mAuthorView.setDefaultImage(R.drawable.avatar_default_big); holder.mAuthorView.setImageUrl(btFriendEntry.getBtf_avatar()); } catch (Exception e) { e.printStackTrace(); holder.mAuthorView .setImageResource(R.drawable.avatar_default_big); } holder.mAuthorView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent spaceIntent = new Intent(context, UserSpaceActivity.class); spaceIntent.putExtra("ouid", btFriendEntry.getBtf_uid()); context.startActivity(spaceIntent); } }); try { entry = btt.getBottleType(btFriendEntry.getBttypeid()); btConfigLoader.DisplayImage(entry.getBttype_sjwicon(), holder.mBtType, R.drawable.bottle_type_1); } catch (Exception e) { e.printStackTrace(); holder.mBtType.setImageResource(R.drawable.bottle_type_1); } holder.mBtType.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fragment.doSendSingleBtPri(btFriendEntry.getBttypeid(), btFriendEntry.getBtid()); } }); String nickName = "<font color='#3F99D8'>"+ btFriendEntry.getBtf_nickname()+ "</font>"; // String sex = (((btFriendEntry.getBtf_sex())==1)?("("+TextUtil.R("login_txt_register_male")+")"):("("+TextUtil.R("login_txt_register_female")+")")); holder.mNickName.setText(Html.fromHtml(nickName)); int sex_res = btFriendEntry.getBtf_sex() == 1 ? R.drawable.male:R.drawable.female; holder.mSex.setBackgroundResource(sex_res); if (!TextUtils.isEmpty(btFriendEntry.getBtf_doing())) { holder.mDoing.setVisibility(View.VISIBLE); String doingTips ="<font color='#000000'>" +TextUtil.R("friend_doing_tips") + "</font>"; holder.mDoing.setText(Html.fromHtml(doingTips+btFriendEntry.getBtf_doing())); }else { holder.mDoing.setVisibility(View.GONE); } if ((!TextUtils.isEmpty(btFriendEntry.getBtf_country()))||(!TextUtils.isEmpty(btFriendEntry.getBtf_city()))) { holder.mLocation.setVisibility(View.VISIBLE); String fromTips =TextUtil.R("friend_comfrom_tips"); holder.mLocation.setText(fromTips+btFriendEntry.getBtf_city()+" "+btFriendEntry.getBtf_country()); }else { holder.mLocation.setVisibility(View.GONE); } String feedNickName = "<font color='#3F99D8'>"+ btFriendEntry.getFeed_nickname()+ "</font>"; String feedTime = (null!=btFriendEntry.getFeed_time()&&btFriendEntry.getFeed_time().length()>0)? ("<font color='#000000'>"+" #"+btFriendEntry.getFeed_time()+ "</font>"):""; holder.mTag.setText(Html.fromHtml(feedNickName+":"+btFriendEntry.getFeed_content()+feedTime)); if (!TextUtils.isEmpty(btFriendEntry.getFeed_location())) { holder.mFriendLocation.setVisibility(View.VISIBLE); holder.mCommentLocation.setText(btFriendEntry.getFeed_location()); holder.mCommentLocation.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent bottleDetailIntent = new Intent(context, BottleDetailActivity.class); bottleDetailIntent.putExtra("btid", btFriendEntry.getBtid()); bottleDetailIntent.putExtra("type", 1);// 1,LikeList2,location context.startActivity(bottleDetailIntent); } }); String distance = (null!=btFriendEntry.getFeed_distance()&&btFriendEntry.getFeed_distance().length()>0)? ("<font color='#000000'>"+btFriendEntry.getFeed_distance()+ "</font>"):""; holder.mDistance.setText(Html.fromHtml(TextUtil.R("friend_distance")+" "+distance)); }else { holder.mFriendLocation.setVisibility(View.GONE); } if (btFriendEntry.getBtf_isfriend()==1) { holder.mbtExProfile.setText(TextUtil.R("friend_whose_profile")); holder.mbtExPhoto.setText(TextUtil.R("friend_whose_photo")); holder.mbtExProfile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context,UserSpaceActivity.class); intent.putExtra("ouid", btFriendEntry.getBtf_uid()); context.startActivity(intent); } }); holder.mbtExPhoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fragment.doVisitAlbum(btFriendEntry.getBtf_uid()); } }); }else{ holder.mbtExProfile.setText(TextUtil.R("friend_exchange_profile")); holder.mbtExPhoto.setText(TextUtil.R("friend_exchange_photo")); holder.mbtExProfile.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fragment.doExchange(AppContext.CHOOSE_FRIEND_EXCHANGE_INFO_TYPE,btFriendEntry.getBtf_uid()); } }); holder.mbtExPhoto.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { fragment.doExchange(AppContext.CHOOSE_FRIEND_EXCHANGE_PHOTO_TYPE,btFriendEntry.getBtf_uid()); } }); } return convertView; } public static class BTFriendViewHolder { public ImageView mSex; RemoteImageView mAuthorView; ImageView mBtType; ImageView mExType; TextView mNickName; TextView mDoing; TextView mLocation; TextView mTag; TextView mCommentLocation; TextView mDistance; Button mbtExPhoto; Button mbtExProfile; LinearLayout mFriendLocation; int flag; } }
Java
package com.outsourcing.bottle.adapter; import java.util.ArrayList; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.outsourcing.bottle.R; import com.outsourcing.bottle.ui.JavaTestActivity; public class TestCustomAdapter extends BaseAdapter{ private JavaTestActivity context; private ArrayList<ArrayList<String>> arrayList; public TestCustomAdapter(JavaTestActivity context,ArrayList<ArrayList<String>> arrayList){ this.context = context; this.arrayList = arrayList; } @Override public int getCount() { return arrayList.size(); } @Override public Object getItem(int position) { return arrayList.get(position); } @Override public long getItemId(int position) { return 0; } @SuppressWarnings("unchecked") @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder holder = null; if (convertView==null) { holder = new ViewHolder(); convertView = LayoutInflater.from(context).inflate(R.layout.address_fragment_listitem, null); holder.layout = (LinearLayout)convertView.findViewById(R.id.layout); holder.iView = (ImageView) convertView.findViewById(R.id.address_portrait); holder.rightView = (ImageView)convertView.findViewById(R.id.address_call); holder.textNum = (TextView)convertView.findViewById(R.id.contact_job); convertView.setTag(holder); }else { holder = (ViewHolder) convertView.getTag(); } ArrayList<String> item = (ArrayList<String>)getItem(position); TextView textView = null; holder.layout.removeAllViews(); for (int i = 0; i < item.size(); i++) { textView = new TextView(context); textView.setText(item.get(i)); holder.layout.addView(textView); } holder.textNum.setText(item.size()+""); holder.iView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // popupWindowMyWork.showAsDropDown(v,50,-50); // popupWindowMyWork.showAtLocation(v,Gravity.RIGHT|Gravity.BOTTOM, 10,10); // QuickAction3D quickAction = new QuickAction3D(context, QuickAction3D.HORIZONTAL); // Toast.makeText(context,"position:"+position+" item:"+getItem(position), Toast.LENGTH_SHORT).show(); } }); holder.rightView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { context.refreshItem(position); } }); return convertView; } class ViewHolder{ LinearLayout layout; ImageView iView; TextView textNum; ImageView rightView; } }
Java
package com.outsourcing.bottle.adapter; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.outsourcing.bottle.R; import com.outsourcing.bottle.domain.BottleFeedListEntry; import com.outsourcing.bottle.remoteimage.RemoteImageView; import com.outsourcing.bottle.util.AppContext; import com.outsourcing.bottle.util.ImageLoader; public class BottleDetailFeedAdapter extends BaseAdapter { protected static final String TAG = "PublicActivityAdapter"; private Context context; private List<BottleFeedListEntry> msgs; public ImageLoader imageLoader; public BottleDetailFeedAdapter(Context context, List<BottleFeedListEntry> msgs) { super(); this.context = context; this.msgs = msgs; imageLoader = new ImageLoader(context, AppContext.BottleTimelineIcon); } @Override public int getCount() { return (msgs!=null&&msgs.size()>0)?msgs.size():0; } @Override public Object getItem(int position) { return (msgs!=null&&msgs.size()>0)?msgs.get(position):null; } @Override public long getItemId(int position) { return position; } BottleDetailViewHolder holder; @Override public View getView(final int position, View convertView, ViewGroup parent) { if (convertView == null) { holder = new BottleDetailViewHolder(); // Item layout convertView = LayoutInflater.from(context).inflate( R.layout.bottle_comment_list_detail_item, null); holder.mAuthorView = (RemoteImageView) convertView.findViewById(R.id.comment_profile_photo); holder.mLink = (ImageView)convertView.findViewById(R.id.iv_feed_comment_white); holder.mfeedContent = (TextView) convertView.findViewById(R.id.tv_comment_feed_content); holder.mfeedReplyComment = (TextView)convertView.findViewById(R.id.tv_comment_feed_reply); holder.mfeedReplyPhoto = (ImageView)convertView.findViewById(R.id.photo); convertView.setTag(holder); } else { holder = (BottleDetailViewHolder) convertView.getTag(); } final BottleFeedListEntry message = (BottleFeedListEntry) getItem(position); holder.mAuthorView.setDefaultImage(R.drawable.avatar_default_small); holder.mAuthorView.setImageUrl(message.getFeed_avatar()); holder.mfeedContent.setText(message.getFeed_nickname()+" "+message.getFeed_content()+" "+message.getFeed_time()+" @"+message.getFeed_location()); if (null!=message.getFeed_replycomment()&&message.getFeed_replycomment().length()>0) { holder.mfeedReplyComment.setVisibility(View.VISIBLE); holder.mfeedReplyComment.setText(message.getFeed_replycomment()); }else { holder.mfeedReplyComment.setVisibility(View.GONE); } if (null!=message.getFeed_commentpic()&&message.getFeed_commentpic().length()>0) { holder.mfeedReplyPhoto.setVisibility(View.VISIBLE); imageLoader.DisplayImage(message.getFeed_commentpic(), holder.mfeedReplyPhoto, R.drawable.avatar_default_small); }else { holder.mfeedReplyPhoto.setVisibility(View.GONE); } return convertView; } public class BottleDetailViewHolder { public RemoteImageView mAuthorView;// 用户头像 public ImageView mLink;//白色的小锁图片 不知道干嘛用的 public TextView mfeedContent;// 回复内容 public LinearLayout mfeedReplyCommentLayout; public TextView mfeedReplyComment;// public ImageView mfeedReplyPhoto; } }
Java
package com.outsourcing.bottle.adapter; import java.util.List; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.outsourcing.bottle.R; import com.outsourcing.bottle.domain.GroupFriendEntry; import com.outsourcing.bottle.ui.HomeActivity; import com.outsourcing.bottle.ui.fragment.FriendFragment; public class GroupFriendAdapter extends BaseAdapter { public FriendFragment fragment; private HomeActivity contact; private List<GroupFriendEntry> groups_list; public GroupFriendAdapter(FriendFragment fragment, HomeActivity contact, List<GroupFriendEntry> groups_list) { super(); this.fragment = fragment; this.contact = contact; this.groups_list = groups_list; } @Override public int getCount() { return groups_list.size(); } @Override public Object getItem(int position) { return groups_list.get(position); } @Override public long getItemId(int position) { return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(contact).inflate( R.layout.list_myfriend_group_item, null); } TextView tv = (TextView) convertView.findViewById(R.id.name); tv.setText(((GroupFriendEntry) getItem(position)).getGroupname()); return convertView; } }
Java