我知道stackoverflow上有很多关于这个问题的例子,但我不知道如何在我的代码上实现它们。
我想要做的是从json url(前15个元素)加载数据,并将它们附加到listfragment,当用户向下滚动到列表的末尾时,另外添加15个元素(列表中总共30个元素)等等..
现在我可以正确地获取前15个元素,但是当我尝试在用户到达滚动结束时添加更多项目时我不知道该怎么做...这是我的代码:
在 MainActivity 中的我有以下类来扩展listfragment:
public static class NewsFragment extends ListFragment implements ILoadDataListener, OnScrollListener {
private ListView listView;
private NewsAdapter newsAdapter;
private int currentPage=1;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceStatee){
View rootView = inflater.inflate(R.layout.fragment_news, container, false);
listView = (ListView) rootView.findViewById(android.R.id.list);
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getListView().setOnScrollListener( this);
// URL to the JSON data
String strUrl = "http://opetmar.hostzi.com/test.php";
// Creating a new non-ui thread task to download json data
ProgressDialog progress = new ProgressDialog(getActivity());
progress.setMessage("loading ...");
GetJSON downloadTask = new GetJSON(this , progress , "news");
// Starting the download process
downloadTask.execute(strUrl);
}
@Override
public void onComplete(String[] titles , String[] images , String[] ids , String[] snippets , String[] data) {
if ( currentPage == 1 ){
newsAdapter = new NewsAdapter( getActivity() , titles , images , ids , snippets , data );
listView.setAdapter(newsAdapter);
}else {
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
DataHolder holder;
holder = (DataHolder) v.getTag();
Intent myIntent = new Intent(getActivity(), NewsOpen.class);
myIntent.putExtra("image", holder.image);
myIntent.putExtra("data", holder.data);
startActivity(myIntent);
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
@Override
public void onScrollStateChanged(AbsListView listView, int scrollState) {
if (scrollState == SCROLL_STATE_IDLE) {
if (listView.getLastVisiblePosition() >= listView.getCount() - 1 ) {
currentPage++;
String strUrl = "http://opetmar.hostzi.com/test.php?page="+currentPage;
ProgressDialog progress = new ProgressDialog(getActivity());
progress.setMessage("loading ...");
GetJSON downloadTask = new GetJSON(this , progress , "news");
// Starting the download process
downloadTask.execute(strUrl);
}
}
}
}
NewsAdapter.java
public class NewsAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] titles;
private final String[] images;
private final String[] ids;
private final String[] snippets;
private final String[] data;
public NewsAdapter(Context context, String[] titles, String[] images , String[] ids , String[] snippets , String[] data) {
super(context, R.layout.drawer_list_item, titles);
this.context = context;
this.titles = titles;
this.images = images;
this.ids = ids;
this.snippets = snippets;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.news_list_item, parent, false);
TextView title = (TextView) rowView.findViewById(R.id.news_title);
TextView snippet = (TextView) rowView.findViewById(R.id.news_snippet);
ImageView imageView = (ImageView) rowView.findViewById(R.id.news_thumble);
title.setText(titles[position]);
snippet.setText(snippets[position]);
DataHolder holder = new DataHolder();
holder.data=data[position];
holder.image=images[position];
rowView.setTag(holder);
new DownloadImageTask(imageView).execute(images[position]);
return rowView;
}
public class DataHolder {
String image;
String data;
}
}
GetJSON.java
/** AsyncTask to download json data */
public class GetJSON extends AsyncTask<String, Integer, String>{
String data = null;
private ListView listView;
private NewsAdapter newsAdapter;
private ILoadDataListener mListener;
private ProgressDialog progress;
private String type;
public GetJSON(ILoadDataListener listener , ProgressDialog progress , String type) {
this.mListener = listener;
this.progress = progress;
this.type = type;
}
public void onPreExecute() {
progress.show();
}
@Override
protected String doInBackground(String... url) {
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
@Override
protected void onPostExecute(String result) {
if (result != null){
if (this.type == "news") {
try {
JSONObject jObject;
jObject = new JSONObject(result);
JSONArray jCountries = jObject.optJSONArray("news");
ArrayList<String> stringArrayList = new ArrayList<String>();
ArrayList<String> stringArrayList2 = new ArrayList<String>();
ArrayList<String> stringArrayList3 = new ArrayList<String>();
ArrayList<String> stringArrayList4 = new ArrayList<String>();
ArrayList<String> stringArrayList5 = new ArrayList<String>();
for (int i=0; i < jCountries.length(); i++)
{
try {
JSONObject oneObject = jCountries.getJSONObject(i);
// Pulling items from the array
stringArrayList.add(oneObject.getString("title"));
stringArrayList2.add( oneObject.getString("image"));
stringArrayList3.add( oneObject.getString("id"));
stringArrayList4.add( oneObject.getString("snippet"));
stringArrayList5.add( oneObject.getString("data"));
} catch (JSONException e) {
// Oops
}
}
String [] stringArray = stringArrayList.toArray(new String[stringArrayList.size()]);
String [] stringArray2 = stringArrayList2.toArray(new String[stringArrayList2.size()]);
String [] stringArray3 = stringArrayList3.toArray(new String[stringArrayList3.size()]);
String [] stringArray4 = stringArrayList4.toArray(new String[stringArrayList4.size()]);
String [] stringArray5 = stringArrayList5.toArray(new String[stringArrayList5.size()]);
progress.dismiss();
if (mListener != null) {
mListener.onComplete(stringArray , stringArray2 , stringArray3 , stringArray4 , stringArray5);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}else{
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
String data = "";
InputStream iStream = null;
try{
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}
data = sb.toString();
br.close();
}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
}
return data;
}
}
更具体地说,当用户到达滚动结尾时,将触发以下代码从json url加载更多数据:
@Override
public void onScrollStateChanged(AbsListView listView, int scrollState) {
if (scrollState == SCROLL_STATE_IDLE) {
if (listView.getLastVisiblePosition() >= listView.getCount() - 1 ) {
currentPage++;
String strUrl = "http://opetmar.hostzi.com/test.php?page="+currentPage;
ProgressDialog progress = new ProgressDialog(getActivity());
progress.setMessage("loading ...");
GetJSON downloadTask = new GetJSON(this , progress , "news");
// Starting the download process
downloadTask.execute(strUrl);
}
}
然后GetJSON将在完成提取和解析数据后调用以下方法:
@Override
public void onComplete(String[] titles , String[] images , String[] ids , String[] snippets , String[] data) {
if ( currentPage == 1 ){
newsAdapter = new NewsAdapter( getActivity() , titles , images , ids , snippets , data );
listView.setAdapter(newsAdapter);
}else {
}
}
所以如果 currentpage 不等于1,我想追加更多数据。怎么实现呢?
答案 0 :(得分:0)
我不确定ListView是否可行,但使用Gallery可以覆盖
public boolean onFling(MotionEvent e1,MotionEvent e2,float velocityX,float velocityY);
并使用它来定义项目滚动到结尾时的事件。我这样做是为了在画廊中组织无限的日历列表。
此致
亚历。