JSON Parsing in android
This tutorial used to featch the title and his image from server. And I also include pagination in this post To make two java class ServiceHandler.java
and ImageFragment.java
ImageFragment.java
public class ImageFragment extends Fragment implements AdapterView.OnItemClickListener, XListView.IXListViewListener {
String url;
final int type=1,category_id=4;
ProgressDialog pd;
ArrayList<HashMap<String, String>> arr_image;
ImageAdaper imageAdaper;
ListView list_image;
String imageId;
int pagenumber=1;
private XListView mListView;
private ArrayAdapter<String> mAdapter;
private ArrayList<String> items = new ArrayList<String>();
private ArrayList<String> iamge_array = new ArrayList<String>();
private ArrayList<String> image_id = new ArrayList<String>();
private Handler mHandler;
private int start = 0;
private static int refreshCnt = 0;
int lastValueSize;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_image, container, false);
mListView = (XListView) view.findViewById(R.id.list_image);
mListView.setPullLoadEnable(true);
mListView.setXListViewListener(this);
mListView.setOnItemClickListener(this);
mHandler = new Handler();
geneItems();
MainActivity.image_refrace.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/*SharedPreferences.Editor editor = getActivity().getSharedPreferences("MyPref", getActivity().MODE_PRIVATE).edit();
editor.putString("listsize", "1");
editor.commit();*/
items.clear();
iamge_array.clear();
mListView.setSelection(0);
// news_id.clear();
int pagenumber = 1;
// Toast.makeText(getApplicationContext(),"News",Toast.LENGTH_SHORT).show();
if (isOnline()) {
url= Appconstant.TAG_BaseUrl + Appconstant.TAG_Method_GetDynamicPost + Appconstant.TAG_Method_GetDynamicPost_CategoryId
+ category_id + Appconstant.TAG_Method_GetDynamicPost_Type
+ type + Appconstant.TAG_Method_GetDynamicPost_PageNumber + pagenumber;
new listAs().execute(url);
} else {
CheckInternet();
}
}
});
return view;
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//imageId=arr_image.get(position).get(Appconstant.TAG_GetDynamicPost_Image_ID);
String imageId=image_id.get(position-1);
Intent intent=new Intent(getActivity(),DetailImage.class);
intent.putExtra("Image ID",imageId);
startActivity(intent);
getActivity().overridePendingTransition(R.anim.open_next, R.anim.close_next);
}
private void geneItems(){
if (isOnline()) {
url= Appconstant.TAG_BaseUrl + Appconstant.TAG_Method_GetDynamicPost + Appconstant.TAG_Method_GetDynamicPost_CategoryId
+ category_id + Appconstant.TAG_Method_GetDynamicPost_Type
+ type + Appconstant.TAG_Method_GetDynamicPost_PageNumber + pagenumber;
new listAs().execute(url);
} else {
CheckInternet();
}
pagenumber++;
}
private void onLoad() {
mListView.stopRefresh();
mListView.stopLoadMore();
mListView.setRefreshTime("刚刚");
}
@Override
public void onRefresh() {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
try {
//items.clear();
//geneItems();
// mAdapter.notifyDataSetChanged();
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
geneItems();
imageAdaper.notifyDataSetChanged();
onLoad();
} catch (Exception e) {
onLoad();
Toast.makeText(getActivity(), "No more item found.", Toast.LENGTH_LONG).show();
}
}
}, 2000);
}
@Override
public void onLoadMore() {
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
//geneItems();
try {
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
geneItems();
imageAdaper.notifyDataSetChanged();
onLoad();
} catch (Exception e) {
onLoad();
Toast.makeText(getActivity(), "No more item found.", Toast.LENGTH_LONG).show();
}
}
}, 2000);
}
class listAs extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
pd = new ProgressDialog(getActivity());
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.setCancelable(false);
pd.setMessage("Please wait");
pd.show();
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
ServiceHandler sh = new ServiceHandler();
String jsonStr = sh.makeServiceCall(params[0], ServiceHandler.GET);
if (jsonStr != null) {
try {
JSONObject jsonObject=new JSONObject(jsonStr);
String result=jsonObject.getString("result");
if(result.equals("1")) {
JSONArray jsonArray = jsonObject.getJSONArray("data");
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject obj = jsonArray.getJSONObject(j);
String ImageId = obj.getString(Appconstant.TAG_GetDynamicPost_Image_ID);
String PostTitle=obj.getString(Appconstant.TAG_GetDynamicPost_Image_Post_Title);
String PostImage=obj.getString(Appconstant.TAG_GetDynamicPost_Image_Title_Image);
items.add(PostTitle);
iamge_array.add(PostImage);
image_id.add(ImageId);
/* HashMap<String, String> in = new HashMap<String, String>();
in.put(Appconstant.TAG_GetDynamicPost_Image_ID, ImageId);
in.put(Appconstant.TAG_GetDynamicPost_Image_Post_Title,PostTitle);
in.put(Appconstant.TAG_GetDynamicPost_Image_Title_Image,PostImage);
arr_image.add(in);*/
}
} else {
Toast.makeText(getActivity(),"Image List Not Found",Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO: handle exception
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (pd.isShowing()) {
pd.dismiss();
}
/* imageAdaper = new ImageAdaper(getActivity(),arr_image);
list_image.setAdapter(imageAdaper);*/
lastValueSize = mListView.getLastVisiblePosition()-1;
imageAdaper = new ImageAdaper(getActivity(), items, iamge_array);
mListView.setAdapter(imageAdaper);
mListView.setSelection(lastValueSize);
}
}
public class ImageAdaper extends BaseAdapter {
private Context context;
// ArrayList<HashMap<String, String>> array_list;
ArrayList<String> array_list;
ArrayList<String> array_list_image;
public ImageAdaper(Context c,
ArrayList<String> array_list,ArrayList<String> array_list_image) {
// TODO Auto-generated constructor stub
context = c;
this.array_list = array_list;
this.array_list_image=array_list_image;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return array_list.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int Position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convert, ViewGroup arg2) {
// TODO Auto-generated method stub
View gv;
if (convert == null) {
LayoutInflater lf = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
gv = new View(context);
gv = lf.inflate(R.layout.text_fragment_image, null);
} else {
gv = (View) convert;
}
// Toast.makeText(context,"size is "+lastValueSize,Toast.LENGTH_SHORT).show();
//Reference of variable
final TextView text_fragment_image= (TextView) gv.findViewById(R.id.fragment_text);
final ImageView image_fragment_image=(ImageView) gv.findViewById(R.id.fragment_image);
text_fragment_image.setText(Html.fromHtml(array_list.get(position)));
String url=array_list_image.get(position);
// imageId=array_list.get(position).get(Appconstant.TAG_GetDynamicPost_Image_ID);
if(url != null && !url.isEmpty()){
Picasso.with(context).load("" +url).placeholder(R.drawable.fragment_image_back).into(image_fragment_image);
}
else{
image_fragment_image.setImageResource(R.drawable.fragment_image_back);
}
// Toast.makeText(context,"Size is="+(array_list.size()-1),Toast.LENGTH_SHORT).show();
return gv;
}
}
private boolean isOnline() {
ConnectivityManager conMgr = (ConnectivityManager) getActivity()
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if (netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()) {
Toast.makeText(getActivity(), "No Internet connection!",
Toast.LENGTH_LONG).show();
return false;
}
return true;
}
public void CheckInternet() {
try {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
alertDialog.setTitle("Network Connection");
alertDialog
.setMessage("Internet is not available, Please check your internet connectivity and try again");
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.setPositiveButton("Setting",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(
android.provider.Settings.ACTION_SETTINGS));
}
});
alertDialog.setNegativeButton("OK",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
getActivity().finish();
}
});
alertDialog.create();
alertDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
To import following libraries
compile 'org.apache.httpcomponents:httpcore:4.4.1'compile 'org.apache.httpcomponents:httpclient:4.5'compile 'com.squareup.picasso:picasso:2.3.2'
ServiceHandler.java
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Making service call
* @url - url to make request
* @method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* @url - url to make request
* @method - http request method
* @params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
To make AppConstant Class
public class Appconstant {
public static String TAG_BaseUrl = "http://www.xx.com/api/xxapi.php?";
//GetDynamicPost
public static String TAG_Method_GetDynamicPost = "method=getDynamicPost";
public static String TAG_Method_GetDynamicPost_CategoryId="&category_id=";
public static String TAG_Method_GetDynamicPost_Type="&type=";
public static String TAG_Method_GetDynamicPost_PageNumber="&getpage=";
}
XML file of layout folder
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:background="#f0f0f0">
<com.abc.xyz.view.XListView
android:id="@+id/list_image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:cacheColorHint="#00000000">
</com.abc.xyz.view.XListView>
</LinearLayout>
XListview's Constant Classes
XListView.java
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.DecelerateInterpolator;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Scroller;
import android.widget.TextView;
public class XListView extends ListView implements OnScrollListener {
private float mLastY = -1; // save event y
private Scroller mScroller; // used for scroll back
private OnScrollListener mScrollListener; // user's scroll listener
// the interface to trigger refresh and load more.
private IXListViewListener mListViewListener;
// -- header view
private XListViewHeader mHeaderView;
// header view content, use it to calculate the Header's height. And hide it
// when disable pull refresh.
private RelativeLayout mHeaderViewContent;
private TextView mHeaderTimeView;
private int mHeaderViewHeight; // header view's height
private boolean mEnablePullRefresh = true;
private boolean mPullRefreshing = false; // is refreashing.
// -- footer view
private XListViewFooter mFooterView;
private boolean mEnablePullLoad;
private boolean mPullLoading;
private boolean mIsFooterReady = false;
// total list items, used to detect is at the bottom of listview.
private int mTotalItemCount;
// for mScroller, scroll back from header or footer.
private int mScrollBack;
private final static int SCROLLBACK_HEADER = 0;
private final static int SCROLLBACK_FOOTER = 1;
private final static int SCROLL_DURATION = 400; // scroll back duration
private final static int PULL_LOAD_MORE_DELTA = 50; // when pull up >= 50px
// at bottom, trigger
// load more.
private final static float OFFSET_RADIO = 1.8f; // support iOS like pull
// feature.
/**
* @param context
*/
public XListView(Context context) {
super(context);
initWithContext(context);
}
public XListView(Context context, AttributeSet attrs) {
super(context, attrs);
initWithContext(context);
}
public XListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initWithContext(context);
}
private void initWithContext(Context context) {
mScroller = new Scroller(context, new DecelerateInterpolator());
// XListView need the scroll event, and it will dispatch the event to
// user's listener (as a proxy).
super.setOnScrollListener(this);
// init header view
mHeaderView = new XListViewHeader(context);
mHeaderViewContent = (RelativeLayout) mHeaderView
.findViewById(R.id.xlistview_header_content);
mHeaderTimeView = (TextView) mHeaderView
.findViewById(R.id.xlistview_header_time);
addHeaderView(mHeaderView);
// init footer view
mFooterView = new XListViewFooter(context);
// init header height
mHeaderView.getViewTreeObserver().addOnGlobalLayoutListener(
new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
mHeaderViewHeight = mHeaderViewContent.getHeight();
getViewTreeObserver()
.removeGlobalOnLayoutListener(this);
}
});
}
@Override
public void setAdapter(ListAdapter adapter) {
// make sure XListViewFooter is the last footer view, and only add once.
if (mIsFooterReady == false) {
mIsFooterReady = true;
addFooterView(mFooterView);
}
super.setAdapter(adapter);
}
/**
* enable or disable pull down refresh feature.
*
* @param enable
*/
public void setPullRefreshEnable(boolean enable) {
mEnablePullRefresh = enable;
if (!mEnablePullRefresh) { // disable, hide the content
mHeaderViewContent.setVisibility(View.INVISIBLE);
} else {
mHeaderViewContent.setVisibility(View.VISIBLE);
}
}
/**
* enable or disable pull up load more feature.
*
* @param enable
*/
public void setPullLoadEnable(boolean enable) {
mEnablePullLoad = enable;
if (!mEnablePullLoad) {
mFooterView.hide();
mFooterView.setOnClickListener(null);
//make sure "pull up" don't show a line in bottom when listview with one page
setFooterDividersEnabled(false);
} else {
mPullLoading = false;
mFooterView.show();
mFooterView.setState(XListViewFooter.STATE_NORMAL);
//make sure "pull up" don't show a line in bottom when listview with one page
setFooterDividersEnabled(true);
// both "pull up" and "click" will invoke load more.
mFooterView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startLoadMore();
}
});
}
}
/**
* stop refresh, reset header view.
*/
public void stopRefresh() {
if (mPullRefreshing == true) {
mPullRefreshing = false;
resetHeaderHeight();
}
}
/**
* stop load more, reset footer view.
*/
public void stopLoadMore() {
if (mPullLoading == true) {
mPullLoading = false;
mFooterView.setState(XListViewFooter.STATE_NORMAL);
}
}
/**
* set last refresh time
*
* @param time
*/
public void setRefreshTime(String time) {
mHeaderTimeView.setText(time);
}
private void invokeOnScrolling() {
if (mScrollListener instanceof OnXScrollListener) {
OnXScrollListener l = (OnXScrollListener) mScrollListener;
l.onXScrolling(this);
}
}
private void updateHeaderHeight(float delta) {
mHeaderView.setVisiableHeight((int) delta
+ mHeaderView.getVisiableHeight());
if (mEnablePullRefresh && !mPullRefreshing) { // 未处于刷新状æ€�,更新ç®å¤´
if (mHeaderView.getVisiableHeight() > mHeaderViewHeight) {
mHeaderView.setState(XListViewHeader.STATE_READY);
} else {
mHeaderView.setState(XListViewHeader.STATE_NORMAL);
}
}
setSelection(0); // scroll to top each time
}
/**
* reset header view's height.
*/
private void resetHeaderHeight() {
int height = mHeaderView.getVisiableHeight();
if (height == 0) // not visible.
return;
// refreshing and header isn't shown fully. do nothing.
if (mPullRefreshing && height <= mHeaderViewHeight) {
return;
}
int finalHeight = 0; // default: scroll back to dismiss header.
// is refreshing, just scroll back to show all the header.
if (mPullRefreshing && height > mHeaderViewHeight) {
finalHeight = mHeaderViewHeight;
}
mScrollBack = SCROLLBACK_HEADER;
mScroller.startScroll(0, height, 0, finalHeight - height,
SCROLL_DURATION);
// trigger computeScroll
invalidate();
}
private void updateFooterHeight(float delta) {
int height = mFooterView.getBottomMargin() + (int) delta;
if (mEnablePullLoad && !mPullLoading) {
if (height > PULL_LOAD_MORE_DELTA) { // height enough to invoke load
// more.
mFooterView.setState(XListViewFooter.STATE_READY);
} else {
mFooterView.setState(XListViewFooter.STATE_NORMAL);
}
}
mFooterView.setBottomMargin(height);
// setSelection(mTotalItemCount - 1); // scroll to bottom
}
private void resetFooterHeight() {
int bottomMargin = mFooterView.getBottomMargin();
if (bottomMargin > 0) {
mScrollBack = SCROLLBACK_FOOTER;
mScroller.startScroll(0, bottomMargin, 0, -bottomMargin,
SCROLL_DURATION);
invalidate();
}
}
private void startLoadMore() {
mPullLoading = true;
mFooterView.setState(XListViewFooter.STATE_LOADING);
if (mListViewListener != null) {
mListViewListener.onLoadMore();
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (mLastY == -1) {
mLastY = ev.getRawY();
}
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mLastY = ev.getRawY();
break;
case MotionEvent.ACTION_MOVE:
final float deltaY = ev.getRawY() - mLastY;
mLastY = ev.getRawY();
if (getFirstVisiblePosition() == 0
&& (mHeaderView.getVisiableHeight() > 0 || deltaY > 0)) {
// the first item is showing, header has shown or pull down.
updateHeaderHeight(deltaY / OFFSET_RADIO);
invokeOnScrolling();
} else if (getLastVisiblePosition() == mTotalItemCount - 1
&& (mFooterView.getBottomMargin() > 0 || deltaY < 0)) {
// last item, already pulled up or want to pull up.
updateFooterHeight(-deltaY / OFFSET_RADIO);
}
break;
default:
mLastY = -1; // reset
if (getFirstVisiblePosition() == 0) {
/* // invoke refresh
if (mEnablePullRefresh
&& mHeaderView.getVisiableHeight() > mHeaderViewHeight) {
mPullRefreshing = true;
mHeaderView.setState(XListViewHeader.STATE_REFRESHING);
if (mListViewListener != null) {
mListViewListener.onRefresh();
}
}*/
resetHeaderHeight();
} else if (getLastVisiblePosition() == mTotalItemCount - 1) {
// invoke load more.
if (mEnablePullLoad
&& mFooterView.getBottomMargin() > PULL_LOAD_MORE_DELTA
&& !mPullLoading) {
startLoadMore();
}
resetFooterHeight();
}
break;
}
return super.onTouchEvent(ev);
}
@Override
public void computeScroll() {
if (mScroller.computeScrollOffset()) {
if (mScrollBack == SCROLLBACK_HEADER) {
mHeaderView.setVisiableHeight(mScroller.getCurrY());
} else {
mFooterView.setBottomMargin(mScroller.getCurrY());
}
postInvalidate();
invokeOnScrolling();
}
super.computeScroll();
}
@Override
public void setOnScrollListener(OnScrollListener l) {
mScrollListener = l;
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (mScrollListener != null) {
mScrollListener.onScrollStateChanged(view, scrollState);
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// send to user's listener
mTotalItemCount = totalItemCount;
if (mScrollListener != null) {
mScrollListener.onScroll(view, firstVisibleItem, visibleItemCount,
totalItemCount);
}
}
public void setXListViewListener(IXListViewListener l) {
mListViewListener = l;
}
/**
* you can listen ListView.OnScrollListener or this one. it will invoke
* onXScrolling when header/footer scroll back.
*/
public interface OnXScrollListener extends OnScrollListener {
public void onXScrolling(View view);
}
/**
* implements this interface to get refresh/load more event.
*/
public interface IXListViewListener {
public void onRefresh();
public void onLoadMore();
}
}
XListViewFooter.java
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
public class XListViewFooter extends LinearLayout {
public final static int STATE_NORMAL = 0;
public final static int STATE_READY = 1;
public final static int STATE_LOADING = 2;
private Context mContext;
private View mContentView;
private View mProgressBar;
private TextView mHintView;
public XListViewFooter(Context context) {
super(context);
initView(context);
}
public XListViewFooter(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
public void setState(int state) {
mHintView.setVisibility(View.INVISIBLE);
mProgressBar.setVisibility(View.INVISIBLE);
mHintView.setVisibility(View.INVISIBLE);
if (state == STATE_READY) {
mHintView.setVisibility(View.VISIBLE);
mHintView.setText(R.string.xlistview_footer_hint_ready);
} else if (state == STATE_LOADING) {
mProgressBar.setVisibility(View.GONE);
} else {
mHintView.setVisibility(View.VISIBLE);
mHintView.setText(R.string.xlistview_footer_hint_normal);
}
}
public void setBottomMargin(int height) {
if (height < 0) return ;
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)mContentView.getLayoutParams();
lp.bottomMargin = height;
mContentView.setLayoutParams(lp);
}
public int getBottomMargin() {
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)mContentView.getLayoutParams();
return lp.bottomMargin;
}
/**
* normal status
*/
public void normal() {
mHintView.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.GONE);
}
/**
* loading status
*/
public void loading() {
mHintView.setVisibility(View.GONE);
mProgressBar.setVisibility(View.VISIBLE);
}
/**
* hide footer when disable pull load more
*/
public void hide() {
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)mContentView.getLayoutParams();
lp.height = 0;
mContentView.setLayoutParams(lp);
}
/**
* show footer
*/
public void show() {
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams)mContentView.getLayoutParams();
lp.height = LayoutParams.WRAP_CONTENT;
mContentView.setLayoutParams(lp);
}
private void initView(Context context) {
mContext = context;
LinearLayout moreView = (LinearLayout) LayoutInflater.from(mContext).inflate(R.layout.xlistview_footer, null);
addView(moreView);
moreView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
mContentView = moreView.findViewById(R.id.xlistview_footer_content);
mProgressBar = moreView.findViewById(R.id.xlistview_footer_progressbar);
mHintView = (TextView)moreView.findViewById(R.id.xlistview_footer_hint_textview);
}
}
XListViewHeader.java
import android.content.Context;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
public class XListViewHeader extends LinearLayout {
private LinearLayout mContainer;
private ImageView mArrowImageView;
private ProgressBar mProgressBar;
private TextView mHintTextView;
private int mState = STATE_NORMAL;
private Animation mRotateUpAnim;
private Animation mRotateDownAnim;
private final int ROTATE_ANIM_DURATION = 180;
public final static int STATE_NORMAL = 0;
public final static int STATE_READY = 1;
public final static int STATE_REFRESHING = 2;
public XListViewHeader(Context context) {
super(context);
initView(context);
}
/**
* @param context
* @param attrs
*/
public XListViewHeader(Context context, AttributeSet attrs) {
super(context, attrs);
initView(context);
}
private void initView(Context context) {
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, 0);
mContainer = (LinearLayout) LayoutInflater.from(context).inflate(
R.layout.xlistview_header, null);
addView(mContainer, lp);
setGravity(Gravity.BOTTOM);
mArrowImageView = (ImageView)findViewById(R.id.xlistview_header_arrow);
mHintTextView = (TextView)findViewById(R.id.xlistview_header_hint_textview);
mProgressBar = (ProgressBar)findViewById(R.id.xlistview_header_progressbar);
mRotateUpAnim = new RotateAnimation(0.0f, -180.0f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
mRotateUpAnim.setDuration(ROTATE_ANIM_DURATION);
mRotateUpAnim.setFillAfter(true);
mRotateDownAnim = new RotateAnimation(-180.0f, 0.0f,
Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
mRotateDownAnim.setDuration(ROTATE_ANIM_DURATION);
mRotateDownAnim.setFillAfter(true);
}
public void setState(int state) {
if (state == mState) return ;
if (state == STATE_REFRESHING) { // 显示进度
mArrowImageView.clearAnimation();
mArrowImageView.setVisibility(View.INVISIBLE);
mProgressBar.setVisibility(View.VISIBLE);
} else { // 显示箭头图片
mArrowImageView.setVisibility(View.VISIBLE);
mProgressBar.setVisibility(View.INVISIBLE);
}
switch(state){
case STATE_NORMAL:
if (mState == STATE_READY) {
mArrowImageView.startAnimation(mRotateDownAnim);
}
if (mState == STATE_REFRESHING) {
mArrowImageView.clearAnimation();
}
mHintTextView.setText(R.string.xlistview_header_hint_normal);
break;
case STATE_READY:
if (mState != STATE_READY) {
mArrowImageView.clearAnimation();
mArrowImageView.startAnimation(mRotateUpAnim);
mHintTextView.setText(R.string.xlistview_header_hint_ready);
}
break;
case STATE_REFRESHING:
mHintTextView.setText(R.string.xlistview_header_hint_loading);
break;
default:
}
mState = state;
}
public void setVisiableHeight(int height) {
if (height < 0)
height = 0;
LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mContainer
.getLayoutParams();
lp.height = height;
mContainer.setLayoutParams(lp);
}
public int getVisiableHeight() {
return mContainer.getLayoutParams().height;
}
}
xlistview_footer.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<RelativeLayout
android:id="@+id/xlistview_footer_content"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp" >
<ProgressBar
android:id="@+id/xlistview_footer_progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="invisible" />
<TextView
android:id="@+id/xlistview_footer_hint_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/xlistview_footer_hint_normal" />
</RelativeLayout>
</LinearLayout>
xlistview_header.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="bottom" >
<RelativeLayout
android:id="@+id/xlistview_header_content"
android:layout_width="fill_parent"
android:visibility="gone"
android:layout_height="60dp" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:orientation="vertical" android:id="@+id/xlistview_header_text">
<TextView
android:id="@+id/xlistview_header_hint_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/xlistview_header_hint_normal" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="3dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/xlistview_header_last_time"
android:textSize="12sp" />
<TextView
android:id="@+id/xlistview_header_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="12sp" />
</LinearLayout>
</LinearLayout>
<ImageView
android:id="@+id/xlistview_header_arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@id/xlistview_header_text"
android:layout_centerVertical="true"
android:layout_marginLeft="-35dp"
android:src="@drawable/xlistview_arrow" />
<ProgressBar
android:id="@+id/xlistview_header_progressbar"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignLeft="@id/xlistview_header_text"
android:layout_centerVertical="true"
android:layout_marginLeft="-40dp"
android:visibility="invisible" />
</RelativeLayout>
</LinearLayout>