Android FlexBox Layout shows only fixed number of lines - android

I'm trying to build a word-to-word RTL language ebook application. The data for the ebook is stored in an Sqlite database. After vigorous searching I found Flexbox layout suitable to my need in order to display my data in my required format. The following link helped me out: Android GridLayout with dynamic number of columns per row But the issue is that if the data passed in the view is large, then partial data is being displayed. If the data passed is small, then i have no issues at all.
Here is the adapter code:
public class VerseAdapter extends RecyclerView.Adapter<VerseAdapter.ViewHolder> {
private List<verseItem> items;
private Context context;
wordsAdapter sAdapter;
GridLayoutManager layoutManager;
public VerseAdapter(List<verseItem> items, Context context) {
this.items = items;
this.context = context;
}
// This method is used to attach
// custom layout to the recycler view
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View vw = LayoutInflater.from(parent.getContext()).inflate(R.layout.verse_row, parent, false);
return new ViewHolder(vw);
}
// This method is used to set the action
// to the widgets of our custom layout.
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
verseItem item = items.get(position);
ArrayList<wordsModel> models = new ArrayList<>(item.getWordsModelList());
String ayahnum = "" + item.getAyah();
holder.ayah.setText(ayahnum);
holder.verses_telugu.setText(item.getVerses_telugu());
// FlexboxLayoutManager code:
FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(context);
layoutManager.setFlexDirection(FlexDirection.ROW_REVERSE);
layoutManager.setJustifyContent(JustifyContent.FLEX_START);
ViewHolder.wordsrecyclerView.setLayoutManager(layoutManager);
sAdapter = new wordsAdapter(models);
ViewHolder.wordsrecyclerView.setAdapter(sAdapter);
sAdapter.notifyItemChanged(position);
holder.setIsRecyclable(false);
}
#Override
public int getItemCount() {
return items.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView ayah;
TextView verses_telugu;
public static RecyclerView wordsrecyclerView;
public ViewHolder(View itemView) {
super(itemView);
ayah = itemView.findViewById(R.id.ayah);
verses_telugu = itemView.findViewById(R.id.telugu_line);
wordsrecyclerView = itemView.findViewById(R.id.words_RV_id);
}
}
}
Here is my layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/ayah"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_margin="5dp"
android:textAlignment="viewStart"
android:textColor="#27A82C"
android:textSize="18sp"
android:textStyle="bold" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/words_RV_id"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/telugu_line"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_margin="5dp"
android:textAlignment="textStart"
android:textSize="16sp"
android:textStyle="bold" />
</LinearLayout>
This is how the final result show actually look like:
This is how my app looks like:
Now if you notice from the screenshots, the data that i'm trying to display is same. But in my app, not all words are being displayed as you can notice.
Another thing i have noticed is for larger data if the screen orientation is vertical the maximum lines i can see is 10 and if it is horizontal i can see 6 lines at max. These number of lines are fixed for all the places where the data is large. If the data is smaller it is displayed in the exact number of lines required and as mentioned earlier I have no issues at all.
Hoping someone helps me out soon. Thanks in advance. (:

Related

Layout view does not wrap content after scrolling

I am using a recycler view to show some data. When the app is launched it looks correct as follows with wrap content for height. After I scroll past the last item, I am able to keep scrolling and the data is no longer wrapped, looking like match parent instead for height. Scrolling back up, everything has changed to match parent for the height.
Using past references here, I have tried with ConstraintLayouts and switched height wrapping between the parent layout and the recyclerview itself. Both doesn't help. I am guessing this has to do more with the xml. Please advice.
This is what I expect to always get. This is what I current get when app launches, but changes after I scroll to last item.
When I scroll to last item this happens.
Now if I scroll back up, the height is no longer wrapped. Everything seems to have changed to match parent.
This is xml for the custom view I am using to inflate.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/feed_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/feed_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingTop="5dp"
android:paddingRight="10dp"
android:textSize="18sp"
app:layout_constraintTop_toTopOf="parent"
tools:layout_editor_absoluteX="0dp"
tools:text="Test Title" />
<TextView
android:id="#+id/feed_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textSize="12sp"
app:layout_constraintTop_toBottomOf="#+id/feed_title"
tools:layout_editor_absoluteX="0dp"
android:layout_below="#+id/feed_title"
tools:text="This is some random description for testing purposes. Other wise just typing on to create more stuff..." />
</RelativeLayout>
This is layout for the Recycler View which is placed on a Fragment activity.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".fragment.CurrentFeedFragment">
<android.support.v7.widget.RecyclerView
android:id="#+id/current_recycler_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
This is over at my FragmentActivity where I am loading the data for the RecyclerView.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_current_feed, container, false);
initiateTestData();
loadDataToRecyclerView(view);
return view;
}
private void initiateTestData(){
testTitles = new ArrayList<>();
testDescriptions = new ArrayList<>();
for (int i = 5; i < 25; i++) {
testTitles.add("title " + i);
testDescriptions.add("This is some random description for testing purposes. Other wise just typing on to create more stuff... " + i);
Log.d(TAG, "initiateTestData: " + "title " + i);
}
}
private void loadDataToRecyclerView(View v){
Log.d(TAG, "loadDataToRecyclerView: " + testTitles.size());
RecyclerView recyclerView = v.findViewById(R.id.current_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
FeedAdapter adapter = new FeedAdapter(testTitles, testDescriptions, getActivity());
recyclerView.setAdapter(adapter);
recyclerView.setItemAnimator(new DefaultItemAnimator());
}
Don't think this is relevant. But for reference, this is my adapter class.
public class FeedAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private static final String TAG = "FeedAdapter";
private List<String> titles;
private List<String> descriptions;
private Context context;
public FeedAdapter(List<String> titles, List<String> descriptions, Context context) {
this.titles = titles;
this.descriptions = descriptions;
this.context = context;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.custom_current_feed, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder viewHolder, int i) {
final ViewHolder holder = (ViewHolder) viewHolder;
holder.feedTitle.setText(titles.get(i));
holder.feedDescription.setText(descriptions.get(i));
holder.layout.setOnClickListener(v -> {
Log.d(TAG, "Clicked: " + titles.get(i));
Toast.makeText(context, titles.get(i), Toast.LENGTH_SHORT).show();
});
}
#Override
public int getItemCount() {
return titles.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView feedTitle;
TextView feedDescription;
RelativeLayout layout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
feedTitle = itemView.findViewById(R.id.feed_title);
feedDescription = itemView.findViewById(R.id.feed_description);
layout = itemView.findViewById(R.id.feed_layout);
}
}
}
Your recycler view height is wrap_content
And recycler view item height match_parent
I would think you'd want them the other way around.
The RV's height = match_parent, i.e. the recycler view occupies all available height.
The RV item's height = wrap_content, i.e. each item only as tall as it needs to be, so that multiple items can fit.

