I have cards with different width and I would like to create a Grid Layout where width = match the parent (filling the screen) and fixed height.
I would like to set the cards in the Grid layout so the number of columns changes accordingly to the width of the elements that can fit the row.
So the elements will be set in a horizontal row till they can fit the screen and then go to the next row, with a vertical scroll when they exceed the fixed height.
I am trying to use a Grid Layout but I don't know if it the suitable solution for this.
I use native Android.
Here a picture of it should look like:
Thanks.
You can use FlexboxLayoutManager
Add the following dependency to your build.gradle file:
implementation 'com.google.android:flexbox:1.0.0'
SAMPLE CODE
LAYOUT.XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="250dp" />
</LinearLayout>
ACTIVTY CODE
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<String> arrayList = new ArrayList<>();
DataAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
initArray();
FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(this);
layoutManager.setFlexDirection(FlexDirection.COLUMN);
layoutManager.setJustifyContent(JustifyContent.FLEX_END);
recyclerView.setLayoutManager(layoutManager);
adapter = new DataAdapter(this, arrayList);
recyclerView.setAdapter(adapter);
}
private void initArray() {
arrayList.add("ioreeoe");
arrayList.add("fghfgh");
arrayList.add("ftyjyjhghgh");
arrayList.add("jfgewrg");
arrayList.add("rwrewr");
arrayList.add("ghyjtyfghh");
arrayList.add("gfhfgh");
arrayList.add("gfhfht");
arrayList.add("retretret");
arrayList.add("retret");
arrayList.add("ioreeoe");
arrayList.add("fghfgh");
arrayList.add("ftyjyjhghgh");
arrayList.add("jfgewrg");
arrayList.add("rwrewr");
arrayList.add("ghyjtyfghh");
arrayList.add("gfhfgh");
arrayList.add("gfhfht");
arrayList.add("retretret");
arrayList.add("retret");
arrayList.add("ioreeoe");
arrayList.add("fghfgh");
arrayList.add("ftyjyjhghgh");
arrayList.add("jfgewrg");
arrayList.add("rwrewr");
arrayList.add("ghyjtyfghh");
arrayList.add("gfhfgh");
arrayList.add("gfhfht");
arrayList.add("retretret");
arrayList.add("retret");
}
}
Adapter code
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by nilesh on 3/4/18.
*/
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
Context context;
ArrayList<String> arrayList = new ArrayList<>();
public DataAdapter(Context context, ArrayList<String> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.custom_layout, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(DataAdapter.ViewHolder holder, int position) {
holder.title.setText(arrayList.get(position));
}
#Override
public int getItemCount() {
return arrayList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView title;
public ViewHolder(View itemView) {
super(itemView);
title = itemView.findViewById(R.id.nilu);
}
}
}
custom_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="#+id/nilu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="#drawable/test"
android:padding="10dp"
android:textColor="#050505" />
</LinearLayout>
#drawable/test
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle" >
<corners android:radius="30dp"/>
<solid android:color="#d10e0e"/>
<stroke android:width="1dip" android:color="#070fe9" />
</shape>
</item>
</selector>
RESULT
You can use Staggered GridView libraries. For eg. https://github.com/etsy/AndroidStaggeredGrid
Edit:
add dependency in build.gradle and in your xml you can add:
<com.etsy.android.grid.StaggeredGridView
android:id="#+id/itemgridfragment_gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:column_count="2"
android:background="#color/white"
app:item_margin="#dimen/fragment_landingpage_8" />
</android.support.v4.widget.SwipeRefreshLayout>
Related
Previously I had crash issues due to the wrong reference to the resource files. Fixed that issue and updated this thread with the logical error that I am getting.
I am new to android and currently learning custom classes and adapter. While working I am facing a problem which is the listview shows the first arraylist item only.
I have attached the codes of the required files as well.
Working Activity
package np.com.shresthakiran.tourswoniga;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
public class KhowpaActivity extends AppCompatActivity {
ListView lvHeritageList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_heritage);
lvHeritageList = findViewById(R.id.lvHeritage);
ArrayList<Heritages> heritageAryList = new ArrayList<>();
heritageAryList.add(new Heritages(R.drawable.ic_launcher_background,"Ngatapol", "Taumadi"));
heritageAryList.add(new Heritages(R.drawable.ic_launcher_foreground, "Dattatreya", "Taumadi"));
heritageAryList.add(new Heritages(R.drawable.ic_launcher_foreground, "Lu dhwakha", "Lyaaku"));
heritageAryList.add(new Heritages(R.drawable.ic_launcher_foreground, "55 jhyale Durbar", "Lyaaku"));
heritageAryList.add(new Heritages(R.drawable.ic_launcher_foreground, "Taleju Bhawani", "Lyaaku"));
HeritageAdapter heritageAdapter = new HeritageAdapter(KhowpaActivity.this, R.layout.heritages_row, heritageAryList);
lvHeritageList.setAdapter(heritageAdapter);
}
}
Custom Adapter
package np.com.shresthakiran.tourswoniga;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class HeritageAdapter extends ArrayAdapter<Heritages> {
private Context mContext;
private int mResource;
public HeritageAdapter(#NonNull Context context, int resource, #NonNull ArrayList<Heritages> objects) {
super(context, resource, objects);
this.mContext = context;
this.mResource = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater layoutInflater =LayoutInflater.from(mContext);
convertView = layoutInflater.inflate(mResource, parent, false);
ImageView ivHeritageImage = convertView.findViewById(R.id.ivHeritage);
TextView tvHeritageName = convertView.findViewById(R.id.tvHeritageName);
TextView tvHeritageAddress = convertView.findViewById(R.id.tvHeritageAddress);
ivHeritageImage.setImageResource(getItem(position).getmImageResourceId());
tvHeritageName.setText(getItem(position).getmHeritageName());
tvHeritageAddress.setText(getItem(position).getmHeritageAddress());
return convertView;
}
}
Object Class
package np.com.shresthakiran.tourswoniga;
public class Heritages {
private int mImageResourceId;
private String mHeritageName;
private String mHeritageAddress;
public Heritages(int heritageImageResourceId, String heritageName, String heritageAddress) {
this.mImageResourceId = heritageImageResourceId;
this.mHeritageName = heritageName;
this.mHeritageAddress = heritageAddress;
}
public int getmImageResourceId() {
return mImageResourceId;
}
public String getmHeritageName() {
return mHeritageName;
}
public String getmHeritageAddress() {
return mHeritageAddress;
}
}
ListView XML
<?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:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="100dp"
android:minHeight="100dp">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lvHeritage">
</ListView>
</RelativeLayout>
List Row 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:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="100"
android:layout_margin="10dp">
<ImageView
android:id="#+id/ivHeritage"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="33.33"
android:padding="2dp"
android:text="Ngatapol"
android:layout_marginTop="7dp"
android:src="#mipmap/ic_launcher"/>
<LinearLayout
android:id="#+id/llHeritageInfo"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="66.66"
android:padding="8dp" >
<TextView
android:id="#+id/tvHeritageName"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:textSize="18sp"
android:textStyle="bold"
android:text="Ngatapol"
android:textAppearance="?android:textAppearanceMedium"
android:padding="2dp"/>
<TextView
android:id="#+id/tvHeritageAddress"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:textSize="18sp"
android:text="Taumadi"
android:padding="2dp"/>
</LinearLayout>
</LinearLayout>
listview shows the first item only is because you have set height in heritages_row layout to match_parent which will cover the whole screen height and for the next item, you've to scroll down even if the content of the first item is not covering the whole height.
To make each row to only cover the content its displaying, use wrap_content instead of match_parent.
I am trying to create StaggeredGrid with this code.
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.userprofile_photos,container,false);
setRetainInstance(true);
photosRecycler=view.findViewById(R.id.userPhotos_recycler);
layoutManager= new StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL);
layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS);
photosRecycler.setLayoutManager(layoutManager);
photosRecycler.setHasFixedSize(true);
adapter=new fetchPhoto_Adapter();
photosRecycler.setAdapter(adapter);
return view;
}
Fragment Layout
<?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="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/userPhotos_recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll" />
</RelativeLayout>
Adapter
public class fetchPhoto_Adapter extends RecyclerView.Adapter<fetchPhoto_Adapter.ViewHolder>{
#NonNull
#Override
public fetchPhoto_Adapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
LayoutInflater inflater= (LayoutInflater) viewGroup.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.photogallery,viewGroup,false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(fetchPhoto_Adapter.ViewHolder viewHolder, int i) {
Glide.with(getActivity()).load(ImageList.get(i)).apply(new RequestOptions().centerCrop()).into(viewHolder.image);
}
#Override
public int getItemCount() {
return ImageList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView image;
public ViewHolder(View itemView) {
super(itemView);
image = itemView.findViewById(R.id.UserProfile_photoThumb);
}
}
}
Adapter Item Layout XML
<?xml version="1.0" encoding="utf-8"?>
<ImageView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/UserProfile_photoThumb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
/>
I tried to make it StaggeredGrid but with above code and with lots of modification like
setting image scaletype to fitxy,centercrop,center and changing height to wrap_content and modifying Glide image loading code all showing same output. I wanted to make my StaggeredGrid Like below required output. Please help me out.
Well I have achieved this in one of my projects, so I am here sharing you some code snippet over here. Try it and let me know.
class DemoActivity : ActivityBase() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_demo_activity)
val layoutmanager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
layoutmanager.gapStrategy = StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS
rcv_staggered.layoutManager = layoutmanager
rcv_staggered.setHasFixedSize(true)
val listItem = ArrayList<DemoModel>()
// This is dummy url for reference and in this image url I was
// getting image with different width and height
val demoModel = DemoModel("https://i.picsum.photos/id/237/200/400.jpg", "Title 1")
val demoModel1 = DemoModel("https://i.picsum.photos/id/237/750/250.jpg", "Title 2")
val demoModel2 = DemoModel("https://i.picsum.photos/id/237/500/250.jpg", "Title 3")
val demoModel3 = DemoModel("https://i.picsum.photos/id/237/100/200.jpg", "Title 4")
listItem.add(demoModel)
listItem.add(demoModel1)
listItem.add(demoModel2)
listItem.add(demoModel3)
rcv_staggered.adapter = DemoAdapter(listItem)
}
}
Create recyclerView adapter same as we all do.
Load images using below snippet:
Glide.with(holder.img.context)
.load(listItem[holder.adapterPosition].color)
.placeholder(R.color.black_alpha_10)
.into(holder.img)
And this is my item layout for recyclerview
<?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:layout_margin="10dp"
android:orientation="vertical">
<androidx.appcompat.widget.AppCompatImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"/>
</LinearLayout>
StaggeredGridLayoutManager Screenshot
Wrap your ImageView inside RelativeLayout, it should be Ok
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp">
<ImageView
android:id="#+id/UserProfile_photoThumb"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
I think their issues in glide code which you have used
Use this
Glide.with(mContext).load(imageList.get(i)).into(viewHolder.image);
Instead of this
Glide.with(getActivity()).load(ImageList.get(i)).apply(new RequestOptions().centerCrop()).into(viewHolder.image);
Also I have made some other changes in your code please check below example
Find the full code here
MainActivity2 code
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import android.os.Bundle;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import java.util.ArrayList;
public class MainActivity2 extends AppCompatActivity {
RecyclerView photosRecycler;
ArrayList<String> imageList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
photosRecycler = findViewById(R.id.userPhotos_recycler);
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_MOVE_ITEMS_BETWEEN_SPANS);
photosRecycler.setLayoutManager(layoutManager);
photosRecycler.setHasFixedSize(true);
imageList.add("https://i.stack.imgur.com/K8FFo.jpg?s=328&g=1");
imageList.add("https://i.stack.imgur.com/Bpdap.jpg?s=328&g=1");
imageList.add("https://i.stack.imgur.com/73QY4.jpg");
imageList.add("https://i.stack.imgur.com/Bpdap.jpg?s=328&g=1");
imageList.add("https://i.stack.imgur.com/K8FFo.jpg?s=328&g=1");
imageList.add("https://i.stack.imgur.com/Bpdap.jpg?s=328&g=1");
imageList.add("https://i.stack.imgur.com/K8FFo.jpg?s=328&g=1");
fetchPhoto_Adapter adapter = new fetchPhoto_Adapter(imageList, this);
photosRecycler.setAdapter(adapter);
}
}
activity_main2 of 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"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/userPhotos_recycler"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
fetchPhoto_Adapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import java.util.ArrayList;
public class fetchPhoto_Adapter extends RecyclerView.Adapter<fetchPhoto_Adapter.ViewHolder> {
ArrayList<String> imageList = new ArrayList<>();
Context mContext;
public fetchPhoto_Adapter(ArrayList<String> imageList, Context mContext) {
this.imageList = imageList;
this.mContext = mContext;
}
#NonNull
#Override
public fetchPhoto_Adapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(R.layout.photogallery, viewGroup, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(fetchPhoto_Adapter.ViewHolder viewHolder, int i) {
Glide.with(mContext).load(imageList.get(i)).into(viewHolder.image);
}
#Override
public int getItemCount() {
return imageList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView image;
public ViewHolder(View itemView) {
super(itemView);
image = itemView.findViewById(R.id.UserProfile_photoThumb);
}
}
}
photogallery layout
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/UserProfile_photoThumb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:layout_margin="2dp"
android:scaleType="fitXY" />
OUTPUT
I am trying to add a RecyclerView to my app, but I am having lots of difficulties. I want the RecyclerView to have items of this layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/txtChords"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center_horizontal"
/>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/txtLyrics"/>
</LinearLayout>
I put that into its own XML file, and declared the RecyclerView in the layout. But I don't know how to display the items
Thank you!!
I searched documentation and tutorials, but they all do something slightly different and too complicated when comparing to what I want to do. I just want to learn the basics of RecyclerViews and how to use them.
I will accept examples and any link
Please note that I am fairly new to android, and might need a simpler explanation
Recyclerview:
Recycler view is same as listview but recyclerview is added in android support lib for material design concept.
Example:
Add dependency for recyclerview
compile 'com.android.support:recyclerview-v7:23.1.0'
Add recyclerview in main 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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/item_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
/>
</LinearLayout>
Make one item layout xml file (here is ur item file)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/txtChords"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center_horizontal"
/>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/txtLyrics"/>
</LinearLayout>
Make one model class for each item in list.it can be any custom class.
public class Item {
private String name;
public Item(String n) {
name = n;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Now most important part is to make adapter for recyclerview:
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.codexpedia.list.viewholder.R;
import java.util.ArrayList;
public class ItemArrayAdapter extends RecyclerView.Adapter<ItemArrayAdapter.ViewHolder> {
//All methods in this adapter are required for a bare minimum recyclerview adapter
private int listItemLayout;
private ArrayList<Item> itemList;
// Constructor of the class
public ItemArrayAdapter(int layoutId, ArrayList<Item> itemList) {
listItemLayout = layoutId;
this.itemList = itemList;
}
// get the size of the list
#Override
public int getItemCount() {
return itemList == null ? 0 : itemList.size();
}
// specify the row layout file and click for each row
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(listItemLayout, parent, false);
ViewHolder myViewHolder = new ViewHolder(view);
return myViewHolder;
}
// load data in each row element
#Override
public void onBindViewHolder(final ViewHolder holder, final int listPosition) {
TextView item = holder.item;
item.setText(itemList.get(listPosition).getName());
}
// Static inner class to initialize the views of rows
static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView item;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
item = (TextView) itemView.findViewById(R.id.txtChords);
}
#Override
public void onClick(View view) {
Log.d("onclick", "onClick " + getLayoutPosition() + " " + item.getText());
}
}
This is simple adapter with minimum requirement method.
Now bind adapter with recyclerview
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import com.codexpedia.list.viewholder.R;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing list view with the custom adapter
ArrayList <Item> itemList = new ArrayList<Item>();
ItemArrayAdapter itemArrayAdapter = new ItemArrayAdapter(R.layout.list_item, itemList);
recyclerView = (RecyclerView) findViewById(R.id.item_list);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(itemArrayAdapter);
// Populating list items
for(int i=0; i<100; i++) {
itemList.add(new Item("Item " + i));
}
}
}
Hope this example will help u...
You can ask any question if u have any confusion.
You can refer this link if u want to make complex list
https://www.binpress.com/tutorial/android-l-recyclerview-and-cardview-tutorial/156
I want to have my items in listview looking like a conversation in messenger.
There is simple code of recieving messages:
if (arrayList2.get(y).toString().equals(myEmail)) {
arrayList.add(arrayList2.get(k).toString());
} else if (arrayList2.get(y).toString().equals(recipientEmail)) {
arrayList.add(arrayList2.get(k).toString());
}
arrayAdapter.notifyDataSetChanged();
When array.get.....equals(myEmail), the messages are from me so, they should stay like they are. When ...equals(recipientEmail), I want text to be on the right of the screen/or listview and have an background of image, like classically in messenger
I will recommend you to add all Your messages in one Arraylist and create two layouts one of sender with left gravity and one of receiver with right gravity then make a logic like-
if(arraylist.get(position).getUserID==currentUser){
senderLayout.setvisibility(View.VISIBLE);
senderTextview.setText(arraylist.get(position).getText)
}
else{
senderLayout.setvisibility(View.GONE);
receiverLayout.setvisibility(View.VISIBLE);
recieverTextview.setText(arraylist.get(position).getText)
}
Do this in getView method of your adapter.
You may create a row with 2 views. One on left and other on right. Based on your if condition you can make one of the views gone and the other visible. At any time only one view in that will be visible.
Another way of doing is to use single view in it and setting (left/right) gravity based on your condition.
You may refer http://www.uandblog.com/How-to-Create-Chat-Application-using-Firebase-in-Android-. See MainActivity.java and item.xml
Use two TextView in raw file
<?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="match_parent">
<com.github.library.bubbleview.BubbleTextVew
android:id="#+id/tv_chatRecive"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="7dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="35dp"
android:layout_marginTop="8dp"
android:padding="10dp"
android:textColor="#android:color/white"
android:visibility="gone"
app:angle="5dp"
app:arrowHeight="12dp"
app:arrowLocation="left"
app:arrowPosition="5dp"
app:arrowWidth="12dp"
app:bubbleColor="#color/colorPrimary" />
<com.github.library.bubbleview.BubbleTextVew
android:id="#+id/tv_chatSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginBottom="7dp"
android:layout_marginLeft="35dp"
android:layout_marginRight="10dp"
android:layout_marginTop="8dp"
android:padding="10dp"
android:textColor="#color/text_labelColoe"
android:visibility="gone"
app:angle="5dp"
app:arrowHeight="12dp"
app:arrowLocation="right"
app:arrowPosition="5dp"
app:arrowWidth="12dp"
app:bubbleColor="#android:color/white" />
</RelativeLayout>
and in Adapter class use this kind of logic to manage textview
#Override
public void onBindViewHolder(final CustomViewHolder customViewHolder, final int position) {
if (listChat.get(position).CHAT_SEND_RECIVE.equalsIgnoreCase("right")) {
customViewHolder.tvSend.setVisibility(View.VISIBLE);
customViewHolder.tvRecive.setVisibility(View.GONE);
customViewHolder.tvSend.setText(listChat.get(position).CHAT_MESSAGE);
} else if (listChat.get(position).CHAT_SEND_RECIVE.equalsIgnoreCase("left")) {
customViewHolder.tvRecive.setVisibility(View.VISIBLE);
customViewHolder.tvSend.setVisibility(View.GONE);
customViewHolder.tvRecive.setText(listChat.get(position).CHAT_MESSAGE);
}
}
Add key in chat responce like just i add right and left
Here is complete example.
Resources under drawable:
activity_main.xml:
<?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="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.andrii.myapplication.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/chat"
android:background="#color/colorAccent"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
Message layout will looks like so (message.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<FrameLayout
android:id="#+id/container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="15dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:paddingRight="10dp"
android:background="#drawable/in_9">
<TextView
android:id="#+id/message"
android:textSize="18sp"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:breakStrategy="balanced"
android:maxWidth="200dp"
android:text="test"
/>
</FrameLayout>
</LinearLayout>
And finally in MainActivity.java :
package com.example.andrii.myapplication;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.LinkedList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Message> list= new LinkedList<>();
list.add(new Message(true, "hi"));
list.add(new Message(false, "hello"));
list.add(new Message(true, "how are you"));
list.add(new Message(false, "I'm fine"));
list.add(new Message(false, "Test test test test test"));
RecyclerView view = (RecyclerView) findViewById(R.id.chat);
view.setLayoutManager(new LinearLayoutManager(this));
view.setAdapter(new ChatAdapter(this, list));
}
private class Message {
private boolean misMine;
private String mMessage;
public Message (boolean mine, String message) {
misMine = mine;
mMessage = message;
}
public boolean isMine() { return misMine; }
public String getMessage() { return mMessage; }
}
private class MessageViewHolder extends RecyclerView.ViewHolder {
private View mContainer;
private TextView mMessage;
public MessageViewHolder(View itemView) {
super(itemView);
mMessage = (TextView) itemView.findViewById(R.id.message);
mContainer = itemView.findViewById(R.id.container);
}
public void setMessage(String message) {
mMessage.setText(message);
}
public void setMine(boolean isMine) {
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) mContainer.getLayoutParams();
params.gravity = isMine ? Gravity.RIGHT : Gravity.LEFT;
mContainer.setBackgroundResource(isMine ? R.drawable.out_9 : R.drawable.in_9 );
mContainer.setLayoutParams(params);
}
}
private class ChatAdapter extends RecyclerView.Adapter<MessageViewHolder> {
private List<Message> mMessages;
public ChatAdapter(Context context, List<Message> list) {
mMessages = list;
}
#Override
public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.message, parent, false);
MessageViewHolder holder = new MessageViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MessageViewHolder holder, int position) {
Message message = mMessages.get(position);
holder.setMessage(message.getMessage());
holder.setMine(message.isMine());
}
#Override
public int getItemCount() {
return mMessages.size();
}
}
}
The result of code above:
I want to create a list where the listview will display a textview and an icon for each row. The diagram should be as follows:
Other than that, The data is retrieved from the database. The attribute of "favorite" will be checked first and if true, then the image in listview will be assigned with favorite_icon.png. Else, no icon need to be assigned.
I have been search for the related answer and tutorial, but all of them is too different from what I want and I cannot understand it very much. Hope somebody here can help me. Thank you in advance.
Here is what I got after I have done my Homework
First we set up a custom layout for listview and also for the row of the listview we will use later.
Here is the custom_listview_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/customListView" />
</LinearLayout>
Here is the custom_listview_row.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"
android:gravity="center_vertical"
android:minHeight="64dp">
<ImageView
android:id="#+id/clv_imageView"
android:layout_width="32dp"
android:layout_height="32dp"
android:contentDescription="#string/empty"
android:layout_alignParentRight="true"
android:layout_marginLeft="9dp"
android:layout_alignParentTop="true"/>
<TextView
android:id="#+id/clv_textView"
android:layout_width="97dp"
android:layout_height="32dp"
android:layout_alignParentLeft="true"
android:gravity="center_vertical"
android:text="#string/tv_definition"
android:textIsSelectable="true" />
</RelativeLayout>
Then we need to customized how our Custom ArrayAdaptor will look and do.
But before that, make sure you have put your icon in the drawable folder.
Here is my MyPerformanceArrayAdapter.java
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MyPerformanceArrayAdapter extends ArrayAdapter<DefinitionObject>{
private List<DefinitionObject> entries;
private Activity activity;
public MyPerformanceArrayAdapter(Activity a, int textViewResourceId, List<DefinitionObject> entries) {
super(a, textViewResourceId, entries);
this.entries = entries;
this.activity = a;
}
public static class ViewHolder{
public TextView item1;
public ImageView item2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder holder;
if (v == null) {
LayoutInflater vi =
(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.custom_listview_row, null);
holder = new ViewHolder();
holder.item1 = (TextView) v.findViewById(R.id.clv_textView);
holder.item2 = (ImageView) v.findViewById(R.id.clv_imageView);
v.setTag(holder);
}
else
holder=(ViewHolder)v.getTag();
final DefinitionObject custom = entries.get(position);
if (custom != null) {
holder.item1.setText(custom.getWord());
if(custom.getFav().equalsIgnoreCase("0"))
{
holder.item2.setImageResource(R.drawable.fav);
holder.item2.setVisibility(holder.item2.INVISIBLE);
}
else
{
holder.item2.setImageResource(R.drawable.fav2);
}
}
return v;
}
}
And lastly, here is my Activity to View the ListView using the CustomArrayAdaptor.
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;
public class TempCLV extends Activity {
private MySQLiteDefinitionHelper db;
String tblName = "";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.custom_listview_main);
Intent msjIntent = getIntent();
tblName = msjIntent.getStringExtra(WordDefinitionHomeActivity.TABLENAME2);
refresh();
}
public void refresh()
{
db = new MySQLiteDefinitionHelper(this);
final List<DefinitionObject> values = db.getAllWords(tblName);
ListView mylist = (ListView)findViewById(R.id.customListView);
MyPerformanceArrayAdapter adapter = new MyPerformanceArrayAdapter(this, R.id.customListView, values);
mylist.setAdapter(adapter);
}
}