Glide overlays screen with loaded image parts - java

Since i could not find anything related in the internet, this is gonna be my first SO question:
Problem Description
I am experiencing the following issue:
In my app i have a RecyclerView with a GridLayoutManager which is displaying images loaded by Glide.
When scrolling slowly everything will work alright.
After scrolling fast up and down (to an extend one could arguably call it "abuse of scrolling") some image parts or whole images will randomly overlay my screen, so that the content below is no longer visible. This is especially the case on the edges of the screen.
The testing device where the described error occurs is a OnePlus One running CM12.1.1 (Android 5.1.1). I didn't test on other devices.
Any hints / help / explanation on why this is happening or how to fix it are appreciated.
CODE
Below is the code for the Adapter with an inner ViewHolder class:
public class PhotoListAdapter extends RecyclerView.Adapter<PhotoListAdapter.PhotoHolder>{
private ArrayList<PhotoDetail> mPhotos;
private String mAccessToken;
private int mUserId;
private int mPageCounter = 1;
private boolean mIsLoading = false;
private boolean mEndReached = false;
public PhotoListAdapter (String accessToken, int userId){
mPhotos = new ArrayList<>();
mAccessToken = accessToken;
mUserId = userId;
fetchPhotos();
}
#Override
public PhotoHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.fragment_photo_list_item, parent, false);
PhotoHolder photoHolder = new PhotoHolder(itemView);
return photoHolder;
}
#Override
public void onBindViewHolder(PhotoHolder holder, int position) {
holder.bind(mPhotos.get(position));
if (position == mPhotos.size() - 6) fetchPhotos();
}
#Override
public int getItemCount() {
return mPhotos.size();
}
public void fetchPhotos () {
if (mIsLoading || mEndReached) return;
else {
mIsLoading = true;
//Retrofit call which will return a JSON Object with the Photo Details, like the filename
// With this information i can build the URL of the image
ApiProvider.getInstance().getApi().getPhotos(mUserId, mAccessToken, "time", "all", mPageCounter, mUserId, 32).enqueue(new Callback<PhotoResponseWrapper>() {
#Override
public void onResponse(Call<PhotoResponseWrapper> call, Response<PhotoResponseWrapper> response) {
if (response.code() == HttpURLConnection.HTTP_OK){
int photoCount = response.body().getPhotoResponse().getPhotosCount();
if (photoCount != 32) mEndReached = true;
Collections.addAll(mPhotos, response.body().getPhotoResponse().getPhotos());
notifyItemRangeInserted(mPhotos.size() - photoCount,photoCount);
mPageCounter++;
}
mIsLoading = false;
}
#Override
public void onFailure(Call<PhotoResponseWrapper> call, Throwable t) {
mIsLoading = false;
}
});
}
}
class PhotoHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView mPhotoView;
private PhotoDetail mPhotoDetail;
public PhotoHolder(View itemView) {
super(itemView);
mPhotoView = (ImageView) itemView.findViewById(R.id.img_photo);
mPhotoView.setOnClickListener(this);
}
public void bind (PhotoDetail photoDetail){
mPhotoDetail = photoDetail;
String photoUrl = Api.Endpoints.PHOTOS_SMALL + photoDetail.getUserId() + '/' + photoDetail.getFileName();
mPhotoView.setContentDescription(photoDetail.getDescription());
// First stop all pending image loads
Glide.clear(mPhotoView);
// Then load new url
Glide.with(mPhotoView.getContext())
.load(photoUrl)
.into(mPhotoView);
}
#Override
public void onClick(View v) {
}
}
}
Below is the XML of a single Item:
<?xml version="1.0" encoding="utf-8"?>
<ImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/img_photo"
android:clickable="true"
android:layout_width="match_parent"
android:layout_height="#dimen/height_photo_item"
android:padding="#dimen/padding_photo_item"
android:scaleType="centerCrop"/>
Below is the XML of the RecyclerView:
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layout_swipe_refresh"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingRight="#dimen/padding_photo_item"
android:paddingLeft="#dimen/padding_photo_item"
android:paddingTop="#dimen/padding_photo_item"
tools:context=".fragments.PhotoListFragment">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v4.widget.SwipeRefreshLayout>
EXAMPLES
Some visual examples of the bug are these screenshots:

You have to use placeholder image.
Glide.with(mPhotoView.getContext())
.load(photoUrl)
.placeholder(R.drawable.image_placeholder) // Your placeholder image
.into(mPhotoView);
I had the same problem and setting the placeholder eliminated it for me.

Since I couldn't find any information on how to fix this, i tried out the major alternative image loading & caching library - Picasso.
With this library the bug mentioned above wasn't reproducible for me, so i guess it is really Glide specific.

Related

How to show a page number on every page in a PDF using voghDev/PdfViewPager library?