RecyclerView onBindViewHolder method increases startup time?

I'm new to android app development and i have recently made my first app containing a basic tablayout with two fragments in my MainActivity.
In my second tab, it consists of only one RecyclerView as a rootlayout. What i did was populating the RecyclerView with an arraylist of my own dataModel.
My RecyclerView has 13 items. The view of these items is a expansion layout from https://github.com/florent37/ExpansionPanel I followed exactly the way he did for RecyclerView and it worked perfectly.
HOWEVER, my app's startup time has INCREASED significantly to 1s++. I found that the onBindViewHolder method in my RecyclerViewAdapter is the culprit. I tried commenting out the content of onBindViewHolder method and the startup time has reduced by half to 600ms, which is okay for me.
So my questions is How can I solve this problem?
Should I bind my data in a different way?
I dont want to have a slow startup time.
I saw some posts about using databinding API, running on a different threads and asyncs, but i dont know how to do it.
Please help ~ Thanks in advance!
Here's my Adapter:
public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private ArrayList<DataModel> list;
private final ExpansionLayoutCollection expansionsCollection = new ExpansionLayoutCollection();
MyAdapter(ArrayList<DataModel> list, Context context) {
this.list = list;
this.context = context;
expansionsCollection.openOnlyOne(true);
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView == LayoutInflater.from(parent.getContext()).inflate(R.layout.expansion_panel, parent, false);
return new ViewHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
DataModel currentData = list.get(position);
switch (currentData.getType()) {
case DataModel.NO_FORMULA:
holder.titleText.setText(currentData.getTitle());
holder.contentText.setText(currentData.getContent());
holder.formulaView.removeAllViews();
expansionsCollection.add(holder.expansionLayout);
break;
case DataModel.WITH_FORMULA:
View formulaLayout = ((Activity)context).getLayoutInflater().inflate(currentData.getFormulaLayoutId(),null);
holder.titleText.setText(currentData.getTitle());
holder.contentText.setText(currentData.getContent());
holder.formulaView.removeAllViews();
holder.formulaView.addView(formulaLayout);
expansionsCollection.add(holder.expansionLayout);
break;
}
}
#Override
public int getItemCount() {
return list.size();
}
private static class ViewHolder extends RecyclerView.ViewHolder {
TextView titleText, contentText;
ExpansionLayout expansionLayout;
FrameLayout formulaView;
ViewHolder(View itemView) {
super(itemView);
this.titleText = itemView.findViewById(R.id.title_text);
this.contentText = itemView.findViewById(R.id.content_text);
this.expansionLayout = itemView.findViewById(R.id.expansionLayout);
this.formulaView = itemView.findViewById(R.id.formula_view);
}
}
This is my item layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:ignore="ContentDescription,RtlHardcoded,HardcodedText">
<com.github.florent37.expansionpanel.ExpansionHeader
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
app:expansion_headerIndicator="#id/headerIndicator"
app:expansion_layout="#id/expansionLayout"
app:expansion_toggleOnClick="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?android:attr/selectableItemBackground"
android:minHeight="50dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:theme="#style/RecyclerViewTheme">
<TextView
android:id="#+id/title_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_toLeftOf="#id/headerIndicator"
android:textColor="#000" />
<android.support.v7.widget.AppCompatImageView
android:id="#+id/headerIndicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginLeft="16dp"
android:adjustViewBounds="true"
app:srcCompat="#drawable/ic_expansion_header_indicator_grey_24dp" />
</RelativeLayout>
</com.github.florent37.expansionpanel.ExpansionHeader>
<com.github.florent37.expansionpanel.ExpansionLayout
android:id="#+id/expansionLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:expansion_expanded="false">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#F5F5F5">
<TextView
android:id="#+id/content_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:textColor="#000" />
<FrameLayout
android:id="#+id/formula_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</com.github.florent37.expansionpanel.ExpansionLayout>
<View
android:layout_width="match_parent"
android:layout_height="0.7dp"
android:background="?android:attr/listDivider" />
</LinearLayout>
Here's my datamodel:
public class DataModel {
public static final int WITH_FORMULA = 0;
public static final int NO_FORMULA = 1;
private String title, content;
private int type, formulaLayoutId;
DataModel(int type, String title, String content) {
this.type = type;
this.title = title;
this.content = content;
}
DataModel(int type, String title, String content, int formulaLayoutId) {
this.type = type;
this.title = title;
this.content = content;
this.formulaLayoutId = formulaLayoutId;
}
public String getTitle() {
return title;
}
public String getContent() {
return content;
}
public int getFormulaLayoutId() {
return formulaLayoutId;
}
public int getType() {
return type;
}
*I've created 13 DataModel objects with long titles and long paragraphs as contents and put them in an arraylist. When the user click on the expansion panel's header, the expansion layout will expand to show the contents of it.
Only 2 out of the 13 items in the recyclerview is the type of WITH_FORMULA that has to inflate the formulaLayout.
If you are sure that the root of your problem is onBindViewHolder then the only problem there is the inflation.
inflate is a very expensive operation because it parses XML and then creates the view hierarchy. Don't do that in onBindViewHolder. Inflate the view once in onCreateViewHolder instead. If you don't want to show it in NO_FORMULA case just set its visibility to GONE and to VISIBLE in WITH_FORMULA case. Changing the visibility is way more simple operation.

First item in RecyclerView not clickable

I am currently implementing the ability to click on an item of an RecyclerView in an Android App. Yet I am stuck with some weird bug where I can only register the clicks on all items but the first one.
This is my layout for each item
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="listItemClick">
<TextView
android:id="#+id/spacer2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:text=" "
android:textSize="8sp" />
<TextView
android:id="#+id/headerTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/spacer2"
android:text="[Auftraggeber] - [Ort]"
android:textAppearance="#style/TextAppearance.AppCompat.Body2"
android:textSize="18sp" />
<TextView
android:id="#+id/captionTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/headerTextView"
android:text="Erstellt am 21.05.1999" />
<TextView
android:id="#+id/spacer3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/captionTextView"
android:text=" "
android:textSize="8sp" />
</RelativeLayout>
I'm using the listItemClick in my MainActivity in order to execute code upon clicking on an item. Further more i'm passing data through the tag of one of the textviews (which I assume not to be the problem).
This is listItemClick():
public void listItemClick (View v){
Toast.makeText(getApplicationContext(), ("You clicked: " + v.findViewById(R.id.headerTextView).getTag()), Toast.LENGTH_LONG).show();
System.out.println("Clicked");
}
This is the Adapter I implemented for the RecyclerView:
public class RapportListAdapter extends RecyclerView.Adapter<RapportListAdapter.ViewHolder> {
private ArrayList<RapportStructure> mDataset;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
// each data item is just a string in this case
public RelativeLayout mRelativeLayout;
public ViewHolder(RelativeLayout v) {
super(v);
mRelativeLayout = v;
}
#Override
public void onClick(View view) {
System.out.println("WORKS");
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public RapportListAdapter(ArrayList<RapportStructure> myDataset) {
mDataset = myDataset;
}
// Create new views (invoked by the layout manager)
#Override
public RapportListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
RelativeLayout rl = (RelativeLayout) LayoutInflater.from(parent.getContext()).inflate(R.layout.celllayout, parent, false);
ViewHolder vh = new ViewHolder(rl);
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
TextView headerTextView = (TextView) holder.mRelativeLayout.findViewById(R.id.headerTextView);
TextView captionTextView = (TextView) holder.mRelativeLayout.findViewById(R.id.captionTextView);
RapportStructure rs = this.mDataset.get(position);
headerTextView.setText("ClientID:" + rs.getClientId() + " - " + rs.getPlace());
captionTextView.setText("Erstellt am " + rs.getCreatedOn().toString());
headerTextView.setTag(position);
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.size();
}
}
I would like the first list item to be clickable as well. If you need any more information, just ask :)
I too have current problem.
after remove animation, my problem resolved. ):
This bug seems to have killed itself. I don't know why. I can use the first element now to open up a new Activity. Thanks for all the help!

