It took me two(!) days to figure out my problem.
I have ListView with both onItemClickListener and onScrollListner. If I implement the onScrollListner then no ItemClick actions are fired.
I saw this problem here: setOnScrollListener with setOnItemClickListener and here:Android: cannot set both: setOnItemClickListener setOnScrollListener? with no real solution.
I have also noticed (in the emulator) that when one of the rows (in the ListView) is selected then ItemClick does fire (I assume that it works in not touch mode).
Very frustrating, can anyone think of a solution?
Some code:
Custom ListView
public class CustomHomeListView extends ListView implements android.widget.AdapterView.OnItemClickListener, OnScrollListener, IReceiver {
public static final String TAG = CustomHomeListView.class.getSimpleName();
private static Context mContext;
List<DiscussionModel> mDiscussionsArray = new ArrayList<DiscussionModel>();
private DiscussionsCustomAdapter mAdapter;
private boolean mIsLoading;
private int mCurrentMinDiscussionRowIndex;
private View mFooterView;
private int mFirstVisiblePosition;
private int mSelectedItemPosition;
private int mDividerHeight;
private int mSavedPositionInsideListView;
public MyResultReceiver mReceiver;
public void onCreate() {
// for computing scroll position to an item after data fetch
mDividerHeight = getDividerHeight();
mSavedPositionInsideListView = 0;
// prepare ResultReceiver for informing that puller service is done
mReceiver = new MyResultReceiver(new Handler());
mReceiver.setReceiver(this);
mCurrentMinDiscussionRowIndex = -1; // default value for retrieving most
// recent
// posts from web
mAdapter = new DiscussionsCustomAdapter(mContext);
CrowdietApplication cda = (CrowdietApplication) mContext.getApplicationContext();
mAdapter.setCurrentUserUid(cda.getUserId());
setAdapter(mAdapter);
setOnScrollListener(this);
setOnItemClickListener(this);
mFooterView = ((LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.home_list_view_footer, null);
//setCustomHomeListViewOnScrollListener();
pullDiscussions();
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
DiscussionModel discussion = mDiscussionsArray.get(position);
Intent intent = new Intent(mContext, DiscussionActivity.class);
intent.putExtra(CONSTS_DISCUSSIONS.DISCUSSION_ID_FROM_CALLING_ACTIVITY, discussion.getDiscussionId());
mContext.startActivity(intent);
}
public void refresh() {
mCurrentMinDiscussionRowIndex = -1;
pullDiscussions();
}
private void pullDiscussions() {
mIsLoading = true;
// preparing puller service
Intent intent = new Intent(mContext, PullDiscussionsListIntentService.class);
intent.putExtra(CONSTS_APP_SIGNALS.MIN_DISCUSSION_ROW_INDEX_TO_FETCH, mCurrentMinDiscussionRowIndex);
intent.putExtra(CONSTS_APP_SIGNALS.RECEIVER_TAG, mReceiver);
mContext.startService(intent);
}
private void refreshListFromDatabase() {
DbDiscussions dbDiscussions = new DbDiscussions(mContext);
Cursor discussionsCursor;
discussionsCursor = dbDiscussions.getDiscussions();
if (discussionsCursor != null && discussionsCursor.getCount() > 0) {
prepareDiscussionsArray(discussionsCursor);
mCurrentMinDiscussionRowIndex = dbDiscussions.getMinDiscussionRowIndex();
mAdapter.setData(mDiscussionsArray);
mAdapter.notifyDataSetChanged();
mIsLoading = false;
}
discussionsCursor.close();
dbDiscussions.destroy();
}
private void prepareDiscussionsArray(Cursor discussionsCursor) {
mDiscussionsArray.clear();
int noOfReturnedDiscussions = discussionsCursor.getCount();
discussionsCursor.moveToFirst();
for (int i = 0; i < noOfReturnedDiscussions; i++) {
DiscussionModel discussion = new DiscussionModel();
discussion.setDiscussionId(discussionsCursor.getString(discussionsCursor.getColumnIndex(CONSTS_DISCUSSIONS.FIELD_DISCUSSION_ID)));
discussion.setDiscussionTitle(discussionsCursor.getString(discussionsCursor.getColumnIndex(CONSTS_DISCUSSIONS.FIELD_DISCUSSION_TITLE)));
discussion.setUsername(discussionsCursor.getString(discussionsCursor.getColumnIndex(CONSTS_DISCUSSIONS.FIELD_USERNAME)));
mDiscussionsArray.add(discussion);
discussionsCursor.moveToNext();
}
}
private int calcItemPosition() {
int posInListView = 0;
for (int i = 0; i < mSelectedItemPosition - mFirstVisiblePosition - 1; i++) {
View child = getChildAt(i);
if (child == null) {
break;
}
posInListView += child.getHeight() + mDividerHeight;
}
// Log.d(TAG, "measured height :" + posInListView);
return posInListView;
}
public CustomHomeListView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
}
private void prepareForMySetSelection() {
if (mSelectedItemPosition > -1) {
mSavedPositionInsideListView = calcItemPosition();
}
}
private void mySetSelection() {
if (mSelectedItemPosition > -1) {
setSelectionFromTop(mSelectedItemPosition, mSavedPositionInsideListView);
} else {
setSelection(mFirstVisiblePosition);
}
}
public void onReceiveResult(int resultCode, Bundle resultData) {
prepareForMySetSelection(); // should be before
// RefreshListFromDatabase() so that
// actual position inside adapter is
// saved
refreshListFromDatabase();
setAdapter(mAdapter);
mySetSelection();
// }
removeFooterView(mFooterView);
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
mFirstVisiblePosition = getFirstVisiblePosition();
mSelectedItemPosition = getSelectedItemPosition();
if (mAdapter != null && mAdapter.getCount() > 0) {
int l = visibleItemCount + firstVisibleItem;
if (l >= totalItemCount && !mIsLoading) {
addFooterView(mFooterView);
pullDiscussions();
}
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
}
Related
Hi I'm using widget listview. I want to load image on each widget listview item so I have used below code to load image using url
public class ListProvider implements RemoteViewsService.RemoteViewsFactory {
private String TAG = ListProvider.class.getSimpleName();
private Context context = null;
private UserPreference userPreference;
private int appWidgetId;
private String feedsData, mLaneName, mLaneId;
private Tooteet.Collection collection;
private ArrayList<Item> mItems;
public ListProvider(Context context, Intent intent) {
this.context = context;
userPreference = new UserPreference(context);
appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
feedsData = intent.getStringExtra(LargeWidgetProvider.LARGE_WIDGET_LIST_DATA);
mLaneId = intent.getStringExtra(LargeWidgetProvider.WIDGET_LANE_ID);
mLaneName = intent.getStringExtra(LargeWidgetProvider.WIDGET_LANE_NAME);
if(mLaneId != null && mLaneName != null) {
collection = new Tooteet.Collection(feedsData, mLaneId, mLaneName);
}
mItems = getItems(collection);
}
public ArrayList<Item> getItems(Tooteet.Collection collection) {
ArrayList<Item> items = new ArrayList<>();
if (collection == null) {
return items;
}
int sectionFirstPosition = 0;
int i = 0;
for (Tooteet tooteet : collection.getItems()) {
int type = tooteet.getTweetType();
int viewType = VIEW_TYPE_TEXT;
switch (type) {
case TooteetType.TEXT:
case TooteetType.NOTE:
viewType = VIEW_TYPE_TEXT;
// add text;
break;
case TooteetType.PICTURE:
case TooteetType.DRAWING:
case TooteetType.VIDEO:
viewType = VIEW_TYPE_MEDIA;
// add media
break;
case TooteetType.AUDIO:
case TooteetType.DOCUMENT:
//case TooteetType.EXPENSE:
viewType = VIEW_TYPE_FILE;
// add file
break;
case TooteetType.MEASURE:
viewType = VIEW_TYPE_MEASURE;
break;
case TooteetType.EXPENSE:
viewType = VIEW_TYPE_EXPENSE;
break;
}
Log.d(TAG, "getItems -- tooteet: "+tooteet);
items.add(new Item("", false, tooteet, viewType, sectionFirstPosition, i));
i++;
}
return items;
}
#Override
public int getCount() {
Log.d(TAG, " getCount() -- mItems.size(): "+mItems.size());
return mItems.size();
}
#Override
public long getItemId(int position) {
return position;
}
/*
*Similar to getView of Adapter where instead of View
*we return RemoteViews
*
*/
#Override
public RemoteViews getViewAt(final int position) {
Log.d(TAG,"=============getViewAt position=========="+position);
RemoteViews remoteView = null;
final Item item = mItems.get(position);
if (item.mTooteet.getTweetType() == TooteetType.TEXT || item.mTooteet.getTweetType() == TooteetType.NOTE) {
remoteView = new RemoteViews(context.getPackageName(), R.layout.widget_feed_list_text);
remoteView.setImageViewResource(R.id.feed_type,R.drawable.feed_list_note);
} else if (item.mTooteet.getTweetType() == TooteetType.PICTURE || item.mTooteet.getTweetType() == TooteetType.DRAWING || item.mTooteet.getTweetType() == TooteetType.VIDEO) {
remoteView = new RemoteViews(context.getPackageName(), R.layout.widget_feed_list_image);
int drawable = R.drawable.feed_list_attachment;
if (item.mTooteet.getTweetType() == TooteetType.PICTURE) {
drawable = R.drawable.feed_list_picture;
} else if (item.mTooteet.getTweetType() == TooteetType.VIDEO) {
drawable = R.drawable.feed_list_video;
}else if(item.mTooteet.getTweetType() == TooteetType.DRAWING){
drawable = R.drawable.feed_list_drawing;
}
remoteView.setImageViewResource(R.id.feed_type,drawable);
try {
} catch (Exception e) {
e.printStackTrace();
}
Handler uiHandler = new Handler(Looper.getMainLooper());
final RemoteViews finalRemoteView1 = remoteView;
uiHandler.post(new Runnable(){
#Override
public void run() {
Picasso.with(context).load(item.mTooteet.getThumbUrl1()).into(
finalRemoteView1, R.id.feed_image,
new int[]{appWidgetId});
}
});
} else if (item.mTooteet.getTweetType() == TooteetType.AUDIO || item.mTooteet.getTweetType() == TooteetType.DOCUMENT) {
remoteView = new RemoteViews(context.getPackageName(), R.layout.widget_feed_list_audio);
int drawable;
if (item.mTooteet.getTweetType() == TooteetType.AUDIO) {
drawable = R.drawable.feed_list_audio;
} else {
drawable = FeedDocResourceHandler.getIconResForListDoc(item.mTooteet.getUniqueFileName());
}
remoteView.setImageViewResource(R.id.feed_type,drawable);
} else if (item.mTooteet.getTweetType() == TooteetType.MEASURE) {
remoteView = new RemoteViews(context.getPackageName(), R.layout.widget_feed_list_measure);
}else if (item.mTooteet.getTweetType() == TooteetType.EXPENSE) {
remoteView = new RemoteViews(context.getPackageName(), R.layout.widget_feed_list_expense);
}
remoteView.setTextViewText(R.id.feed_keywords, item.mTooteet.getKeywords());
if(!TextUtils.isEmpty(item.mTooteet.getTooteetText())){
remoteView.setViewVisibility(R.id.feed_text, View.VISIBLE);
remoteView.setTextViewText(R.id.feed_text, item.mTooteet.getTooteetText());
}else{
remoteView.setViewVisibility(R.id.feed_text, View.GONE);
}
if (!item.mTooteet.isLocationEmpty()) {
if (!TextUtils.isEmpty(item.mTooteet.getLocationString())) {
remoteView.setViewVisibility(R.id.feed_location, View.VISIBLE);
remoteView.setTextViewText(R.id.feed_location, item.mTooteet.getLocationString());
} else {
final RemoteViews finalRemoteView = remoteView;
ReverseGeocoder.with(Constants.getLanesApp()).load(item.mTooteet, new com.kwypesoft.lanes.location.GeocodeApi.OnLocationListener() {
#Override
public void onReceive(String location) {
if (!TextUtils.isEmpty(location)) {
finalRemoteView.setViewVisibility(R.id.feed_location, View.VISIBLE);
finalRemoteView.setTextViewText(R.id.feed_location, item.mTooteet.getLocationString());
item.mTooteet.setLocationString(location);
}else{
finalRemoteView.setViewVisibility(R.id.feed_location, View.GONE);
}
}
});
}
}else{
remoteView.setViewVisibility(R.id.feed_location, View.GONE);
}
final Intent fillInIntent = new Intent();
fillInIntent.setAction(LargeWidgetProvider.ACTION_TOAST);
final Bundle bundle = new Bundle();
bundle.putString(LargeWidgetProvider.WIDGET_LANE_ID, mLaneId);
bundle.putSerializable(DetailBase.FEED_DETAILS, item.mTooteet);
fillInIntent.putExtras(bundle);
remoteView.setOnClickFillInIntent(R.id.root, fillInIntent);
return remoteView;
}
#Override
public RemoteViews getLoadingView() {
return null;
}
#Override
public int getViewTypeCount() {
return 5;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public void onCreate() {
}
#Override
public void onDataSetChanged() {
}
#Override
public void onDestroy() {
}
private static class Item{
boolean isHeader;
String header;
public Tooteet mTooteet;
int viewType;
int firstPosition;
int itemPosition;
public Item(String header, boolean isHeader, Tooteet tooteet, int type, int firstPosition, int itemPosition) {
this.header = header;
this.isHeader = isHeader;
mTooteet = tooteet;
this.viewType = type;
this.firstPosition = firstPosition;
this.itemPosition = itemPosition;
}
}
}
But this will change my widget UI design and it shows only one listview item at a time.
where i have only one appWidgetId in listview provider class which extends RemoteViewsService.RemoteViewsFactory. I do not know. What's went wrong. Could you please suggest me a idea to fix it?
Picasso offers much more than just downloading image. It can resize the image, transform before it is displayed in ImageView. So you can resize or transform your image as follow.
Picasso.with(this)
.load("YOUR IMAGE URL HERE")
.error(R.drawable.ic_error_fallback) // optional
.resize(250, 200) // optional
.rotate(90) // optional
.into(imageView);
thank you.
I have fix my issue using Universal image loader like below,
public class YourViewsFactory implements RemoteViewsService.RemoteViewsFactory
{
Map<Integer, Boolean> flags = Collections.synchronizedMap(new HashMap<Integer, Boolean>());
Bitmap mBitmap;
Handler handler = new Handler(Looper.getMainLooper());
#Override
public RemoteViews getViewAt(final int position)
{
final RemoteViews row = new RemoteViews(ctxt.getPackageName(), R.layout.row);
flags.put(position, false);
handler.post(new Runnable()
{
#Override
public void run()
{
m_imgLoader.loadImage(YOUR_IMAGE_URL, new SimpleImageLoadingListener()
{
#Override
public void onLoadingStarted(String imageUri, View view)
{
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason)
{
flags.put(position, true);
}
#Override
public void onLoadingCancelled(String imageUri, View view)
{
flags.put(position, true);
}
#Override
public void onLoadingComplete(String arg0, View arg1, Bitmap bitmap)
{
mBitmap = bitmap;
flags.put(position, true);
}
});
}
});
while (!flags.get(position))
{
try
{
Thread.sleep(100);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
flags.put(position, false);
if (mBitmap != null)
{
row.setImageViewBitmap(R.id.ivPoster, mBitmap);
} else
{
row.setImageViewResource(R.id.ivPoster, R.drawable.cw);
}
mBitmap = null;
} // End of getViewAt override
} // End of class
Please make use of it.
I want to place admob ad in my settings activity, since I am not using any xml for the settings activity I want to place the ad in the listview.
My settings activity looks as follows:
public class SettingsActivity extends BaseFragment implements NotificationCenter.NotificationCenterDelegate, PhotoViewer.PhotoViewerProvider {
private ListView listView;
private ListAdapter listAdapter;
private BackupImageView avatarImage;
private TextView nameTextView;
private TextView onlineTextView;
private ImageView writeButton;
private AnimatorSetProxy writeButtonAnimation;
private AvatarUpdater avatarUpdater = new AvatarUpdater();
private View extraHeightView;
private View shadowView;
private int extraHeight;
private int overscrollRow;
private int emptyRow;
private int numberSectionRow;
private int numberRow;
private int usernameRow;
private int settingsSectionRow;
private int settingsSectionRow2;
private int enableAnimationsRow;
private int notificationRow;
private int backgroundRow;
private int languageRow;
private int privacyRow;
private int mediaDownloadSection;
private int mediaDownloadSection2;
private int mobileDownloadRow;
private int wifiDownloadRow;
private int roamingDownloadRow;
private int saveToGalleryRow;
private int messagesSectionRow;
private int messagesSectionRow2;
private int customTabsRow;
private int directShareRow;
private int textSizeRow;
private int stickersRow;
private int cacheRow;
private int raiseToSpeakRow;
private int sendByEnterRow;
//private int useSystemEmojiRow;
private int supportSectionRow;
private int supportSectionRow2;
// private int askQuestionRow;
//private int telegramFaqRow;
private int adsRow;
private int privacyPolicyRow;
private int sendLogsRow;
private int clearLogsRow;
private int switchBackendButtonRow;
private int versionRow;
private int contactsSectionRow;
private int contactsReimportRow;
private int contactsSortRow;
private int autoplayGifsRow;
private int rowCount;
private final static int edit_name = 1;
private final static int logout = 2;
private static class LinkMovementMethodMy extends LinkMovementMethod {
#Override
public boolean onTouchEvent(#NonNull TextView widget, #NonNull Spannable buffer, #NonNull MotionEvent event) {
try {
return super.onTouchEvent(widget, buffer, event);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
return false;
}
}
#Override
public boolean onFragmentCreate() {
super.onFragmentCreate();
avatarUpdater.parentFragment = this;
avatarUpdater.delegate = new AvatarUpdater.AvatarUpdaterDelegate() {
#Override
public void didUploadedPhoto(TLRPC.InputFile file, TLRPC.PhotoSize small, TLRPC.PhotoSize big) {
TLRPC.TL_photos_uploadProfilePhoto req = new TLRPC.TL_photos_uploadProfilePhoto();
req.caption = "";
req.crop = new TLRPC.TL_inputPhotoCropAuto();
req.file = file;
req.geo_point = new TLRPC.TL_inputGeoPointEmpty();
ConnectionsManager.getInstance().sendRequest(req, new RequestDelegate() {
#Override
public void run(TLObject response, TLRPC.TL_error error) {
if (error == null) {
TLRPC.User user = MessagesController.getInstance().getUser(UserConfig.getClientUserId());
if (user == null) {
user = UserConfig.getCurrentUser();
if (user == null) {
return;
}
MessagesController.getInstance().putUser(user, false);
} else {
UserConfig.setCurrentUser(user);
}
TLRPC.TL_photos_photo photo = (TLRPC.TL_photos_photo) response;
ArrayList<TLRPC.PhotoSize> sizes = photo.photo.sizes;
TLRPC.PhotoSize smallSize = FileLoader.getClosestPhotoSizeWithSize(sizes, 100);
TLRPC.PhotoSize bigSize = FileLoader.getClosestPhotoSizeWithSize(sizes, 1000);
user.photo = new TLRPC.TL_userProfilePhoto();
user.photo.photo_id = photo.photo.id;
if (smallSize != null) {
user.photo.photo_small = smallSize.location;
}
if (bigSize != null) {
user.photo.photo_big = bigSize.location;
} else if (smallSize != null) {
user.photo.photo_small = smallSize.location;
}
MessagesStorage.getInstance().clearUserPhotos(user.id);
ArrayList<TLRPC.User> users = new ArrayList<>();
users.add(user);
MessagesStorage.getInstance().putUsersAndChats(users, null, false, true);
AndroidUtilities.runOnUIThread(new Runnable() {
#Override
public void run() {
NotificationCenter.getInstance().postNotificationName(NotificationCenter.updateInterfaces, MessagesController.UPDATE_MASK_ALL);
NotificationCenter.getInstance().postNotificationName(NotificationCenter.mainUserInfoChanged);
UserConfig.saveConfig(true);
}
});
}
}
});
}
};
NotificationCenter.getInstance().addObserver(this, NotificationCenter.updateInterfaces);
rowCount = 0;
overscrollRow = rowCount++;
emptyRow = rowCount++;
numberSectionRow = rowCount++;
numberRow = rowCount++;
usernameRow = rowCount++;
settingsSectionRow = rowCount++;
settingsSectionRow2 = rowCount++;
notificationRow = rowCount++;
privacyRow = rowCount++;
backgroundRow = rowCount++;
languageRow = rowCount++;
adsRow = rowCount++;
enableAnimationsRow = rowCount++;
mediaDownloadSection = rowCount++;
mediaDownloadSection2 = rowCount++;
mobileDownloadRow = rowCount++;
wifiDownloadRow = rowCount++;
roamingDownloadRow = rowCount++;
if (Build.VERSION.SDK_INT >= 11) {
autoplayGifsRow = rowCount++;
}
saveToGalleryRow = rowCount++;
messagesSectionRow = rowCount++;
messagesSectionRow2 = rowCount++;
customTabsRow = rowCount++;
if (Build.VERSION.SDK_INT >= 23) {
directShareRow = rowCount++;
}
textSizeRow = rowCount++;
stickersRow = rowCount++;
cacheRow = rowCount++;
raiseToSpeakRow = rowCount++;
sendByEnterRow = rowCount++;
// useSystemEmojiRow = rowCount++;
supportSectionRow = rowCount++;
supportSectionRow2 = rowCount++;
// askQuestionRow = rowCount++;
//telegramFaqRow = rowCount++;
privacyPolicyRow = rowCount++;
if (BuildVars.DEBUG_VERSION) {
sendLogsRow = rowCount++;
clearLogsRow = rowCount++;
switchBackendButtonRow = rowCount++;
}
versionRow = rowCount++;
//contactsSectionRow = rowCount++;
//contactsReimportRow = rowCount++;
//contactsSortRow = rowCount++;
MessagesController.getInstance().loadFullUser(UserConfig.getCurrentUser(), classGuid, true);
return true;
}
#Override
public void onFragmentDestroy() {
super.onFragmentDestroy();
if (avatarImage != null) {
avatarImage.setImageDrawable(null);
}
MessagesController.getInstance().cancelLoadFullUser(UserConfig.getClientUserId());
NotificationCenter.getInstance().removeObserver(this, NotificationCenter.updateInterfaces);
avatarUpdater.clear();
}
#Override
public View createView(Context context) {
actionBar.setBackgroundColor(AvatarDrawable.getProfileBackColorForId(5));
actionBar.setItemsBackground(AvatarDrawable.getButtonColorForId(5));
actionBar.setBackButtonImage(R.drawable.ic_ab_back);
actionBar.setAddToContainer(false);
extraHeight = 88;
if (AndroidUtilities.isTablet()) {
actionBar.setOccupyStatusBar(false);
}
actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
#Override
public void onItemClick(int id) {
if (id == -1) {
finishFragment();
} else if (id == edit_name) {
presentFragment(new ChangeNameActivity());
} else if (id == logout) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setMessage(LocaleController.getString("AreYouSureLogout", R.string.AreYouSureLogout));
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setPositiveButton(LocaleController.getString("OK", R.string.OK), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MessagesController.getInstance().performLogout(true);
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showDialog(builder.create());
}
}
});
ActionBarMenu menu = actionBar.createMenu();
ActionBarMenuItem item = menu.addItem(0, R.drawable.ic_ab_other);
item.addSubItem(edit_name, LocaleController.getString("EditName", R.string.EditName), 0);
item.addSubItem(logout, LocaleController.getString("LogOut", R.string.LogOut), 0);
listAdapter = new ListAdapter(context);
fragmentView = new FrameLayout(context) {
#Override
protected boolean drawChild(#NonNull Canvas canvas, #NonNull View child, long drawingTime) {
if (child == listView) {
boolean result = super.drawChild(canvas, child, drawingTime);
if (parentLayout != null) {
int actionBarHeight = 0;
int childCount = getChildCount();
for (int a = 0; a < childCount; a++) {
View view = getChildAt(a);
if (view == child) {
continue;
}
if (view instanceof ActionBar && view.getVisibility() == VISIBLE) {
if (((ActionBar) view).getCastShadows()) {
actionBarHeight = view.getMeasuredHeight();
}
break;
}
}
parentLayout.drawHeaderShadow(canvas, actionBarHeight);
}
return result;
} else {
return super.drawChild(canvas, child, drawingTime);
}
}
};
FrameLayout frameLayout = (FrameLayout) fragmentView;
listView = new ListView(context);
listView.setDivider(null);
listView.setDividerHeight(0);
listView.setVerticalScrollBarEnabled(false);
AndroidUtilities.setListViewEdgeEffectColor(listView, AvatarDrawable.getProfileBackColorForId(5));
frameLayout.addView(listView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT));
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
if (i == textSizeRow) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("TextSize", R.string.TextSize));
final NumberPicker numberPicker = new NumberPicker(getParentActivity());
numberPicker.setMinValue(12);
numberPicker.setMaxValue(30);
numberPicker.setValue(MessagesController.getInstance().fontSize);
builder.setView(numberPicker);
builder.setNegativeButton(LocaleController.getString("Done", R.string.Done), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("fons_size", numberPicker.getValue());
MessagesController.getInstance().fontSize = numberPicker.getValue();
editor.commit();
if (listView != null) {
listView.invalidateViews();
}
}
});
showDialog(builder.create());
} else if (i == enableAnimationsRow) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
boolean animations = preferences.getBoolean("view_animations", true);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("view_animations", !animations);
editor.commit();
if (view instanceof TextCheckCell) {
((TextCheckCell) view).setChecked(!animations);
}
} else if (i == notificationRow) {
presentFragment(new NotificationsSettingsActivity());
} else if (i == backgroundRow) {
presentFragment(new WallpapersActivity());
}
else if (i == adsRow) {
}
Hence I want to place the code under i== adsRow else if condition at the last.
How can I do the same?
You will be creating a banner AdView object programmatically, and stitch it to your ListView:
// Create a banner ad. The ad size and ad unit ID must be set before calling loadAd.
AdView mAdView = new AdView(this);
mAdView.setAdSize(AdSize.SMART_BANNER);
mAdView.setAdUnitId("myAdUnitId");
// Create an ad request.
AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
// Add the AdView to the view hierarchy.
layout.addView(mAdView);
// Start loading the ad.
mAdView.loadAd(adRequestBuilder.build());
I have used GridView inside the ViewPager, and when I try to update the GridView using the gridViewAdapter.notifydatasetchanged(), it doesn't updates. But when I scroll through all the pages and comes back to the original page, it shows the updated view. Im cluless, please help me someone how to deal with this.
I don't want to use the viewPager.notifydatsetchanged() as it reloads all the page items.
public class ViewPagerAdapter extends PagerAdapter {
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "FTICKERS";
case 1:
return "QUOTES";
case 2:
return "MEMES";
case 3:
return "MOVIES";
}
return null;
}
Context activity;
public ViewPagerAdapter(Context act) {
activity = act;
}
public int getCount() {
return 4;
}
#Override
public int getItemPosition(Object object) {
//return super.getItemPosition(object);
return POSITION_NONE;
}
public Object instantiateItem(View collection, final int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Context context = cont;
view0 = inflater.inflate(R.layout.fragment_f, null);
//send=view0;
gridview0 = (GridView) view0.findViewById(R.id.gridview_stickers_f);
imageAdapter0 = new ImageAdapter(context,"fticker");
gridview0.setAdapter(imageAdapter0);
view1 = inflater.inflate(R.layout.fragment_quotes, null);
//send=view0;
gridview1 = (GridView) view1.findViewById(R.id.gridview_stickers_quotes);
imageAdapter1 = new ImageAdapter(context,"quotes");
gridview1.setAdapter(imageAdapter1);
view2 = inflater.inflate(R.layout.fragment_memes, null);
//send=view0;
gridview2 = (GridView) view2.findViewById(R.id.gridview_stickers_memes);
imageAdapter2 = new ImageAdapter(context,"memes");
gridview2.setAdapter(imageAdapter2);
view3 = inflater.inflate(R.layout.fragment_movies, null);
//send=view0;
gridview3 = (GridView) view3.findViewById(R.id.gridview_stickers_movies);
imageAdapter3 = new ImageAdapter(context,"movies");
gridview3.setAdapter(imageAdapter3);
if(position==0)
{
send=view0;
folder="fticker";
Log.e("Folder Name is::",folder);
urlSet = new HashSet<String>();
imgUri = new HashSet<Uri>();
imgName = new HashSet<String>();
display = dialog.getWindow().getWindowManager().getDefaultDisplay();
metrics = new DisplayMetrics();
if(instFlag0==0) {
addDatatoAdapter(pg, null, "fticker");
instFlag0=1;
//Toast.makeText(cont,"Hola", Toast.LENGTH_SHORT).show();
}
gridview0.setOnScrollListener(new AbsListView.OnScrollListener() {
private int currentVisibleItemCount;
private int currentScrollState;
private int currentFirstVisibleItem;
private int totalItem;
private LinearLayout lBelow;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
this.currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
this.totalItem = totalItemCount;
}
private void isScrollCompleted() {
if (totalItem - currentFirstVisibleItem == currentVisibleItemCount
&& this.currentScrollState == SCROLL_STATE_IDLE) {
/** To do code here*/
//Toast.makeText(cont, "Scrolled down", Toast.LENGTH_SHORT).show();
Toast.makeText(cont, "0", Toast.LENGTH_SHORT).show();
pg++;
addDatatoAdapter(pg, null, "fticker");
//viewPagerAdapter.notifyDataSetChanged();
}
}
});
gridview0.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
ChatWidgetService.onShare(imageAdapter0.getUri(position));
}
});
gridview0.setTag(0);
((ViewPager) collection).addView(view0, 0);
return view0;
}
Loading the Dynamic values from to ListView in Android
it's purpose is:
resources is
retrieving the 10 items and placing in ListView,and
Thanks in Adv..
Here is my code
public class MainFucntions extends Activity {
ImageButton searchingpacksImg;
EditText searchEntry;
GridView searched_data_grid;
String entry;
String entry_from_db[];
List<String> disp_items_list;
Context context;
ArrayAdapter<String> adp;
int start = 0,limit = 10;
boolean flag_loading = false;
View loadMoreView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.allpackages);
getInits();
sortingOperations();
}
private void sortingOperations() {
searchingpacksImg.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
searched_data_grid.setTextFilterEnabled(true);
searched_data_grid.setAdapter(new ArrayAdapter<String>
(context,android.R.layout.simple_gallery_item,disp_items_list));
searched_data_grid.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int
totalItemCount) {
Log.e("onScroll First", ""+firstVisibleItem);
Log.e("onScroll totalItemCount", ""+totalItemCount);
Log.e("onScroll visibleItemCount", ""+visibleItemCount);
if(firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0)
{
if(flag_loading == false)
{
flag_loading = true;
additems();
}
}
}
private void additems() {
entry = searchEntry.getText().toString();
for(int i = 0 ; i < entry_from_db.length ; i++)
if(entry_from_db[i].contains(entry)){
disp_items_list.add(entry_from_db[i]);
}
flag_loading = false;
}
});
}
});
}
private void getInits() {
context = this;
searchingpacksImg = (ImageButton) findViewById(R.id.search);
searchEntry = (EditText) findViewById(R.id.searching_field);
searched_data_grid = (GridView) findViewById(R.id.searched_data);
disp_items_list = new ArrayList<String>();
entry_from_db = getResources().getStringArray(R.array.all_stations_names);
adp =new ArrayAdapter<String>
(context,android.R.layout.simple_gallery_item,entry_from_db);
searched_data_grid.setAdapter(adp);
}
}
I'm trying to do Autogrowin/Endless ListView but I have a problem with ArrayAdapter = update after downloading the data.
public class ListShowActivity extends ListActivity {
private ShowsAdapter m_adapter;
private ArrayList<ShowsList> showList = new ArrayList<ShowsList>();
// Adapter
private class ShowsAdapter extends ArrayAdapter<ShowsList>
{
private ArrayList<ShowsList> items = new ArrayList<ShowsList>();
public ShowsAdapter(Context context, int textViewResourceId, ArrayList<ShowsList> items)
{
super(context, textViewResourceId, items);
this.items = items;
}
public void appendList(ArrayList<ShowsList> results)
{
if((results != null) && (results.size() != 0))
{
m_adapter.add(results.get(0));
m_adapter.notifyDataSetChanged();
Log.i("test", "appendList: "+results.get(0).originalTitle);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
TextView tt = null;
TextView bt = null;
ImageView iv = null;
if (v == null){
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_show_item, null);
tt = (TextView) v.findViewById(R.id.showOriginalTitle);
bt = (TextView) v.findViewById(R.id.showTitle);
iv = (ImageView) v.findViewById(R.id.showPoster);
}
ShowsList item = this.items.get(position);
if (item != null) {
if(tt != null){
tt.setText(item.originalTitle);
}
if(bt != null){
bt.setText(item.title);
}
if(iv != null)
{
new DownloadImage().downloadImage(item.poster, iv);
}
}
return v;
}
}
// Implement new OnScrollListener
public class onScrollLoad implements OnScrollListener {
private int lastOffset = 10;
private int limit = 10;
private int mPrevTotalItemCount = 0;
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (((firstVisibleItem + visibleItemCount) >= totalItemCount) && totalItemCount != mPrevTotalItemCount) {
lastOffset = totalItemCount;
mPrevTotalItemCount = lastOffset;
limit += 1;
ArrayList<ShowsList> results = new Api().getShows(lastOffset, limit);
m_adapter.appendList(results);
//new PagingRequest(m_adapter).execute(lastOffset, limit);
Toast.makeText(getApplicationContext(), lastOffset+" / "+limit, Toast.LENGTH_SHORT).show();
}
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
Log.i("test", "onScrollStateChange()");
}
}
// Implement AsyncTask for download items?
/*
private static class PagingRequest extends AsyncTask<Integer, Void, ArrayList<ShowsList>> {
private ShowsAdapter mAdapter;
public PagingRequest(ShowsAdapter adapter) {
this.mAdapter = adapter;
}
protected ArrayList<ShowsList> doInBackground(Integer... params) {
return new Api().getShows(params[0], params[1]);
}
protected void onPostExecute(ArrayList<ShowsList> result) {
this.mAdapter.appendList(result);
}
}
*/
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.list_shows);
TextView tv = (TextView) findViewById(R.id.headerbarText);
tv.setText("List Shows");
// Get Items
Api a = new Api();
// First 10 items
showList = a.getShows(0, 0);
if(showList.isEmpty() == false)
{
//showList = new Api().getShows(0,0);
m_adapter = new ShowsAdapter(this, R.layout.list_show_item, showList);
setListAdapter(m_adapter);
ListView lv = getListView();
lv.setOnScrollListener(new onScrollLoad());
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Intent intent = new Intent(ListShowActivity.this, ShowActivity.class);
//intent.putExtra("showID", getShowsList.get(position).ID);
startActivity(intent);
}
});
}else{
Toast.makeText(getApplicationContext(), "NoData", Toast.LENGTH_SHORT).show();
}
}
}
I pasted code without working Asynctask.
In "theory"^^ everything works (appendList Log return correct value), but i as say i have problem with update ShowsAdapter (Download new image + and insert content to ListView)