It's been days of researching and I cannot figure out a way to do it.
Here is the link of the library on Github. Library
public class PDFViewActivity1 extends AppCompatActivity {
LinearLayout root;
EditText etPdfUrl;
Button btnDownload;
PDFPagerAdapter adapter;
String id;
ArrayList<String> topicLink;
File file;
String filePath;
PDFViewPager pdfViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
setContentView(R.layout.activity_p_d_f_view);
root = (LinearLayout) findViewById(R.id.remote_pdf_root);
final Context ctx = this;
Intent intent = getIntent();
String str = intent.getStringExtra("filePath");
str = str; // This contains the path of the PDF on my device
Log.i("filePathInString", str);
pdfViewPager = new PDFViewPager(ctx, str);
pdfViewPager.setId(R.id.pdfViewPager);
pdfViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
adapter = new PDFPagerAdapter(ctx, str);
pdfViewPager.setAdapter(adapter);
root.removeAllViewsInLayout();
root.addView(pdfViewPager,
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
}
#Override
protected void onDestroy() {
super.onDestroy();
((PDFPagerAdapter) pdfViewPager.getAdapter()).close();
}
}
The PDF renders perfectly form my device but I cannot see the page numbers, title , total pages of the PDF when the PDF is loaded.
This is my XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/remote_pdf_root"
android:orientation="vertical"
android:background="#FFFFFF"
tools:context=".PDFViewActivity1"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<es.voghdev.pdfviewpager.library.PDFViewPager
android:id="#+id/pdfViewPager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
What do I do when the page is scrolled, I cannot figure out a thing , I tried a lot of methods of the PDFAdapter but I an unsuccessful :( How can I do the task ?
RelativeLayout remotePdfRoot = findViewById(R.id.remote_pdf_root);
remotePDFViewPager = new RemotePDFViewPager(this, downloadFileUrlConnection, url, listener);
remotePDFViewPager.setId(R.id.pdfViewPager);
//after file loading success
PDFPagerAdapter adapter = new PDFPagerAdapter(this, FileUtil.extractFileNameFromURL(url));
remotePDFViewPager.setAdapter(adapter);
updateLayout();
private void updateLayout() {
remotePdfRoot.removeAllViewsInLayout();
remotePdfRoot.addView(remotePDFViewPager, LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
}
I preview pdf this way and there will be a pagenumber.
You can use https://github.com/barteksc/AndroidPdfViewer library for this and you can get the page count by
`vpPdf.fromAsset("sample.pdf").onError {
Log.i(TAG, "${it.localizedMessage}")
it.printStackTrace()
}.onPageError { _, t ->
t.printStackTrace()
}.enableSwipe(true).swipeHorizontal(true).onPageChange { page, pageCount ->
//here page count is count of page user currently is viewing.
}.load()`
I had to use this lib at work and it is working perfectly fine!!
The above code is from kotlin but you can convert it to java i guess,If you are not able to convert it the kindly comment so i will help you with that too!!.

FrameLayout cannot be cast to AbsListView Layout Params

I have an strange issue I have the nexts code files:
result_suggestion.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/result_suggestion_container"
android:orientation="vertical"
android:background="#fff">
<!--android:visibility="gone"-->
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/result_list"
android:scrollbars="vertical" />
</LinearLayout>
results_suggestions_footer.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:background="#e6e9ea">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="250dp"
android:layout_marginTop="10dp"
android:contentDescription="#string/results_suggestion_footer"
app:srcCompat="#drawable/ic_baseline_search_24px" />
<Button
android:id="#+id/keep_searching"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/search_button"
android:text="#string/quotes_suggestion_footer" />
<!--android:drawableEnd="#drawable/ic_baseline_search_24px"-->
</RelativeLayout>
bidAdapter.java:
package com.my.app.ui.adapters;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.my.app.R;
import com.my.app.api.models.sonnet;
import com.my.app.api.models.sonnetbid;
import com.my.app.api.interfaces.SuggestionListItem;
import java.util.ArrayList;
import java.util.List;
import javax.security.auth.login.LoginException;
/**
* Class of the custom adapter for the suggestions list of bids.
*
* #author Dennis Mostajo on 1/18/18
*/
public class bidAdapter extends BaseAdapter {
private static final int sonnet = 0;
private static final int bid = 1;
private List<SuggestionListItem> mSuggestions;
private LayoutInflater mInflater;
//===========================================================================
// CONSTRUCTOR
//===========================================================================
/**
* Custom constructor implementation in charge of the initialization of internal members
*
* #param context application context for the layout inflater initialization
*/
public bidAdapter(Context context) {
this.mSuggestions = new ArrayList<>();
this.mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
//===========================================================================
// OVERRIDE METHODS
//===========================================================================
#Override
public int getCount() {
return mSuggestions.size();
}
#Override
public Object getItem(int position) {
return mSuggestions.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int position) {
if(mSuggestions.get(position).getInstanceType() == SuggestionListItem.InstanceType.sonnet) {
return sonnet;
} else {
return bid;
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
int cellType = getItemViewType(position);
if (convertView == null) {
holder = new ViewHolder();
switch(cellType) {
case sonnet:
convertView = mInflater.inflate(R.layout.source_cell, null);
holder.mSource = convertView.findViewById(R.id.source);
holder.mSourceInformation = convertView.findViewById(R.id.source_information);
break;
case bid:
convertView = mInflater.inflate(R.layout.bid_cell, null);
holder.mbid = convertView.findViewById(R.id.bid);
holder.mbidInformation = convertView.findViewById(R.id.bid_information);
break;
}
if (convertView != null) {
convertView.setTag(holder);
}
} else {
holder = (ViewHolder)convertView.getTag();
}
switch (cellType) {
case sonnet:
holder.mSource.setText(((sonnet) mSuggestions.get(position)).getContent());
holder.mSourceInformation.setText("");
break;
case bid:
holder.mbid.setText(((sonnetbid) mSuggestions.get(position)).getText());
sonnet sonnet = ((sonnetbid) mSuggestions.get(position)).getsonnet();
String text = String.format("%s%s%s%s%s%s%s", " (", sonnet.getBook(), " ", sonnet
.getChapter(), ":", sonnet.getsonnetNumber(), ").");
holder.mbidInformation.setText(text);
break;
}
return convertView;
}
//===========================================================================
// CUSTOM METHODS
//===========================================================================
/**
* Method used to update the list of suggestions to be given to the user
*
* #param suggestions list containing suggested bids and stanzas
*/
public void updateSuggestions(List<SuggestionListItem> suggestions) {
if(suggestions != null) {
this.mSuggestions.clear();
this.mSuggestions = suggestions;
this.notifyDataSetChanged();
}
}
//===========================================================================
// PRIVATE CLASSES
//===========================================================================
/**
* Class for the implementation of the ViewHolder design pattern used to represent the bids
* and stanzas cells.
*/
private static class ViewHolder {
private TextView mbid;
private TextView mbidInformation;
private TextView mSource;
private TextView mSourceInformation;
}
}
and when I using my keyboardIME:
private View initInputView() {
mCurrentTheme = ThemeManager.getInstance(this).getTheme();
mKeyboardView.setKeyboard(mKeyboard);
mKeyboardView.setOnKeyboardActionListener(this);
mInflater = (LayoutInflater) this.getSystemService(Context
.LAYOUT_INFLATER_SERVICE);
mSuggestionsView = mInflater.inflate(R.layout.result_suggestion, null);
mResultListFooter = mInflater.inflate(R.layout.results_suggestion_footer, null);
initAlternativeCandidatesView();
mResultList = mSuggestionsView.findViewById(R.id.result_list);
mResultList.addFooterView(mResultListFooter);
mResultsAdapter = new bidAdapter(this);
mResultList.setAdapter(mResultsAdapter);
mResultList.setOnItemClickListener((AdapterView<?> parent, View view, int position,
long id) -> {
SuggestionListItem item = (SuggestionListItem) mResultsAdapter
.getItem(position);
});
return mKeyboardView;
}
#Override
protected void onPostExecute(SearchRequestResult result) {
switch (result) {
case SUCCESS:
if(mSonnetBidResult.size() > 0) {
List<SuggestionListItem> bidSonnetList = new ArrayList<>(
mSonnetBidResult);
mQuotesIME.get().mResultsAdapter.updateSuggestions(bisSonnetList);
// the crash is here
mQuotesIME.get().mQuoteList.setAdapter(mQuotesIME.get().mResultsAdapter);// IMEKeyboard.java:2305
mQuotesIME.get().mResultsAdapter);
// Added by Dennis Try to fix Height of suggestions lists
if (mSonnetBidResult.size() > 2) {
mQuotesIME.get().maximize_quote_lists();
} else {
mQuotesIME.get().minimize_quote_lists();
}
mQuotesIME.get().setCandidatesView(mQuotesIME.get().mSuggestionsView);
} else {
mQuotesIME.get().updateWaitingCandidateView(mQuotesIME.get().getString(R
.string.no_results_label));
}
break;
case ERROR:
try {
JSONObject jsonObject = new JSONObject(this.mErrorMessage);
int minLength = jsonObject.getInt("min_phrase_len");
if(minLength > 0) {
mQuotesIME.get().updateWaitingCandidateView(mQuotesIME.get().getString(
R.string.length_error).replace("{int}", String.valueOf(
minLength)));
} else {
mQuotesIME.get().updateWaitingCandidateView(mQuotesIME.get().getString(
R.string.no_phrase_error));
}
} catch (JSONException e) {
Crashlytics.log("Error extracting message from /search call: "
+ e.getMessage());
e.printStackTrace();
}
break;
}
}
}
}
ERROR CRASH:
07-16 14:41:09.488 21099-21099/com.my.app D/AndroidRuntime: Shutting down VM
07-16 14:41:09.514 21099-21099/com.my.app E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.my.app, PID: 21099
java.lang.ClassCastException: android.widget.FrameLayout$LayoutParams cannot be cast to android.widget.AbsListView$LayoutParams
at android.widget.ListView.clearRecycledState(ListView.java:627)
at android.widget.ListView.resetList(ListView.java:614)
at android.widget.ListView.setAdapter(ListView.java:557)
at com.my.app.services.IMEKeyboard$resultSearchAsyncTask.onPostExecute(IMEKeyboard.java:2305)
at com.my.app.services.IMEKeyboard$resultSearchAsyncTask.onPostExecute(IMEKeyboard.java:2175)
at android.os.AsyncTask.finish(AsyncTask.java:695)
at android.os.AsyncTask.-wrap1(Unknown Source:0)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
07-16 14:41:11.786 21099-21151/com.my.app I/CrashlyticsCore: Crashlytics report upload complete: 5D2E1A3601BE-0001-526B-29AD77A5B0D7
I have a strange issue setting up an adapter for a ListView, the ListView is inside the CandidateView of a custom keyboard, I use a class that inherit of AsyncTask class to execute an API call that returns me a list of items to be displayed on a ListView, in the method onPostExecute() of AsyncTask I take the search results and add to an ArrayList, then this array is being passed to the adapter using the method updateResults(), and finally set the ListView's adapter, everything is fine until here, the code compiles, but during runtime I get the next error:
java.lang.ClassCastException: android.widget.FrameLayout$LayoutParams cannot be cast to android.widget.AbsListView$LayoutParams
ANY HELP PLEASE?, how can I fix it?
Thank you very much for your time
As I see, this issue can come from the wrong LayoutParams. ListView implementation expects AbsListView.LayoutParams and not FrameLayout.LayoutParams. I guess, one of your layout (source_cell.xml or bid_cell.xml) has a FrameLayout as root view. This is not a problem but you would fix the inflation method to get proper LayoutParams.
Change this in bidAdapter.java inside of getView() method:
convertView = mInflater.inflate(R.layout.source_cell, null);
To this:
convertView = mInflater.inflate(R.layout.source_cell, parent, false);
This inflation procedure will know the candidate parent where inflated view would be placed. This allows it to inflate with proper LayoutParam. The next false parameter are going to prevent to add child view automatically. (Because ListView implementation will add later)
For all I can see the error occurs a few calls after setting the adapter and happen inside the ListView, this is a complicated issue to fix taking into account the line of code where is crashing, also is hard to get this wrong without a warning from Android Studio or the compiler, so my suggestion is to use RecyclerView instead of the ListView, RecyclerView is a more advanced and flexible version of ListView, is easy to implement and I'm pretty sure that will fix your issue in the app. Follow this link and you will find a good example on how to implement the RecyclerView.

React Native: How to invoke native Android layout from module?

Regarding this question, I've been trying to get this done via native modules in Android.
I've declared my Module at .../java/com/myproject/multiplecamerastream following the example at React Native ToastModule (functionality here is not important):
public class MultipleCameraStreamModule extends ReactContextBaseJavaModule {
private static final String CAMERA_FRONT = "SHORT";
private static final String CAMERA_BACK = "LONG";
public MultipleCameraStreamModule(ReactApplicationContext reactContext) {
super(reactContext);
}
#Override
public String getName() {
return "MultipleCameraStream";
}
#Override
public Map<String, Object> getConstants() {
final Map<String, Object> constants = new HashMap<>();
constants.put(CAMERA_FRONT, Toast.LENGTH_SHORT);
constants.put(CAMERA_BACK, Toast.LENGTH_LONG);
return constants;
}
#ReactMethod
public void show(String message, int duration) {
Toast.makeText(getReactApplicationContext(), message, duration).show();
}
}
Then, my module packager:
public class MultipleCameraStreamPackage implements ReactPackage {
#Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
#Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new MultipleCameraStreamModule(reactContext));
return modules;
}
}
I've been able to register it and to make it work. However, it only calls to a Toast in Android (no layout involved).
I'd like to set a layout, so when I call <MultipleCameraStream /> in JSX it renders a native Android layout, like the following:
/* .../multiplecamerastream/MultipleCameraStreamLayout.xml */
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView android:id="#+id/multipleCameraText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a TextView"
/>
<Button android:id="#+id/multipleCameraButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, I am a Button"
/>
</LinearLayout>
How can I make that layout to be invoked from my module scripts (MultipleCameraStreamModule), and how can I make reference to its elements so I can interact with them from the Android module side programatically?
Thank you.
There's explanation in the RN Native UI website itself, but I got lost in it too. :(
But here goes, let me know if there's improvement needed on this:
1) Create a View that will inflate your xml MultipleCameraStreamLayout.xml. Ideally, this CustomView can be used in Android pure code.
public class CustomView extends LinearLayout {
private Context context;
public CustomView(Context context) {
super(context);//ADD THIS
this.context = context;
}
..
public void init() {
//modified here.
inflate(context, R.layout.xxxxxxxxx, this);
...
2) Once set, put this into another class(View Manager) extending SimpleViewManager. Sample:
public class MyCustomReactViewManager extends SimpleViewManager<CustomView> {
public static final String REACT_CLASS = "MyCustomReactViewManager";
#Override
public String getName() {
return REACT_CLASS;
}
#Override
public CustomView createViewInstance(ThemedReactContext context) {
return new CustomView(context); //If your customview has more constructor parameters pass it from here.
}
3) Now add it into the React package createViewManager method, you have created it in MultipleCameraStreamPackage. So, it'll be:
#Override
public List<ViewManager> createViewManagers(
ReactApplicationContext reactContext) {
return Arrays.<ViewManager>asList(
new MyCustomReactViewManager() //Add here.
);
}
4) You can now use the Android code, by reinstalling it
react-native run-android
5) Expose it in javascript. Create some file CustomView.js
import {requireNativeComponent, ViewPropTypes} from 'react-native';
//
module.exports = requireNativeComponent('MyCustomReactViewManager', null); //Add props are bit different.
6) Start using it into your views. Eg.
import CustomView from './CustomView.js';
...
render() {
return
...
<CustomView style={{height:200, width:200}}/>
...;
}
Hope this helps.
If you need a code sample it's uploaded here.