RecyclerView with 100 items loading too slow

I have used RecyclerView several times before, but it is the first time that it is working too slow.
In this case, the items are represented by a simple LinearLayout with 3 views inside it:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="#+id/linearLayout"
android:orientation="horizontal"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/tvTicketNumber"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:gravity="center"
android:padding="8dp"/>
<EditText
android:id="#+id/etTotalSold"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="match_parent"
android:padding="8dp"
android:gravity="center" />
<TextView
android:id="#+id/tvSurplus"
android:layout_width="0dp"
android:layout_weight="1"
android:padding="8dp"
android:layout_height="match_parent"
android:gravity="center"/>
</LinearLayout>
The RecyclerView uses the previous layout in its adapter:
public class TicketAdapter extends RecyclerView.Adapter<TicketAdapter.ViewHolder> {
private ArrayList<Ticket> dataSet;
// Define references to the views for each data item
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvTicketNumber, tvSurplus;
public EditText etQuantity;
public ViewHolder(View v) {
super(v);
tvTicketNumber = (TextView) v.findViewById(R.id.tvTicketNumber);
etQuantity = (EditText) v.findViewById(R.id.etQuantity);
tvSurplus = (TextView) v.findViewById(R.id.tvSurplus);
}
}
public TicketAdapter() {
dataSet = new ArrayList<>();
}
public void setDataSet(ArrayList<Ticket> dataSet) {
this.dataSet = dataSet;
}
private String twoDigits(final int i) {
final String pre = (i<=9 ? "0" : "");
return pre + i;
}
#Override
public TicketAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.table_row, parent, false);
// set the view's size, margins, padding and layout parameters
return new ViewHolder(v);
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
// get element from the data set
Ticket ticket = dataSet.get(position);
// replace the contents of the view with that element
holder.tvTicketNumber.setText(twoDigits(position));
holder.tvSurplus.setText("6");
}
#Override
public int getItemCount() {
return dataSet.size();
}
}
Before, I was using TableLayout with TableRows created programmatically, but I have read that layout have to be used for a defined number of rows in XML.
I have to load a list of 100 items in a fragment. But it takes approximately 4 seconds to load. For that reason I wrote some logic to show a progressBar and next hide it and show the scrollView (the recycler is within it).
The fragmentTransaction was still slow, so I moved the code to the onViewCreated method.
The transaction was still slow and I added an AsyncTask. With this last change, the transaction is faster, but the progressBar looks stopped all the time and the buttons can't be used (the onPostExecute is taking 4 seconds to load and show the recyclerView).
I want to show the animation of the progressBar, but the onPostExecute is executed in the UI thread and all the app is stopped for 4 seconds while the RecyclerView is loading.
Please give me some ideas. Before I have used items with images loaded from internet, and the RecyclerView was working faster. It is too strange.

