I am quite new to Android and can't achieve this, been searching all day.
Layout I'm trying to create.
I have created the custom xml layout, I have found ways to add items on create, but I need the list to be empty and than when the button is pressed to add from a list.
This is the layout:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow>
<ImageView
android:id="#+id/info_img_view"
android:layout_width="30dp"
android:layout_height="30dp" />
<TextView
android:id="#+id/info_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
<TextView
android:id="#+id/info_time_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="right"
/>
</TableRow>
I have a ListView in the main activity:
<ListView
android:id="#+id/list_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
How do I go about this? I would appreciate it if someone can point me to a resource where I can learn what the code is actually doing, not the tutorials I find where I just copy and paste...
Thanks!
Edit, a bit more explanation of what I'm trying to achieve
I have 6 buttons. When a button is pressed it should add a list item with two textviews, and one image out of total three images.
So for instance if Button1 is pressed: Add list item > "Text one" "Text one" "imageTwoOfThree".
Than, if Button2 is pressed: Add list item on top > "Text two" "Text two" "imageTwoOfThree"
And so on... The text is hardcoded.
Here use this:
I have created a list with dummydata you can change the text and Image according to you
First create a class Data:
public class Data {
private String name,price;
private int imageId;
public Data(){}
public Data(String name,String price,int imageId){
this.name = name;
this.price = price;
this.imageId = imageId;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
}
Then create a ListView Adapter to handle your data:
public class ListViewAdaptor extends RecyclerView.Adapter<ListViewAdaptor.MyViewHolder> {
private List<Data> mDataList;
public class MyViewHolder extends RecyclerView.ViewHolder{
public TextView name,price;
public ImageView imageView;
public MyViewHolder(View view){
super(view);
name = (TextView) view.findViewById(R.id.name);
price= (TextView) view.findViewById(R.id.price);
imageView = (ImageView) view.findViewById(R.id.image);
}
}
public ListViewAdaptor(List<Data> dataList){
this.mDataList = dataList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_view_item, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Data data = mDataList.get(position);
holder.name.setText(data.getName());
holder.price.setText(data.getPrice());
holder.imageView.setImageResource(data.getImageId());
}
#Override
public int getItemCount() {
return mDataList.size();
}
}
layout for your list view items name it list_view_item:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/ic_launcher"
android:id="#+id/image"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/name"
android:text="name"
android:gravity="center"
android:textSize="26sp"
android:layout_weight="1"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/price"
android:text="price"
android:gravity="center"
android:textSize="26sp"
android:layout_weight="1"/>
</LinearLayout>
Then from your activity where you want to add listView add recyclerView in layout:
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/recycler_view">
</android.support.v7.widget.RecyclerView>
Then use this recyclerview like this:
//I have called it from my MainActivity you can use it in whatever activity you'll like
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private ListViewAdaptor mAdapter;
private List<Data> mDataList = new ArrayList<>();
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new ListViewAdaptor(mDataList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setItemAnimator(new DefaultItemAnimator());
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setAdapter(mAdapter);
prepareList();
}
public void prepareList(){
Data data = new Data("Item1","Price1",R.drawable.star);
mDataList.add(data);
data = new Data("Item2","Price2",R.drawable.star);
mDataList.add(data);
data = new Data("Item3","Price3",R.drawable.star);
mDataList.add(data);
data = new Data("Item4","Price4",R.drawable.star);
mDataList.add(data);
data = new Data("Item5","Price5",R.drawable.star);
mDataList.add(data);
}
}
Hope this helps!!!
You will find lots of online resources for this. But let me put it in a brief way.
Assuming you want to store 2 textviews in one single row.
1. For each layout of the row, you will need to make a custom layout xml file and design your layout there.
Next, make a class which stores the data and returns the data through getters.
class Category {
private String categoryName;
private String categoryImageURL;
Category (String categoryName, String categoryImageUrl) {
this.categoryName = categoryName;
this.categoryImageURL = categoryImageUrl;
}
String getCategoryName () {
return categoryName;
}
String getCategoryImageURL () {
return categoryImageURL;
}
}
Now make a custom arrayadapter which will link the data and the layout.
Extend the arrayadapter class with the class you defined above.
private class categoryArrayAdapter extends ArrayAdapter<Category> {
private Context context;
private List<Category> categories;
public categoryArrayAdapter (Context context, int resource, ArrayList<Category> objects) {
super(context, resource, objects);
this.context = context;
this.categories = objects;
}
public View getView (int position, View convertView, ViewGroup parent) {
Category category = categories.get(position);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.category_row_view, null);
TextView categoryListRowText = (TextView) view.findViewById(R.id.categoryListRowText);
TextView categoryListRowImage = (TextView) view.findViewById(R.id.categoryListRowImage);
categoryListRowText.setText(category.getCategoryName());
categoryListRowImage.setText(category.getCategoryImageURL());
return view;
}
}
Finally link the adapter to your listview
ArrayAdapter<Category> adapter = new categoryArrayAdapter(this, 0, categories);
categoryListView.setAdapter(adapter);
Hope this answered you question.
Related
I am trying to add a spinner object inside each item of a recyclerview.
I think the problem is that in OnCreate the setContentView(R.layout.activity_modify_list2) is referring to the xml file that contains the recyclerview:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modify_list2);
initView();
}
Because of this, the createSpinner() method is looking for the spinner in that file rather than the xml file for the individual recyclerview item, giving a null object reference error:
private Spinner CreateSpinner() {
Spinner staticSpinner = findViewById(R.id.spinner);
... }
Full java file for the page:
public class ModifyListActivity extends Activity {
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modify_list2);
initView();
}
private void initView() {
recyclerView = (RecyclerView) findViewById(R.id.recyclerViewModifyList);
createList();
}
private void createList() {
ArrayList<ModifyListPageItem> items = new ArrayList<>();
ModifyListPageItem item;
item = new ModifyListPageItem();
item.setTitle("Resident Evil Games");
item.setDescription("Ranking all Resident Evil games");
items.add(item);
item = new ModifyListPageItem();
item.setRank("1.");
item.setSpinner(CreateSpinner());
items.add(item);
item = new ModifyListPageItem();
item.setRank("2.");
item.setSpinner(CreateSpinner());
items.add(item);
item = new ModifyListPageItem();
item.setRank("3.");
item.setSpinner(CreateSpinner());
items.add(item);
// set adapter
ModifyListPageAdapter adapter = new ModifyListPageAdapter(this, items);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(adapter);
}
private Spinner CreateSpinner() {
Spinner staticSpinner = findViewById(R.id.spinner);
// Create an ArrayAdapter using the string array and a default spinner
ArrayAdapter<CharSequence> staticAdapter = ArrayAdapter
.createFromResource(this, R.array.resident_evil_games,
android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
staticAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
staticSpinner.setAdapter(staticAdapter);
return staticSpinner;
}
}
Full Java file for adapter
public class ModifyListPageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static int TYPE_HEADER = 1;
private static int TYPE_ITEM = 2;
private Context context;
private ArrayList<ModifyListPageItem> items;
public ModifyListPageAdapter(Context context, ArrayList<ModifyListPageItem> items) {
this.context = context;
this.items = items;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
if (viewType == TYPE_HEADER) {
view = LayoutInflater.from(context).inflate(R.layout.item_modlist_header, parent, false);
return new HeaderViewHolder(view);
}
else {
view = LayoutInflater.from(context).inflate(R.layout.item_modlist_object, parent, false);
return new ItemViewHolder(view);
}
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
if (getItemViewType(position) == TYPE_HEADER)
((HeaderViewHolder)holder).SetHeaderDetails(items.get(position));
else
((ItemViewHolder)holder).SetItemDetails(items.get(position));
}
#Override
public int getItemCount() {
return items.size();
}
#Override
public int getItemViewType(int position) {
if (TextUtils.isEmpty(items.get(position).getRank())) {
return TYPE_HEADER;
}
else
return TYPE_ITEM;
}
class HeaderViewHolder extends RecyclerView.ViewHolder {
private TextView txtTitle;
private TextView txtDescription;
public HeaderViewHolder(#NonNull View itemView) {
super(itemView);
txtTitle = itemView.findViewById(R.id.txtModListTitle);
txtDescription = itemView.findViewById(R.id.txtModListDescription);
}
private void SetHeaderDetails(ModifyListPageItem item) {
txtTitle.setText(item.getTitle());
txtDescription.setText(item.getDescription());
}
}
class ItemViewHolder extends RecyclerView.ViewHolder {
private TextView txtRank;
private Spinner spinner;
public ItemViewHolder(#NonNull View itemView) {
super(itemView);
txtRank = itemView.findViewById(R.id.modlist_rank);
spinner = itemView.findViewById(R.id.spinner);
}
private void SetItemDetails(ModifyListPageItem item) {
txtRank.setText(item.getRank());
spinner.setOnItemClickListener(spinner.getOnItemClickListener());
}
}
}
XML file for the page 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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ModifyListActivity">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/bottom_navigation"
app:itemBackground="#color/colorPrimary"
app:itemTextColor="#drawable/selector"
app:itemIconTint="#drawable/selector"
app:menu="#menu/menu_navigation"
android:layout_alignParentBottom="true"
android:background="#color/colorPrimary"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/recyclerViewModifyList"/>
</RelativeLayout>
XML File for the recyclerview item layout:
<?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:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="1dp"
android:padding="8dp"
tools:context=".MainActivity">
<TextView
android:id="#+id/modlist_rank"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="1."
android:textColor="#000000"
android:textSize="38dp" />
<Spinner
android:id="#+id/spinner"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp" />
</LinearLayout>
I want to show items in my custom listview but I cant seem to get it to work. Activity just crashes. My purpose is to show both items in a listview. I am able to retrieve and store the necessary data from firebase into separate arraylists but unable to show them in the listview. Attaching all necessary codes below.
This is my customadapter class
public class CustomAdapter extends ArrayAdapter<String>{
private final Activity context;
private final ArrayList main;
private final ArrayList sub;
public CustomAdapter(Activity context,
ArrayList main, ArrayList sub) {
super(context, R.layout.colortext, main);
this.context = context;
this.main = main;
this.sub = sub;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.colortext, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.textmain);
TextView txtSub=rowView.findViewById(R.id.address);
txtTitle.setText((Integer) main.get(position));
txtSub.setText((Integer) sub.get(position));
return rowView;
}
}
xml of custom
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView1">
</ListView>
<TextView
android:id="#+id/textmain"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeight"
android:paddingLeft="6dip"
android:paddingRight="10dip"
android:textSize="23dp"
android:textColor="#01B9F5"
android:textAppearance="?android:attr/textAppearanceLarge" />
<CheckBox
android:id="#+id/checkBox"
android:clickable="true"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeight"
android:paddingLeft="6dip"
android:paddingRight="10dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:focusable="false"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello"
android:id="#+id/address"
android:layout_below="#+id/checkBox"
android:textColor="#color/white"/>
</RelativeLayout>
mainactivity
mDatabase.child("users").child(mUserId).child("locs").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds:dataSnapshot.getChildren())
{
main.add(ds.child("title").getValue(String.class));
String g = main.toString();
sub.add(ds.child("addr").getValue(String.class));
String s = sub.toString();
ListView list = findViewById(R.id.listView1);
CustomAdapter adapter2 = new CustomAdapter(Location.this, main, sub);
list.setAdapter(adapter2);
}
}
Try this. In your adapter add these methos to add item in your arraylist.
public class CustomAdapter extends ArrayAdapter<String>{
private final ArrayList mainList;
private final ArrayList subList;
public void addMain(Main main){
mainList.add(main);
notifyDataSetChanged();
}
public void addSub(Sub sub){
subList.add(sub);
notifyDataSetChanged();
}
// manage your data in onBind
#Override
public void onBindViewHolder(final ViewHolder holder, int
position) {
if(position < mainList.size() ){
// display mainlist related data here
// after adding items in mainlist, this will executed.
}
if(position > mainList.size()-1) {
// display sublist related data here
}
}
}
You need to add mainList first for the condition in onbind will be met.
You can add data to your adapter like below.
// For example this is that path of your main lists
DatabaseReference ref = database.getReference().child("main");
ref.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// I assume you have a custom object. In this case let's just say `Main`
Main main = dataSnapshot.getValue(Main.class);
adapter.addMain(notification);
}
// ... other override methods
I used spinner sp which filled with SpinnerAdapter adapter and when run the app the spinner will be filled with the first item of Arraylist list witch contains img and text but when I click on the spinner the app stop and Android Monitor says that : Resource ID #0x7f0e00d5 type #0x12 is not valid
. I watched some cases similar to my case but didn't help and here is my code :
public class Serivce_Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.service_activity);
ArrayList<ItemData> list = new ArrayList<>();
list.add(new ItemData("tvsupport", R.drawable.com1_tvsupport));
list.add(new ItemData("refrigerator", R.drawable.com2_refrigerator));
list.add(new ItemData("wifi", R.drawable.com4_wifi));
list.add(new ItemData("plumbing", R.drawable.com5_plumbing));
Spinner sp = (Spinner) findViewById(R.id.request_spinner1);
SpinnerAdapter adapter = new SpinnerAdapter(this, R.layout.spinner_layout, R.id.txt, list);
sp.setAdapter(adapter);
}
}
This is SpinnerAdapter class :
class SpinnerAdapter extends ArrayAdapter<ItemData>{
private int groupid;
Activity context;
private ArrayList<ItemData> list;
private LayoutInflater inflater;
SpinnerAdapter(Activity context, int groupid, int id, ArrayList<ItemData> list){
super(context,id,list);
this.list=list;
inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.groupid=groupid;
}
#NonNull
public View getView(int position, View convertView, #NonNull ViewGroup parent){
View itemView=inflater.inflate(groupid,parent,false);
ImageView imageView=(ImageView)itemView.findViewById(R.id.img);
imageView.setImageResource(list.get(position).getImageId());
TextView textView=(TextView)itemView.findViewById(R.id.txt);
textView.setText(list.get(position).getText());
return itemView;
}
public View getDropDowenView(int position,View convertView,ViewGroup parent){
return getView(position,convertView,parent);
}
}
ItemData :
public class ItemData {
String text;
Integer imageId;
public ItemData(String text, Integer imageId) {
this.text = text;
this.imageId = imageId;
}
public String getText(){
return text;
}
public Integer getImageId(){
return imageId;
}
}
Spinner code :
<Spinner
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="#+id/request_spinner1"
android:layout_gravity="center"
>
</Spinner>
spinner_layout :
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/img"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_marginLeft="20dp"
android:src="#drawable/com0_yourrequest" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:id="#+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/selection"
android:textColor="#2d5d13"
android:textSize="20sp" />
</LinearLayout>
In your spinner layout try removing this line
android:src="#drawable/com0_yourrequest"
I think this resource is missing. And check for other resources too if they are in your res folder or not also check names carefully.Hope it helps !
Check spellings here:
public View getDropDowenView(int position,View convertView,ViewGroup parent){ return getView(position,convertView,parent); }
and change spellings of getDropDowenView to getDropDownView
I want to add card style in my app like this
i use in my app mysql database so i need to make like this cards and put my data from database in it now i use ListView with this code
public void listAllItme() {
ListAdapter lA = new listAdapter(listitems);
listView.setAdapter(lA);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent open = new Intent(R_arabic.this, rewaya_show.class);
open.putExtra("name", listitems.get(position).name);
open.putExtra("url", listitems.get(position).url);
open.putExtra("img", listitems.get(position).img);
open.putExtra("num", listitems.get(position).num);
startActivity(open);
}
}
});
}
class listAdapter extends BaseAdapter {
ArrayList<listitem_gib> lista = new ArrayList<listitem_gib>();
public listAdapter(ArrayList<listitem_gib> lista) {
this.lista = lista;
}
#Override
public int getCount() {
return lista.size();
}
#Override
public Object getItem(int position) {
return lista.get(position).name;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = getLayoutInflater();
View view = layoutInflater.inflate(R.layout.row_item_gib, null);
TextView name = (TextView) view.findViewById(R.id.textView_gib);
ImageView img = (ImageView) view.findViewById(R.id.imageView_gib);
TextView num = (TextView) view.findViewById(R.id.textView_gib2);
TextView size = (TextView) view.findViewById(R.id.textView_gib3);
name.setText(lista.get(position).name);
num.setText(lista.get(position).num);
size.setText(lista.get(position).size);
Picasso.with(R_arabic.this).load("http://grassyhat.com/android/image/" + lista.get(position).img).into(img);
return view;
}
}
first i want to know how i can make like this card style
second how i can use this code with card menu not listview
sorry im new in android and sorry for my bad english
What do you mean by card menu? because the example in the image is a recyclerview with a cardview item, you can achieve this by doing something like this
This will be your activity
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
//Just your list of objects, in your case the list that comes from the db
List<Items> itemsList = new ArrayList<>();
CardAdapter adapter = new CardAdapter(this, itemsList);
//RecyclerView needs a layout manager in order to display data so here we create one
StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
//Here we set the layout manager and the adapter to the listview
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
Inside the layout file you just have to place the recyclerview like this
<RelativeLayout
android:id="#+id/activity_main"
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"
tools:context="jsondh.myapplication.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
Then your adapter will be something like this
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardViewHolder> {
private List<Items> itemsList;
private Activity activity;
public CardAdapter(Activity activity, List<Items> items){
this.activity = activity;
this.itemsList = items;
}
#Override
public CardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = activity.getLayoutInflater().inflate(R.layout.cardview_layout, parent, false);
return new CardViewHolder(itemView);
}
#Override
public void onBindViewHolder(CardViewHolder holder, int position) {
//Here you bind your views with the data from each object from the list
}
#Override
public int getItemCount() {
return itemsList.size();
}
public class CardViewHolder extends RecyclerView.ViewHolder {
public ImageView bookImage;
public TextView bookLabel01, bookLabel02;
public CardViewHolder(View itemView) {
super(itemView);
bookImage = (ImageView)itemView.findViewById(R.id.image);
bookLabel01 = (TextView)itemView.findViewById(R.id.label01);
bookLabel02 = (TextView)itemView.findViewById(R.id.label02);
}
}
And the last one will be the layout from each item on the list, like this
<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"
android:layout_margin="10dp">
<android.support.v7.widget.CardView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:cardElevation="15dp"
app:cardBackgroundColor="#3369Ed">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/image"
android:layout_width="150dp"
android:layout_height="130dp"/>
<TextView
android:id="#+id/label01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Label"
android:layout_gravity="right"
android:padding="5dp"
android:textColor="#ffffff"/>
<TextView
android:id="#+id/label02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LongerLabel"
android:layout_gravity="right"
android:padding="5dp"
android:textColor="#ffffff"/>
</LinearLayout>
</android.support.v7.widget.CardView>
You also have to add this to your gradle file:
compile 'com.android.support:recyclerview-v7:25.0.0'
compile 'com.android.support:cardview-v7:25.0.0'
Hope it helps!
It's pretty simple. You will have to use a RecyclerView with GridLayoutManager and add a cardView to it.
Then, use an Adapter and ViewHolder to feed the data.
I suggest you to check this out:
https://developer.android.com/training/material/lists-cards.html
I followed a good tutorial, with some changes, to create a custom ListView that will allow me to display multiple images for each row in my ListView. What I would like to do is highlight by selecting multiple items in the list and then perform some sort of action to all of those list items by selecting an option on my Options Menu. However, the problem I seem to be running into is that I cannot select multiple items, even though I have added android:choiceMode="multipleChoice" to the ListView in the .xml file. I realize that this can be done using check boxes or radio buttons, but I would prefer to avoid that. I have attached my source code below. Any help would be appreciated. Lastly, thanks to http://custom-android-dn.blogspot.com/ for a great tutorial. Thanks.
CustomlistviewActivity.java
package DucNguyen.example.customlistview;
public class CustomlistviewActivity extends Activity {
private ListView listViewFootballLegend;
private Context ctx;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customlistview);
ctx=this;
List<FootballLegend> legendList= new ArrayList<FootballLegend>();
legendList.add(new FootballLegend("Pele","October 23, 1940 (age 72)","pele","brazil"));
legendList.add(new FootballLegend("Diego Maradona","October 30, 1960 (age 52)","maradona","argentina"));
legendList.add(new FootballLegend("Johan Cruyff","April 25, 1947 (age 65)","cruyff","netherlands"));
legendList.add(new FootballLegend("Franz Beckenbauer","September 11, 1945 (age 67)","beckenbauer","germany"));
legendList.add(new FootballLegend("Michel Platini","June 21, 1955 (age 57)","platini","france"));
legendList.add(new FootballLegend("Ronaldo De Lima","September 22, 1976 (age 36)","ronaldo","brazil"));
listViewFootballLegend = ( ListView ) findViewById( R.id.FootballLegend_list);
listViewFootballLegend.setAdapter( new FootballLegendListAdapter(ctx, R.layout.legend_row_item, legendList ) );
// Click event for single list row
listViewFootballLegend.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
FootballLegend o = (FootballLegend) parent.getItemAtPosition(position);
Toast.makeText(CustomlistviewActivity.this, o.getName().toString(), Toast.LENGTH_SHORT).show();
}
});
}
}
FootballLegendListAdapter.java
package DucNguyen.example.customlistview;
public class FootballLegendListAdapter extends ArrayAdapter<FootballLegend> {
private int resource;
private LayoutInflater inflater;
private Context context;
public FootballLegendListAdapter ( Context ctx, int resourceId, List<FootballLegend> objects) {
super( ctx, resourceId, objects );
resource = resourceId;
inflater = LayoutInflater.from( ctx );
context=ctx;
}
#Override
public View getView ( int position, View convertView, ViewGroup parent ) {
convertView = ( RelativeLayout ) inflater.inflate( resource, null );
FootballLegend Legend = getItem( position );
TextView legendName = (TextView) convertView.findViewById(R.id.legendName);
legendName.setText(Legend.getName());
TextView legendBorn = (TextView) convertView.findViewById(R.id.legendBorn);
legendBorn.setText(Legend.getNick());
ImageView legendImage = (ImageView) convertView.findViewById(R.id.legendImage);
String uri = "drawable/" + Legend.getImage();
int imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
Drawable image = context.getResources().getDrawable(imageResource);
legendImage.setImageDrawable(image);
ImageView NationImage = (ImageView) convertView.findViewById(R.id.Nation);
uri = "drawable/" + Legend.getNation();
imageResource = context.getResources().getIdentifier(uri, null, context.getPackageName());
image = context.getResources().getDrawable(imageResource);
NationImage.setImageDrawable(image);
return convertView;
}
}
FootballLegend.java
package DucNguyen.example.customlistview;
public class FootballLegend {
public FootballLegend(String name, String born, String image, String nation) {
super();
this.name = name;
this.born = born;
this.image = image;
this.nation = nation;
}
private String name;
private String born;
private String image;
private String nation;
public String getName() {
return name;
}
public void setName(String nameText) {
name = nameText;
}
public String getNick() {
return born;
}
public void setNick(String born) {
this.born = born;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getNation() {
return nation;
}
public void setNation(String image) {
this.image = nation;
}
}
legend_row_item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dip" >
<!-- ListRow Left side Thumbnail image -->
<LinearLayout android:id="#+id/thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="3dip"
android:layout_alignParentLeft="true"
android:layout_marginRight="5dip">
<ImageView
android:id="#+id/legendImage"
android:layout_width="50dip"
android:layout_height="50dip" />
</LinearLayout>
<TextView
android:id="#+id/legendName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/thumbnail"
android:layout_toRightOf="#+id/thumbnail"
android:textColor="#040404"
android:typeface="sans"
android:textSize="15dip"
android:textStyle="bold"/>
<TextView
android:id="#+id/legendBorn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/legendName"
android:textColor="#343434"
android:textSize="10dip"
android:layout_marginTop="1dip"
android:layout_toRightOf="#+id/thumbnail" />
<ImageView
android:id="#+id/Nation"
android:layout_width="45dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:layout_marginRight="5dp"
android:layout_centerVertical="true" />
</RelativeLayout>
activity_customlistview.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="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/FootballLegend_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingTop="5dp"
android:choiceMode="multipleChoice" >
</ListView>
</LinearLayout>
The root View of each item you will display in list must implement Checkable. When implementing this interface also update the drawable state of View. See this answer for how to do that.
Set a <selector> drawable as background for this root View. Which different color/drawables for checked state and normal states.
Set ListView's choice mode to single choice or multi-choice.
In list adapter, provide item views with above created View as parent layout.
Now, ListView will take care of setting checked/unchecked state on its item views. Also you can call getCheckedItemIds() or getCheckedItemPositions() on ListView to get currently selected items.