Android RecyclerView addition & removal of items

I have a RecyclerView with an TextView text box and a cross button ImageView. I have a button outside of the recyclerview that makes the cross button ImageView visible / gone.
I'm looking to remove an item from the recylerview, when that items cross button ImageView is pressed.
My adapter:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> implements View.OnClickListener, View.OnLongClickListener {
private ArrayList<String> mDataset;
private static Context sContext;
public MyAdapter(Context context, ArrayList<String> myDataset) {
mDataset = myDataset;
sContext = context;
}
#Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_text_view, parent, false);
ViewHolder holder = new ViewHolder(v);
holder.mNameTextView.setOnClickListener(MyAdapter.this);
holder.mNameTextView.setOnLongClickListener(MyAdapter.this);
holder.mNameTextView.setTag(holder);
return holder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.mNameTextView.setText(mDataset.get(position));
}
#Override
public int getItemCount() {
return mDataset.size();
}
#Override
public void onClick(View view) {
ViewHolder holder = (ViewHolder) view.getTag();
if (view.getId() == holder.mNameTextView.getId()) {
Toast.makeText(sContext, holder.mNameTextView.getText(), Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onLongClick(View view) {
ViewHolder holder = (ViewHolder) view.getTag();
if (view.getId() == holder.mNameTextView.getId()) {
mDataset.remove(holder.getPosition());
notifyDataSetChanged();
Toast.makeText(sContext, "Item " + holder.mNameTextView.getText() + " has been removed from list",
Toast.LENGTH_SHORT).show();
}
return false;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mNumberRowTextView;
public TextView mNameTextView;
public ViewHolder(View v) {
super(v);
mNameTextView = (TextView) v.findViewById(R.id.nameTextView);
}
}
}
My layout is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_vertical"
android:id="#+id/layout">
<TextView
android:id="#+id/nameTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp"
android:padding="5dp"
android:background="#drawable/greyline"/>
<ImageView
android:id="#+id/crossButton"
android:layout_width="16dp"
android:layout_height="16dp"
android:visibility="gone"
android:layout_marginLeft="50dp"
android:src="#drawable/cross" />
</LinearLayout>
How can I get something like an onClick working for my crossButton ImageView? Is there a better way? Maybe changing the whole item onclick into a remove the item? The recyclerview shows a list of locations that need to be edited. Any technical advice or comments / suggestions on best implementation would be hugely appreciated.
I have done something similar.
In your MyAdapter:
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public CardView mCardView;
public TextView mTextViewTitle;
public TextView mTextViewContent;
public ImageView mImageViewContentPic;
public ImageView imgViewRemoveIcon;
public ViewHolder(View v) {
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
mTextViewTitle = (TextView) v.findViewById(R.id.item_title);
mTextViewContent = (TextView) v.findViewById(R.id.item_content);
mImageViewContentPic = (ImageView) v.findViewById(R.id.item_content_pic);
//......
imgViewRemoveIcon = (ImageView) v.findViewById(R.id.remove_icon);
mTextViewContent.setOnClickListener(this);
imgViewRemoveIcon.setOnClickListener(this);
v.setOnClickListener(this);
mTextViewContent.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View view) {
if (mItemClickListener != null) {
mItemClickListener.onItemClick(view, getPosition());
}
return false;
}
});
}
#Override
public void onClick(View v) {
//Log.d("View: ", v.toString());
//Toast.makeText(v.getContext(), mTextViewTitle.getText() + " position = " + getPosition(), Toast.LENGTH_SHORT).show();
if(v.equals(imgViewRemoveIcon)){
removeAt(getPosition());
}else if (mItemClickListener != null) {
mItemClickListener.onItemClick(v, getPosition());
}
}
}
public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}
public void removeAt(int position) {
mDataset.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, mDataSet.size());
}
Edit:
getPosition() is deprecated now, use getAdapterPosition() instead.
first of all, item should be removed from the list!
mDataSet.remove(getAdapterPosition());
then:
notifyItemRemoved(getAdapterPosition());
notifyItemRangeChanged(getAdapterPosition(), mDataSet.size()-getAdapterPosition());
if still item not removed use this magic method :)
private void deleteItem(int position) {
mDataSet.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, mDataSet.size());
holder.itemView.setVisibility(View.GONE);
}
Kotlin version
private fun deleteItem(position: Int) {
mDataSet.removeAt(position)
notifyItemRemoved(position)
notifyItemRangeChanged(position, mDataSet.size)
holder.itemView.visibility = View.GONE
}
The Problem
RecyclerView was built to display data in an efficient and responsive manner.
Usually you have a dataset which is passed to your adapter and is looped through to display your data.
Here your dataset is:
private ArrayList<String> mDataset;
The point is that RecyclerView is not connected to your dataset, and therefore is unaware of your dataset changes.
It just reads data once and displays it through your ViewHolder, but a change to your dataset will not propagate to your UI.
This means that whenever you make a deletion/addition on your data list, those changes won't be reflected to your RecyclerView directly. (i.e. you remove the item at index 5, but the 6th element remains in your recycler view).
A (old school) solution
RecyclerView exposes some methods for you to communicate your dataset changes, reflecting those changes directly on your list items.
The standard Android APIs allow you to bind the process of data removal (for the purpose of the question) with the process of View removal.
The methods we are talking about are:
notifyItemChanged(index: Int)
notifyItemInserted(index: Int)
notifyItemRemoved(index: Int)
notifyItemRangeChanged(startPosition: Int, itemCount: Int)
notifyItemRangeInserted(startPosition: Int, itemCount: Int)
notifyItemRangeRemoved(startPosition: Int, itemCount: Int)
A Complete (old school) Solution
If you don't properly specify what happens on each addition, change or removal of items, RecyclerView list items are animated unresponsively because of a lack of information about how to move the different views around the list.
The following code will allow RecyclerView to precisely play the animation with regards to the view that is being removed (And as a side note, it fixes any IndexOutOfBoundExceptions, marked by the stacktrace as "data inconsistency").
void remove(position: Int) {
dataset.removeAt(position)
notifyItemChanged(position)
notifyItemRangeRemoved(position, 1)
}
Under the hood, if we look into RecyclerView we can find documentation explaining that the second parameter we pass to notifyItemRangeRemoved is the number of items that are removed from the dataset, not the total number of items (As wrongly reported in some others information sources).
/**
* Notify any registered observers that the <code>itemCount</code> items previously
* located at <code>positionStart</code> have been removed from the data set. The items
* previously located at and after <code>positionStart + itemCount</code> may now be found
* at <code>oldPosition - itemCount</code>.
*
* <p>This is a structural change event. Representations of other existing items in the data
* set are still considered up to date and will not be rebound, though their positions
* may be altered.</p>
*
* #param positionStart Previous position of the first item that was removed
* #param itemCount Number of items removed from the data set
*/
public final void notifyItemRangeRemoved(int positionStart, int itemCount) {
mObservable.notifyItemRangeRemoved(positionStart, itemCount);
}
Open source solutions
You can let a library like FastAdapter, Epoxy or Groupie take care of the business, and even use an observable recycler view with data binding.
New ListAdapter
Google recently introduced a new way of writing the recycler view adapter, which works really well and supports reactive data.
It is a new approach and requires a bit of refactoring, but it is 100% worth switching to it, as it makes everything smoother.
here is the documentation, and here a medium article explaining it
Here are some visual supplemental examples. See my fuller answer for examples of adding and removing a range.
Add single item
Add "Pig" at index 2.
String item = "Pig";
int insertIndex = 2;
data.add(insertIndex, item);
adapter.notifyItemInserted(insertIndex);
Remove single item
Remove "Pig" from the list.
int removeIndex = 2;
data.remove(removeIndex);
adapter.notifyItemRemoved(removeIndex);
Possibly a duplicate answer but quite useful for me. You can implement the method given below in RecyclerView.Adapter<RecyclerView.ViewHolder>
and can use this method as per your requirements, I hope it will work for you
public void removeItem(#NonNull Object object) {
mDataSetList.remove(object);
notifyDataSetChanged();
}
I tried all the above answers, but inserting or removing items to recyclerview causes problem with the position in the dataSet. Ended up using delete(getAdapterPosition()); inside the viewHolder which worked great at finding the position of items.
The problem I had was I was removing an item from the list that was no longer associated with the adapter to make sure you are modifying the correct adapter you can implement a method like this in your adapter:
public void removeItemAtPosition(int position) {
items.remove(position);
}
And call it in your fragment or activity like this:
adapter.removeItemAtPosition(position);
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private Context context;
private List<cardview_widgets> list;
public MyAdapter(Context context, List<cardview_widgets> list) {
this.context = context;
this.list = list;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(this.context).inflate(R.layout.fragment1_one_item,
viewGroup, false);
return new MyViewHolder(view);
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView txtValue;
TextView txtCategory;
ImageView imgInorEx;
ImageView imgCategory;
TextView txtDate;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
txtValue= itemView.findViewById(R.id.id_values);
txtCategory= itemView.findViewById(R.id.id_category);
imgInorEx= itemView.findViewById(R.id.id_inorex);
imgCategory= itemView.findViewById(R.id.id_imgcategory);
txtDate= itemView.findViewById(R.id.id_date);
}
}
#NonNull
#Override
public void onBindViewHolder(#NonNull final MyViewHolder myViewHolder, int i) {
myViewHolder.txtValue.setText(String.valueOf(list.get(i).getValuee()));
myViewHolder.txtCategory.setText(list.get(i).getCategory());
myViewHolder.imgInorEx.setBackgroundColor(list.get(i).getImg_inorex());
myViewHolder.imgCategory.setImageResource(list.get(i).getImg_category());
myViewHolder.txtDate.setText(list.get(i).getDate());
myViewHolder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
list.remove(myViewHolder.getAdapterPosition());
notifyDataSetChanged();
return false;
}
});
}
#Override
public int getItemCount() {
return list.size();
}}
i hope this help you.
if you want to remove item you should do this:
first remove item:
phones.remove(position);
in next step you should notify your recycler adapter that you remove an item by this code:
notifyItemRemoved(position);
notifyItemRangeChanged(position, phones.size());
but if you change an item do this:
first change a parameter of your object like this:
Service s = services.get(position);
s.done = "Cancel service";
services.set(position,s);
or new it like this :
Service s = new Service();
services.set(position,s);
then notify your recycler adapter that you modify an item by this code:
notifyItemChanged(position);
notifyItemRangeChanged(position, services.size());
hope helps you.
String str = arrayList.get(position);
arrayList.remove(str);
MyAdapter.this.notifyDataSetChanged();
To Method onBindViewHolder Write This Code
holder.remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Cursor del=dbAdapter.ExecuteQ("delete from TblItem where Id="+values.get(position).getId());
values.remove(position);
notifyDataSetChanged();
}
});
Incase Anyone wants to implement something like this in Main class instead of Adapter class, you can use:
public void removeAt(int position) {
peopleListUser.remove(position);
friendsListRecycler.getAdapter().notifyItemRemoved(position);
friendsListRecycler.getAdapter().notifyItemRangeChanged(position, peopleListUser.size());
}
where friendsListRecycler is the Adapter name
you must to remove this item from arrayList of data
myDataset.remove(holder.getAdapterPosition());
notifyItemRemoved(holder.getAdapterPosition());
notifyItemRangeChanged(holder.getAdapterPosition(), getItemCount());
//////// set the position
holder.cancel.setTag(position);
///// click to remove an item from recycler view and an array list
holder.cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int positionToRemove = (int)view.getTag(); //get the position of the view to delete stored in the tag
mDataset.remove(positionToRemove);
notifyDataSetChanged();
}
});
make interface into custom adapter class and handling click event on recycler view..
onItemClickListner onItemClickListner;
public void setOnItemClickListner(CommentsAdapter.onItemClickListner onItemClickListner) {
this.onItemClickListner = onItemClickListner;
}
public interface onItemClickListner {
void onClick(Contact contact);//pass your object types.
}
#Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
// below code handle click event on recycler view item.
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onItemClickListner.onClick(mContectList.get(position));
}
});
}
after define adapter and bind into recycler view called below code..
adapter.setOnItemClickListner(new CommentsAdapter.onItemClickListner() {
#Override
public void onClick(Contact contact) {
contectList.remove(contectList.get(contectList.indexOf(contact)));
adapter.notifyDataSetChanged();
}
});
}
In case you are wondering like I did where can we get the adapter position in the method getadapterposition(); its in viewholder object.so you have to put your code like this
mdataset.remove(holder.getadapterposition());
In the activity:
mAdapter.updateAt(pos, text, completed);
mAdapter.removeAt(pos);
In the your adapter:
void removeAt(int position) {
list.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, list.size());
}
void updateAt(int position, String text, Boolean completed) {
TodoEntity todoEntity = list.get(position);
todoEntity.setText(text);
todoEntity.setCompleted(completed);
notifyItemChanged(position);
}
in 2022, after trying everything the whole internet given below is the answer
In MyViewHolder class
private myAdapter adapter;
inside MyViewHolder function initalise adapter
adapter = myAdapter.this
inside onclick
int position = getAdapterPosition()
list.remove(position);
adapter.notifyItemRemoved(position);