Display UI like facebook messenger in Android java programatically

Image
--
I want to achieve something like this in above image
I have to loop through this json array to get all my datas;
the data contained in my json array are for example
{
'img' : http:\\.....
'name' : XYZ
'msg' : xyz
'time' : abc
}
//this is where I am tring to append everything
final LinearLayout rl = (LinearLayout)main.findViewById(R.id.mainL);
for (int i = 0; i < json.length(); i++) {
try {
JSONObject c = json.getJSONObject(i);
//here components must be created and added to view
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I just want to know the how do you programmatically style the views(textview,imageview etc) like in the above image.
Any Help will be appreciated
Ok, the image you are looking at is actually a ListView serving custom-made views.
How does that work?
You will need to subclass the BaseAdapter class. This subclass will contain the underlying data which in your case you are getting as a JSON-formatted reply from the web-server.
When the getView() of the BaseAdapter subclass is called, you can inflate a layout that contains an ImageView and TextViews to display the data onscreen.
The answer is just for future visitors, since the question was asked long day ago. At first, I will just redirect you to my GitHub page where I used RecyclerView to show data and Retrofit to call data. I used Volley also. Finally, let me show simple way to load data to recyclerview.
You need an extra class call it CustomAdapter.
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
Context context;
private String countryList[];
private int imgList[];
//constructor
public CustomAdapter(Context context, String countryList[],int imgList[]) {
this.context = context;
this.countryList = countryList;
this.imgList=imgList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
// inflate the item Layout
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.items, parent, false);
// set the view's size, margins, paddings and layout parameters
MyViewHolder vh = new MyViewHolder(view); // pass the view to View Holder
return vh;
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder myHolder, final int position) {
myHolder.txtName.setText(countryList[position]);
myHolder.imgCountry.setImageResource(imgList[position]);
// implement setOnClickListener event on item view.
myHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// display a toast with person name on item click
Toast.makeText(context, countryList[position], Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return countryList.length;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
TextView txtName;
ImageView imgCountry;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
// get the reference of item view's
txtName = itemView.findViewById(R.id.txt_name);
imgCountry = itemView.findViewById(R.id.img_flag);
}
}
}
And in the MainActivity, you have declare a LayoutManager for RecyclerView and have to call CustomAdapter to load data in RecyclerView.
String countryList[]={"Bangladesh","India","China","Australia","America","New Zealand","Portugal"};
int imgList[]={R.drawable.bd,R.drawable.india,R.drawable.china,R.drawable.australia,R.drawable.america,R.drawable.new_zealand,R.drawable.portugle};
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the reference of RecyclerView
recyclerView = findViewById(R.id.recycler_view);
// set a LinearLayoutManager with default vertical orientation
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
// set a LinearLayoutManager with default Horizontal orientation
// LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.HORIZONTAL,false);
recyclerView.setLayoutManager(linearLayoutManager);
// call the constructor of CustomAdapter to send the reference and data to Adapter
CustomAdapter customAdapter = new CustomAdapter(MainActivity.this,countryList, imgList);
recyclerView.setAdapter(customAdapter); // set the Adapter to RecyclerView
}
activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
items.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/img_flag"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_margin="5dp"
app:srcCompat="#mipmap/ic_launcher" />
<TextView
android:id="#+id/txt_name"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center|left"
android:paddingLeft="10dp"
android:text="TextView"
android:textSize="24sp" />
</LinearLayout>
</LinearLayout>
Here's the github repository. If you are calling data from server then visit my Volley repo.

Categories

Resources