[英]How to implement load more function using setOnScrollListener in android
我已經實現了一個android應用。 當用戶向下滾動列表視圖時,我想使用加載更多功能。 我將setOnScrollListener用於列表視圖,但是在向下滾動列表視圖時,它沒有顯示加載更多項目。
MainActivity
public class MainActivity extends Activity {
private ActionBar actionBar;
private ListView listView;
DBHelper dbHelper;
ArrayList<Personinfo> list;
AdapterFilter adapterfilter;
Personinfo personinfo;
boolean isLoading = false;
static int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
count = count + 10;
actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#03A9F4")));
list = new ArrayList<Personinfo>();
dbHelper = new DBHelper(this);
listView = (ListView) findViewById(R.id.listView);
initList();
adapterfilter = new AdapterFilter(this, R.layout.child_listview, list);
listView.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
int lastIndexInScreen = visibleItemCount + firstVisibleItem;
if (lastIndexInScreen >= totalItemCount && !isLoading) {
isLoading = true;
loadMore();
}
}
});
listView.setAdapter(adapterfilter);
listView.setTextFilterEnabled(true);
}
public void initList() {
list = new ArrayList<Personinfo>();
dbHelper.openDataBase();
Cursor cursor = dbHelper.Get_ContactDetails(count);
cursor.moveToFirst();
do {
String name = cursor.getString(0);
String phoneno = cursor.getString(1);
Personinfo personinfo = new Personinfo(name, phoneno);
list.add(personinfo);
} while (cursor.moveToNext());
dbHelper.close();
cursor.close();
}
public void loadMore() {
list = new ArrayList<Personinfo>();
dbHelper.openDataBase();
Cursor cursor = dbHelper.Get_ContactDetails(count);
if (list.size() <= 90) { // Limit the number of items to 100 (stop
// loading when reaching 100 items)
cursor.moveToFirst();
do {
String name = cursor.getString(0);
String phoneno = cursor.getString(1);
Personinfo personinfo = new Personinfo(name, phoneno);
list.add(personinfo);
} while (cursor.moveToNext());
dbHelper.close();
cursor.close();
adapterfilter.notifyDataSetChanged();
isLoading = false;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_actions, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
.getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextChange(String newText) {
// this is your adapter that will be filtered
adapterfilter.getFilter().filter(newText);
System.out.println("on text chnge text: " + newText);
return true;
}
@Override
public boolean onQueryTextSubmit(String query) {
// this is your adapter that will be filtered
adapterfilter.getFilter().filter(query);
System.out.println("on query submit: " + query);
return true;
}
};
searchView.setOnQueryTextListener(textChangeListener);
return super.onCreateOptionsMenu(menu);
}
/**
* On selecting action bar icons
* */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_search:
// search action
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
DBHelper
public class DBHelper extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "Demo.sqlite";
private static final String DB_PATH_SUFFIX = "/databases/";
static Context ctx;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
ctx = context;
}
// Getting single contact
public Cursor Get_ContactDetails(int count) {
//public Cursor Get_ContactDetails() {
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT col_1, col_2 FROM agrawalSurnameDataDemo limit 10 offset "+ count;
//String query = "SELECT col_1, col_2 FROM agrawalSurnameDataDemo";
Cursor cursor = db.rawQuery(query, null);
cursor.moveToFirst();
do {
cursor.getString(0);
cursor.getString(1);
// return details;
} while (cursor.moveToNext());
return db.rawQuery(query, null);
}
public void CopyDataBaseFromAsset() throws IOException {
InputStream myInput = ctx.getAssets().open(DATABASE_NAME);
// Path to the just created empty db
String outFileName = getDatabasePath();
// if the path doesn't exist first, create it
File f = new File(ctx.getApplicationInfo().dataDir + DB_PATH_SUFFIX);
if (!f.exists())
f.mkdir();
// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
private static String getDatabasePath() {
return ctx.getApplicationInfo().dataDir + DB_PATH_SUFFIX
+ DATABASE_NAME;
}
public SQLiteDatabase openDataBase() throws SQLException {
File dbFile = ctx.getDatabasePath(DATABASE_NAME);
if (!dbFile.exists()) {
try {
CopyDataBaseFromAsset();
System.out.println("Copying sucess from Assets folder");
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}
return SQLiteDatabase.openDatabase(dbFile.getPath(), null,
SQLiteDatabase.NO_LOCALIZED_COLLATORS
| SQLiteDatabase.CREATE_IF_NECESSARY);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}
AdapterFilter
public class AdapterFilter extends ArrayAdapter<Personinfo>{
ArrayList<Personinfo> list = new ArrayList<Personinfo>();
Context context;
LayoutInflater inflater;
public AdapterFilter(Context context, int resource, ArrayList<Personinfo> list) {
super(context, resource);
this.list = list;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
@Override
public Personinfo getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.child_listview, parent,
false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final Personinfo personinfo = (Personinfo) getItem(position);
viewHolder.txtName.setText(personinfo.getName());
viewHolder.txtPhone.setText(personinfo.getPhoneno());
viewHolder.txtName.setSelected(true);
viewHolder.imageButtonCalling.setOnClickListener(new OnClickListener() {
// Calling on selected number
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "number button Clicked",
Toast.LENGTH_SHORT).show();
String selectedChildPhone = personinfo.getPhoneno();
String phoneNo = "tel:" + selectedChildPhone.trim();
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(phoneNo));
context.startActivity(intent);
}
});
viewHolder.imageButtonMessage.setOnClickListener(new OnClickListener() {
// Sending sms to whatsapp
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "meesaage button Clicked",
Toast.LENGTH_SHORT).show();
String selectedChildPhone = personinfo.getPhoneno();
Uri mUri = Uri.parse("smsto:" + selectedChildPhone);
Intent mIntent = new Intent(Intent.ACTION_SENDTO, mUri);
mIntent.setPackage("com.whatsapp");
mIntent.putExtra("sms_body", "The text goes here");
mIntent.putExtra("chat", true);
context.startActivity(mIntent);
}
});
return convertView;
}
private class ViewHolder {
TextView txtName, txtPhone;
ImageButton imageButtonCalling, imageButtonMessage;
public ViewHolder(View item) {
txtName = (TextView) item.findViewById(R.id.person_name);
txtPhone = (TextView) item.findViewById(R.id.phoneno);
imageButtonCalling = (ImageButton) item.findViewById(R.id.imageButtonCalling);
imageButtonMessage = (ImageButton) item.findViewById(R.id.imageButtonMessage);
}
}
}
請幫助我,我哪里錯了!
這段代碼對我來說很好用。 我每次加載10行並將其添加到適配器中,並且我有一個int變量totalNum
,它引用數據庫中的總行數,並且布爾值loading
告訴我ListView是否正在加載
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int position = firstVisibleItem + visibleItemCount;
if (position >= totalItemCount && totalItemCount > 0 && totalItemCount < totalNum && !loading) {
loading = true;
// write what you want here
}
}
});
Try this:-
private boolean mHasRequestedMore;
private int preLast;
listView.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (!mHasRequestedMore) {
final int lastItem = firstVisibleItem + visibleItemCount;
if (lastItem == totalItemCount)
{
if (preLast != lastItem) {
preLast = lastItem;
loadMore();
}
}
}
}
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.