How to create an expandable list?

I need to create Collapse / Expand forms in Android. I am thinking about using either RelativeLayout or TableLayout for this purpose. But, what XML element make these forms expand and hide in android?
If you are not sure what I am not talking about, take an application like Sales Force for an example. There you have these expandable menus in all the forms. How can I do this?
Following is an example (taken from Sales Force)
When you expand these, it looks like below
You could do the following. create a layout that has the following:
1. A Heading or a textview with the label contacts
2. Below it a layout that has forms related to it
3. Add another textview below #2 and name it address
4. Add a lyout below #3 .
The layout 2 and 4 will have visibility gone in the first case
When the user taps on layout 1, or the first textview, make layout 2 visible and vice versa. Do the same with the second textview.
Hope that helps.!
I have had a similar problem, i want parts of my form to be hidden in sektions and created a class for this issue.
public class section extends LinearLayout{
public LinearLayout container;
public Button toggler;
public section(Context context, String section_name, String section_state) {
super(context);
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.flxsection, this);
container = (LinearLayout) this.findViewById(R.id.container);
container.setVisibility(section_state.equals("0") ? View.GONE:View.VISIBLE);
toggler = ((Button)this.findViewById(R.id.section_toggle));
toggler.setTag(section_state);
toggler.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
String tag = (String) v.getTag();
v.setTag(tag.equals("0") ? "1":"0");
if(tag.equals("0")){expand(container,false);}else{collapse(container,false);}
setImage(tag.equals("0"));
}
});
toggler.setText(" " + section_name);
setImage(section_state.equals("1"));
setTextSize();
}
public void setTextSize(){
toggler.setTextSize(GV.Style.TextSize);
}
public void setImage(boolean open){
int a = open ? R.drawable.minus_48_white: R.drawable.plus_48_white;
Drawable img = main.res.getDrawable(a);
final float scale = main.res.getDisplayMetrics().density;
int size = (int) (12 * scale + 0.5f);
img.setBounds(0,0,size,size);
toggler.setCompoundDrawables(img,null,null,null);
}
}
the 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:background="#android:color/transparent"
android:focusable="false"
android:layout_marginLeft="4dip"
android:layout_marginRight="4dip"
android:orientation="vertical" >
<Button
android:id="#+id/section_toggle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="4dip"
android:layout_marginTop="4dip"
android:background="#drawable/section"
android:drawableLeft="#drawable/plus_48"
android:focusable="false"
android:gravity="left|center_vertical"
android:padding="6dip"
android:textAppearance="?android:attr/textAppearanceLargeInverse"
android:textSize="22dip" />
<LinearLayout
android:id="#+id/container"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusable="false"
android:background="#android:color/transparent"
android:orientation="vertical" >
</LinearLayout>
Expand and collapse:
public static void expand(final View v,boolean quick) {
v.requestLayout();
v.measure(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
final int targtetHeight = v.getMeasuredHeight();
v.getLayoutParams().height = 0;
v.getLayoutParams().width = LayoutParams.FILL_PARENT;
v.setVisibility(View.VISIBLE);
if(quick){
v.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
v.requestLayout();
}else{
android.view.animation.Animation a = new android.view.animation.Animation()
{
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
v.getLayoutParams().height = interpolatedTime == 1
? LayoutParams.WRAP_CONTENT
: (int)(targtetHeight * interpolatedTime);
v.requestLayout();
}
#Override
public boolean willChangeBounds() {
return true;
}
};
// 1dp/ms
int duration = (int)(targtetHeight / v.getContext().getResources().getDisplayMetrics().density);
if(duration> 500)duration=500;
a.setDuration(duration);
//(int)(targtetHeight / v.getContext().getResources().getDisplayMetrics().density)
v.startAnimation(a);
}
}
public static void collapse(final View v,boolean quick) {
v.requestLayout();
final int initialHeight = v.getMeasuredHeight();
if(quick){
v.setVisibility(View.GONE);
v.requestLayout();
}else{
android.view.animation.Animation a = new android.view.animation.Animation()
{
#Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
if(interpolatedTime == 1){
v.setVisibility(View.GONE);
}else{
v.getLayoutParams().height = initialHeight - (int)(initialHeight * interpolatedTime);
v.requestLayout();
}
}
#Override
public boolean willChangeBounds() {
return true;
}
};
// 1dp/ms
int duration = (int)( initialHeight/ v.getContext().getResources().getDisplayMetrics().density);
if(duration> 500)duration=500;
a.setDuration(duration);
v.startAnimation(a);
}
}
If if create a form and need a section, i create a instance of this class and add the controls.
You might need to turn the hardware acceleration on in order to get the best performance
edit:
Usage is like:
section s = new section(context, section_name, section_state);
s.container.addView([your view 1]);
s.container.addView([your view 2]);
s.container.addView([your view 3]);
//...
form.addView(s);

Categories

Resources