I am working on this application and I'm trying to show my "expenses" database data in my personal fragment. I have created a recycler view file to replace the default layout. I am struggling to make this work. Can anyone help with the FirebaseRecycler Adapter and the holder class? I am not able to make this work, my fragment display the default layout with no information. I have tried and follow some codes but it is not working.
here is my personal fragment where the recycler view should appear
package uk.brighton.ama75.project;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.TextView;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import java.time.chrono.JapaneseDate;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class personalFragment extends Fragment {
private FirebaseAuth mAuth;
private String currentUserID;
private DatabaseReference databaseReference;
private RecyclerView recyclerView;
private Adapter adapter;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_personal, container, false);
mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
databaseReference = FirebaseDatabase.getInstance().getReference().child("Expenses").child(currentUserID);
recyclerView = myView.findViewById(R.id.recycler_expense);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
layoutManager.setStackFromEnd(true);
layoutManager.setReverseLayout(true);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
return myView;
}
#Override
public void onStart() {
super.onStart();
Query query = FirebaseDatabase.getInstance()
.getReference()
.child("expenses")
.limitToLast(5);
FirebaseRecyclerOptions<PersonalExpenses> options =
new FirebaseRecyclerOptions.Builder<PersonalExpenses>()
.setQuery(query, PersonalExpenses.class)
.build();
FirebaseRecyclerAdapter adapter = new FirebaseRecyclerAdapter<PersonalExpenses, MyViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull MyViewHolder holder, int position, #NonNull PersonalExpenses model) {
holder.setDate(model.getDate());
holder.setDescription(model.getDescription());
holder.setAmount(model.getAmount());
holder.setType(model.getType());
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.expense_recycler, parent, false);
return new MyViewHolder(view);
}
};
recyclerView.setAdapter(adapter);
}
#Override
public void onStop() {
super.onStop();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
private final View mView;
public MyViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
private void setDate(String date) {
TextView mDate = mView.findViewById(R.id.date_income);
mDate.setText(date);
}
private void setType(String type) {
TextView mType = mView.findViewById(R.id.type_txt);
mType.setText(type);
}
private void setDescription(String description) {
TextView mNote = mView.findViewById(R.id.note_txt);
mNote.setText(description);
}
private void setAmount(String amount) {
TextView mAmount = mView.findViewById(R.id.amount_income);
String stramount = String.valueOf(amount);
mAmount.setText(stramount);
}
}
}
This is the expenses recycler view file
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/expense_recycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="5dp"
app:cardElevation="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="horizontal">
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1">
<TextView
android:id="#+id/date_income"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="6 June 2019"
android:textAppearance="?android:textAppearanceSmall"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2">
<TextView
android:id="#+id/type_txt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="1"
android:text="Type"
android:textAlignment="center"
android:textAppearance="?android:textAppearanceSmall"
android:textStyle="bold" />
<TextView
android:id="#+id/note_txt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/type_txt"
android:text="#string/description"
android:textAlignment="center"
android:textAppearance="?android:textAppearanceSmall"
android:textStyle="bold" />
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3
">
<TextView
android:id="#+id/amount_income"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="0000"
android:textAlignment="center"
android:textAppearance="?android:textAppearanceSmall"
android:textStyle="bold" />
</RelativeLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
This is the personal 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"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:background="#FFF1F3FC"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
app:cardElevation="5dp"
android:elevation="10dp"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="0dp"
android:layout_weight="1"
android:gravity="center"
android:layout_margin="10dp"
android:layout_height="wrap_content"
tools:ignore="Suspicious0dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:textAppearanceMedium"
android:textColor="#android:color/black"
android:id="#+id/expenses"
android:text="expense"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="0dp"
android:layout_weight="3"
android:gravity="center"
android:layout_margin="10dp"
android:layout_height="wrap_content"
tools:ignore="Suspicious0dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/expense_txt"
android:textAppearance="?android:textAppearanceMedium"
android:textColor="#android:color/black"
android:text="000.00"/>
</RelativeLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:id="#+id/recycler_expense"
android:layout_height="match_parent"/>
</LinearLayout>
I believe you are missing these two main code.
Set adapter.startListening() inside onStart()
Set adapter.stopListening() inside onStop()
Make sure to put the code before the scope end of onStart() as you are performing a lot of operations and setting your adapter above.
Related
I am programming a simple search for users but my app is not displaying the results of the query and crashes about 40% of the time after I click search. Here is my code. Any advice would be appreciated.
My Activity:
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.MyApp.Objects.ParticipantsObject;
import com.MyApp.R;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
public class ParticipantsActivity extends AppCompatActivity {
private EditText mSearchField;
private ImageButton mSearchBtn;
private RecyclerView mResultList;
private DatabaseReference mUserDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_neighbors);
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child("Participants");
mSearchField = (EditText) findViewById(R.id.search_field);
mSearchBtn = (ImageButton) findViewById(R.id.search_btn);
mResultList = (RecyclerView) findViewById(R.id.result_list);
mResultList.setHasFixedSize(true);
mResultList.setLayoutManager(new LinearLayoutManager(this));
mSearchBtn.setOnClickListener(view -> {
String searchText = mSearchField.getText().toString();
firebaseUserSearch(searchText);
});
}
private void firebaseUserSearch(String searchText) {
Toast.makeText(ParticipantsActivity.this, "Started Search", Toast.LENGTH_LONG).show();
Query firebaseSearchQuery = mUserDatabase.orderByChild("name").startAt(searchText);
FirebaseRecyclerOptions<ParticipantsObject> firebaseRecyclerOptions = new FirebaseRecyclerOptions.Builder<ParticipantsObject>()
.setQuery(firebaseSearchQuery, ParticipantsObject.class)
.build();
class UserHolder extends RecyclerView.ViewHolder {
private TextView imageThumbTextView, nameTextView
UserHolder(View itemView) {
super(itemView);
imageThumbTextView = itemView.findViewById(R.id.profile_image);
nameTextView = itemView.findViewById(R.id.name_text);
}
void setUsers(ParticipantsObject participantsObject) {
String imageThumb = driverObject.getThumb_image();
imageThumbTextView.setText(imageThumb);
String name = participantsObject.getName();
nameTextView.setText(name);
}
}
FirebaseRecyclerAdapter<ParticipantsObject, UserHolder> firebaseRecyclerAdapter;
firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<ParticipantsObject, UserHolder>(firebaseRecyclerOptions) {
#Override
protected void onBindViewHolder(#NonNull UserHolder userHolder, int position, #NonNull ParticipantsObject participantsObject) {
userHolder.setUsers(participantsObject);
}
#Override
public UserHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_layout, parent, false);
return new UserHolder(view);
}
};
mResultList.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
}
}
My activity_participants.xml:
<?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"
android:background="#ffffff"
tools:context="com.MyApp.ParticipantsActivity">
<TextView
android:id="#+id/heading_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="30dp"
android:layout_marginTop="30dp"
android:text="Firebase Search"
android:textColor="#555555"
android:textSize="24sp" />
<EditText
android:id="#+id/search_field"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/heading_label"
android:layout_below="#+id/heading_label"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
android:layout_toStartOf="#+id/search_btn"
android:background="#drawable/search_layout"
android:ems="10"
android:hint="Search here"
android:inputType="textPersonName"
android:paddingBottom="10dp"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingTop="10dp"
android:textColor="#999999"
android:textSize="16sp" />
<ImageButton
android:id="#+id/search_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/search_field"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/search_field"
android:layout_marginRight="30dp"
android:background="#android:color/background_light"
app:srcCompat="#mipmap/search_button" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/result_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/search_field"
android:layout_marginTop="50dp">
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
My list 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="wrap_content">
<ImageView
android:id="#+id/profile_image"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="30dp"
android:layout_marginTop="20dp"
app:srcCompat="#mipmap/ic_default_user" />
<TextView
android:id="#+id/name_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginStart="14dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="213dp"
android:layout_marginRight="20dp"
android:layout_toEndOf="#+id/profile_image"
android:text="Username"
android:textColor="#555555"
android:textSize="16sp" />
</RelativeLayout>
Anyone have any ideas as to why it's not displaying results?
My relevant Firebase DB basic paths are like so:
Users -> Participants -> UserIDs -> name, image, etc
Logcat isn't giving me much at the moment.
I want to make an app that shows a list of books that relate to a given keyword. I made the ListView, EditText view and a search button. The layout is given below:
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:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="horizontal">
<EditText
android:id="#+id/search_query_text_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:hint="#string/hint" />
<Button
android:id="#+id/search_button1"
android:layout_width="42dp"
android:layout_height="42dp"
android:drawableLeft="#drawable/search"
/>
</LinearLayout>
<TextView
android:id="#+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:text="Results" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp" />
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:visibility="invisible" />
</RelativeLayout>
</LinearLayout>
The XML for a single item in the list is given below.
list_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="#dimen/list_item_height"
android:layout_margin="5dp"
android:orientation="horizontal">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="#dimen/list_item_height">
<ImageView
android:id="#+id/thumbnail_imageview"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_marginRight="10dp"
android:layout_marginTop="10dp"
android:src="#drawable/kite_runner" />
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="#dimen/list_item_height"
android:layout_margin="5dp">
<TextView
android:id="#+id/title_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="The Kite Runner"
android:textColor="#000000"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/author_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/title_textview"
android:layout_marginBottom="10dp"
android:text="Khaled Hosseini"
android:textColor="#000000"
android:textSize="17sp" />
<TextView
android:id="#+id/publisher_texview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/author_textview"
android:text="Penguin Books"
android:textColor="#000000"
android:textSize="15sp" />
</RelativeLayout>
</LinearLayout>
</LinearLayout>
I am using the Google Books API query to access the book list.
I have the base URL and I now need to add the value in the EditText view to this URL.
The custom adapter for the list view is given below.
package com.example.shara.booklistapp;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by shara on 12/17/2017.
*/
public class ListAdapter extends ArrayAdapter<Blist> {
public ListAdapter(#NonNull Context context, ArrayList<Blist> blists) {
super(context, 0, blists);
}
public String rslt;
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listitemview = convertView;
if (listitemview == null) {
listitemview = LayoutInflater.from(getContext()).inflate(R.layout.list_layout, parent, false);
}
Blist blist = getItem(position);
EditText search_query = listitemview.findViewById(R.id.search_query_text_view);
Button search_button = listitemview.findViewById(R.id.search_button1);
search_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String searchquery = search_query.getText().toString();
}
});
ImageView bookthumbnail = listitemview.findViewById(R.id.thumbnail_imageview);
TextView title = listitemview.findViewById(R.id.title_textview);
TextView author = listitemview.findViewById(R.id.author_textview);
TextView publisher = listitemview.findViewById(R.id.publisher_texview);
return listitemview;
}
}
I am using another class named BookQueryUtils to create the URL and to do the HTTP request and JSON parsing.
I want to access the value of EditText view from BookQueryUtils class and then append it to the base URL.
Also how can I call the AsyncTaskLoader inside the BookQueryUtils class when the button is pressed. How can I do that?
Use Volley, example:
String url = "https://example.com";
StringRequest stringRequest = new StringRequest(Request.Method.GET,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.e("RESPONSE", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
stringRequest.setTag("LOL");
queue.add(stringRequest);
I'm new to Android..
I am trying to create a simple application with a sliding tab to scroll between 2 fragments. The fragments are populated with dummy buttons just to see if the scrolling works. However when I run all I see are the viewPager indexes on top without the fragments. I am also using these two files SlidingTabLayout.java and SlidingTabStrip.java that are given by Android. Here are my classes:
MyFragmentPagerAdapter.java
package billdozer.com.testxml;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
// Holds tab titles
private String tabTitles[] = new String[] { "Frag #1", "Frag #2"};
private Context context;
public MyFragmentPagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return 2;
}
// Return the correct Fragment based on index
#Override
public Fragment getItem(int position) {
if(position == 0){
return new TabFragment1();
} else if(position == 1) {
return new TabFragment2();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
// Return the tab title to SlidingTabLayout
return tabTitles[position];
}
}
TabFragment1.java
package billdozer.com.testxml;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TabFragment1 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.tab_fragment_1, container, false);
return view;
}
}
TabFragment2.java
package billdozer.com.testxml;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class TabFragment2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.tab_fragment_2, container, false);
return view;
}
}
tab_fragment_1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TableLayout
android:id="#+id/tl"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:gravity="center" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center" >
<Button
android:id="#+id/button1"
android:layout_weight="1"
android:text="#string/_1" />
<Button
android:id="#+id/button2"
android:layout_weight="1"
android:text="#string/_2" />
<Button
android:id="#+id/button3"
android:layout_weight="1"
android:text="#string/_3" />
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center" >
<Button
android:id="#+id/button5"
android:layout_weight="1"
android:text="#string/_4" />
<Button
android:id="#+id/button6"
android:layout_weight="1"
android:text="#string/_5" />
<Button
android:id="#+id/button7"
android:layout_weight="1"
android:text="#string/_6" />
</TableRow>
</TableLayout>
</LinearLayout>
tab_fragment_2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TableLayout
android:id="#+id/tl"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:gravity="center" >
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center" >
<Button
android:id="#+id/button1"
android:layout_weight="1"
android:text="#string/_7" />
<Button
android:id="#+id/button2"
android:layout_weight="1"
android:text="#string/_8" />
<Button
android:id="#+id/button3"
android:layout_weight="1"
android:text="#string/_9" />
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center" >
<Button
android:id="#+id/button5"
android:layout_weight="1"
android:text="#string/_10" />
<Button
android:id="#+id/button6"
android:layout_weight="1"
android:text="#string/_11" />
<Button
android:id="#+id/button7"
android:layout_weight="1"
android:text="#string/_12" />
</TableRow>
</TableLayout>
</LinearLayout>
MainActivity.java
package com.example.user.billdozer_ui;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import com.example.user.billdozer_ui.stab.SlidingTabLayout;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new MyFragmentPagerAdapter(getSupportFragmentManager(),
MainActivity.this));
SlidingTabLayout slidingTabLayout = (SlidingTabLayout) findViewById(R.id.sliding_tabs);
slidingTabLayout.setViewPager(viewPager);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.user.billdozer_ui.MainActivity">
<com.example.user.billdozer_ui.stab.SlidingTabLayout
android:id="#+id/sliding_tabs"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0px" />
</LinearLayout>
I want to add shared element transition to items in a recyclerview which will opened on another fragment, but nothing works.
The only view that i want to share is an ImageView.
ImageViews and Textviews inside recyclerview items are loaded using Glide for images and firebase database methods for texts. In the detailed fragment, the bitmap of recyclerview item is passed and only the text is downloaded again.
the method which opens the new fragment from recyclerview items is :
homeUserAnnouncesAdapter.setOnCardAnnounceClickedListener(new OnCardAnnounceClickedListener() {
#Override
public void onCardClicked(CardRentAnnounce card, ImageView imageView, int poz) {
Log.v("TRANSITIONTEST", "CLICKED FROM HOME FRAGMENT --- RENT");
Log.v("TRANSITIONTEST", "in onClick: " + imageView.getTransitionName());
Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
OpenRentAnnounceFragment newFragment = OpenRentAnnounceFragment.newInstanceWithImage(card, bitmap, poz);
newFragment.setSharedElementEnterTransition(new DetailsTransition());
newFragment.setEnterTransition(new Fade());
newFragment.setExitTransition(new Fade());
newFragment.setSharedElementReturnTransition(new DetailsTransition());
getActivity().getSupportFragmentManager()
.beginTransaction()
.addSharedElement(imageView, imageView.getTransitionName())
.replace(R.id.content_main_without_toolbar, newFragment)
.addToBackStack(null)
.commit();
}
});
the DetailsTransition class is :
public class DetailsTransition extends TransitionSet{
public DetailsTransition() {
init();
}
/**
* This constructor allows us to use this transition in XML
*/
public DetailsTransition(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
setOrdering(ORDERING_TOGETHER);
addTransition(new ChangeBounds())
.addTransition(new ChangeTransform())
.addTransition(new ChangeImageTransform());
}
}
i'm assigning different transition names for every view, on adapter:
#Override
public void onBindViewHolder(final HomeUserAnnouncesViewHolder holder, int position) {
final CardRentAnnounce cardRentAnnounce = cardRentAnnounceArrayList.get(position);
holder.updateUI(cardRentAnnounce);
ViewCompat.setTransitionName(holder.rentImage, String.valueOf(position) + "_rent");
MaterialRippleLayout mlr = (MaterialRippleLayout)holder.itemView.findViewById(R.id.search_home_ripple);
mlr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(listener != null){
listener.onCardClicked(cardRentAnnounce, holder.rentImage, holder.getAdapterPosition());
}
}
});
}
the id of image in recyclerview item is identically with the image in fragment
i have followed this tutorial to create the transition, even cloned the project to my pc, run on emulator and trying to do exactly like in the working project but still not working.
how i set the image and imageTransition name in new fragment :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_open_rent_announce, container, false);
rootView = view;
image = (ImageView)view.findViewById(R.id.detailed_image);
image.setImageBitmap(currentImageBitmap);
image.setTransitionName(String.valueOf(pozition) + "_rent");
Log.v("TRANSITIONTEST", "in onCreateView: " + image.getTransitionName());
initViews(view);
setViews();
return view;
}
Fragment SharedElementsTransition tutorial
both images on recyclerview and detailed fragment are loaded with Glide, but i've tried with local images and still no succes.
What did i'm missing? ask for more code if needed.
Thanks.
the full adapter :
package com.minimalart.studentlife.adapters;
import android.content.Context;
import android.net.Uri;
import android.support.v4.view.ViewCompat;
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.ImageView;
import android.widget.TextView;
import com.balysv.materialripple.MaterialRippleLayout;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import com.firebase.ui.storage.images.FirebaseImageLoader;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.minimalart.studentlife.R;
import com.minimalart.studentlife.interfaces.OnCardAnnounceClickedListener;
import com.minimalart.studentlife.interfaces.OnImageReadyListener;
import com.minimalart.studentlife.models.CardRentAnnounce;
import java.util.ArrayList;
/**
* Created by ytgab on 23.01.2017.
*/
public class HomeUserAnnouncesAdapter extends RecyclerView.Adapter<HomeUserAnnouncesAdapter.HomeUserAnnouncesViewHolder>{
public OnCardAnnounceClickedListener listener;
public OnImageReadyListener imageListener;
private ArrayList<CardRentAnnounce> cardRentAnnounceArrayList;
private Context context;
public void setOnCardAnnounceClickedListener(OnCardAnnounceClickedListener listener){
this.listener = listener;
}
public void setOnImageReadyListener(OnImageReadyListener imageListener) {
this.imageListener = imageListener;
}
public HomeUserAnnouncesAdapter(ArrayList<CardRentAnnounce> cardRentAnnounceArrayList, Context context) {
this.cardRentAnnounceArrayList = cardRentAnnounceArrayList;
this.context = context;
}
#Override
public HomeUserAnnouncesViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View announceCard = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_home_user_announces, parent, false);
return new HomeUserAnnouncesAdapter.HomeUserAnnouncesViewHolder(announceCard);
}
#Override
public void onBindViewHolder(final HomeUserAnnouncesViewHolder holder, int position) {
final CardRentAnnounce cardRentAnnounce = cardRentAnnounceArrayList.get(position);
holder.updateUI(cardRentAnnounce);
ViewCompat.setTransitionName(holder.rentImage, String.valueOf(position) + "_rent");
MaterialRippleLayout mlr = (MaterialRippleLayout)holder.itemView.findViewById(R.id.search_home_ripple);
mlr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(listener != null){
listener.onCardClicked(cardRentAnnounce, holder.rentImage, holder.getAdapterPosition());
}
}
});
}
public void loadNewData(ArrayList<CardRentAnnounce> list){
cardRentAnnounceArrayList = list;
}
#Override
public int getItemCount() {
return cardRentAnnounceArrayList.size();
}
public class HomeUserAnnouncesViewHolder extends RecyclerView.ViewHolder{
private TextView rentTitle;
private TextView rentRooms;
private TextView rentPrice;
private TextView rentLocation;
private ImageView rentImage;
private Uri uri;
StorageReference storageReference;
private static final String REF_RENT_IMAGES = "rent-images";
public HomeUserAnnouncesViewHolder(View itemView) {
super(itemView);
rentTitle = (TextView)itemView.findViewById(R.id.card_home_user_announces_title);
rentImage = (ImageView)itemView.findViewById(R.id.detailed_image);
}
public void updateUI(CardRentAnnounce cardRentAnnounce){
getImageURL(cardRentAnnounce.getAnnounceID());
rentTitle.setText(cardRentAnnounce.getTitle());
}
public void getImageURL(String announceID){
FirebaseStorage firebaseStorage = FirebaseStorage.getInstance();
storageReference = firebaseStorage.getReference().child(REF_RENT_IMAGES).child(announceID);
/*rentImage.setImageDrawable(context.getResources().getDrawable(R.drawable.apartment_inside, context.getTheme()));*/
Glide.with(context).using(new FirebaseImageLoader()).load(storageReference).into(new GlideDrawableImageViewTarget(rentImage){
#Override
public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> animation) {
super.onResourceReady(resource, animation);
Log.v("TRANSITIONTEST", "Image ready");
if(imageListener != null)
imageListener.onImageReady();
}
});
}
public ImageView getRentImage(){
return rentImage;
}
public Uri getUri() {
return uri;
}
public void setUri(Uri uri) {
this.uri = uri;
}
}
}
recyclerview card layout :
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card="http://schemas.android.com/apk/res-auto"
android:layout_width="100dp"
android:layout_height="match_parent"
android:id="#+id/card_home_user_announces"
card:cardElevation="#dimen/card_elevation"
card:cardCornerRadius="#dimen/card_radius">
<com.balysv.materialripple.MaterialRippleLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/search_home_ripple">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="120dp"
android:layout_height="120dp"
android:src="#drawable/apartment_inside"
android:id="#+id/detailed_image"
android:scaleType="centerCrop"
android:adjustViewBounds="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:ellipsize="marquee"
android:id="#+id/card_home_user_announces_title"
android:text="Titlu"
android:textColor="#color/textPrincipal"
android:maxLines="1"
android:lines="1"
android:textSize="16sp"
android:textStyle="normal"/>
</LinearLayout>
</com.balysv.materialripple.MaterialRippleLayout>
</android.support.v7.widget.CardView>
detailed fragment layout :
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.minimalart.studentlife.fragments.OpenRentAnnounceFragment">
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/background_light"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:id="#+id/rent_appbar"
android:layout_width="match_parent"
android:layout_height="300dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:fitsSystemWindows="true">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/rent_detailed_collapsing"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginStart="48dp"
app:expandedTitleMarginEnd="64dp"
android:descendantFocusability="blocksDescendants">
<ImageView
android:id="#+id/detailed_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:fitsSystemWindows="true"
android:src="#drawable/apartment_inside"
app:layout_collapseMode="parallax"
android:transitionName="rentTransition"/>
<android.support.v7.widget.Toolbar
android:id="#+id/detailed_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:layout_collapseMode="pin"
app:title="Titlu">
</android.support.v7.widget.Toolbar>
<ImageButton
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="left"
android:layout_marginLeft="#dimen/standard_padding"
android:layout_marginTop="#dimen/standard_padding"
android:src="#drawable/ic_arrow_back"
android:background="#color/full_alpha"
android:id="#+id/detailed_back_btn"/>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="none"
app:behavior_overlapTop="30dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/standard_padding"
android:layout_marginLeft="#dimen/standard_padding"
android:layout_marginRight="#dimen/standard_padding">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/detailed_description"
android:textColor="#color/textSecondary"
android:textSize="16sp"
android:text="Descriere: "
android:padding="#dimen/activity_horizontal_margin" />
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/standard_padding"
android:layout_marginLeft="#dimen/standard_padding"
android:layout_marginRight="#dimen/standard_padding">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/detailed_rooms"
android:textColor="#color/textSecondary"
android:textSize="16sp"
android:text="Număr camere: "
android:padding="#dimen/activity_horizontal_margin" />
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/standard_padding"
android:layout_marginLeft="#dimen/standard_padding"
android:layout_marginRight="#dimen/standard_padding">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/detailed_location"
android:textColor="#color/textSecondary"
android:textSize="16sp"
android:text="Locatie: "
android:padding="#dimen/activity_horizontal_margin" />
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/standard_padding"
android:layout_marginLeft="#dimen/standard_padding"
android:layout_marginRight="#dimen/standard_padding">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/detailed_price"
android:textColor="#color/textSecondary"
android:textSize="16sp"
android:text="Pret: "
android:padding="#dimen/activity_horizontal_margin" />
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/standard_padding"
android:layout_marginLeft="#dimen/standard_padding"
android:layout_marginRight="#dimen/standard_padding"
android:layout_marginBottom="#dimen/standard_padding">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/detailed_discount"
android:textColor="#color/textSecondary"
android:textSize="16sp"
android:text="Discount studenti"
android:padding="#dimen/activity_horizontal_margin" />
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/standard_padding"
android:layout_marginRight="#dimen/standard_padding"
android:layout_marginBottom="#dimen/standard_padding">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/detailed_seller"
android:textSize="16sp"
android:text="#string/open_rent_seller"
android:padding="#dimen/activity_horizontal_margin" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/detailed_contact_user_email"
android:background="#color/full_alpha"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:text="#string/open_rent_email"
android:textStyle="bold"
android:textColor="#color/textSecondary"
android:layout_weight="1">
</Button>
<Button
android:id="#+id/detailed_contact_user_phone"
android:background="#color/full_alpha"
android:layout_height="wrap_content"
android:layout_width="0dp"
android:text="#string/open_rent_phone"
android:textStyle="bold"
android:textColor="#color/textSecondary"
android:layout_weight="1">
</Button>
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
</android.support.v4.widget.NestedScrollView>
<android.support.design.widget.FloatingActionButton
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_margin="#dimen/activity_horizontal_margin"
android:id="#+id/rent_detailed_fab"
app:fabSize="normal"
android:src="#drawable/ic_favorite"
android:layout_gravity="bottom|end" />
</android.support.design.widget.CoordinatorLayout>
</FrameLayout>
I am trying to add a RecyclerView with GridLayoutManagerto my app. Everything works as expected, only problem is it seems the columns are left justified instead of center justified. Any ideas? Thanks in advance!
Here is an image showing how it looks:
Here is the single 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="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:background="?android:selectableItemBackgroundBorderless"
android:clickable="true"
android:gravity="center_horizontal"
android:orientation="vertical">
<ImageView
android:id="#+id/iconSpot"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="center_horizontal"
android:src="#drawable/ic_launcher"
tools:ignore="MissingPrefix" />
<TextView
android:id="#+id/textLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Dummy Text"
android:textSize="16sp" />
</LinearLayout>
And here is the full activity 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:id="#+id/totalScreen"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignTop="#+id/fab"
android:layout_gravity="bottom|center"
android:gravity="bottom|center_vertical">
<TextView
android:id="#+id/sheetTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#424242"
android:padding="12dp"
android:text="Dummy Title"
android:textSize="18sp" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/sheetTitle"
android:layout_marginEnd="20dp"
android:layout_marginTop="-28dp"
android:visibility="gone"
app:fabSize="normal" />
<android.support.v7.widget.RecyclerView
android:id="#+id/gridScreen"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/sheetTitle"
android:background="#424242"
android:gravity="bottom|center"
android:layout_gravity = "center"
android:orientation="vertical"
android:paddingBottom="24dp" />
</RelativeLayout>
Ok! I figured it out, it ended up being the fact that I needed to make the item layout width set as match_parent instead of wrap_content. So that makes it look like this:
<?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_gravity="center_horizontal"
android:layout_margin="10dp"
android:background="?android:selectableItemBackgroundBorderless"
android:clickable="true"
android:orientation="vertical">
<ImageView
android:id="#+id/iconSpot"
android:layout_width="44dp"
android:layout_height="44dp"
android:layout_gravity="center_horizontal"
android:src="#drawable/ic_launcher"
tools:ignore="MissingPrefix" />
<TextView
android:id="#+id/textLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Dummy Text"
android:textSize="16sp" />
</LinearLayout>
It is hard to fix with just the layout file since the item layout needs to be inflated and attached to the main layout in order to see the result.
So I decided to recreate it. I made modification to your layout file.
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="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#color/colorPrimary"
android:layout_margin="2dp"
android:clickable="true"
android:orientation="vertical">
<ImageView
android:id="#+id/iconSpot"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="center_horizontal"
android:src="#android:drawable/ic_delete"
tools:ignore="MissingPrefix" />
<TextView
android:id="#+id/textLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Dummy Text"
android:textSize="16sp" />
</LinearLayout>
Main activity 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:id="#+id/totalScreen"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignTop="#+id/fab"
android:layout_gravity="bottom|center"
android:gravity="bottom|center_vertical">
<TextView
android:id="#+id/sheetTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#424242"
android:padding="12dp"
android:text="Dummy Title"
android:textSize="18sp" />
<android.support.v7.widget.RecyclerView
android:id="#+id/gridScreen"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/sheetTitle"
android:background="#424242"
android:gravity="bottom|center"
android:layout_gravity = "center"
android:clipToPadding="false"
android:orientation="vertical"
android:paddingBottom="24dp" />
</RelativeLayout>
Main Activity class. This class (GridSpacingItemDecoration) used for item margin is copied from here
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private GridLayoutManager layout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = new GridLayoutManager(MainActivity.this, 2);
RecyclerView rView = (RecyclerView)findViewById(R.id.gridScreen);
rView.setHasFixedSize(true);
rView.setLayoutManager(layout);
int spanCount = 2;
int spacing = 50;
boolean includeEdge = true;
rView.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, includeEdge));
RecyclerViewAdapter rcAdapter = new RecyclerViewAdapter(MainActivity.this, getAllItemList());
rView.setAdapter(rcAdapter);
}
private List<ItemObject> getAllItemList(){
List<ItemObject> allItems = new ArrayList<ItemObject>();
allItems.add(new ItemObject(android.R.drawable.ic_delete, "United"));
allItems.add(new ItemObject(android.R.drawable.ic_delete, "United"));
allItems.add(new ItemObject(android.R.drawable.ic_delete, "United"));
allItems.add(new ItemObject(android.R.drawable.ic_delete, "United"));
allItems.add(new ItemObject(android.R.drawable.ic_delete, "United"));
allItems.add(new ItemObject(android.R.drawable.ic_delete, "United"));
return allItems;
}
}
RecycleView Adapter Class
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewHolders> {
private List<ItemObject> itemList;
private Context context;
public RecyclerViewAdapter(Context context, List<ItemObject> itemList) {
this.itemList = itemList;
this.context = context;
}
#Override
public RecyclerViewHolders onCreateViewHolder(ViewGroup parent, int viewType) {
View layoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.list, null);
RecyclerViewHolders rcv = new RecyclerViewHolders(layoutView);
return rcv;
}
#Override
public void onBindViewHolder(RecyclerViewHolders holder, int position) {
holder.displayedImage.setImageResource(itemList.get(position).getImage());
holder.textTitle.setText(itemList.get(position).getTitle());
}
#Override
public int getItemCount() {
return this.itemList.size();
}
}
ViewHolder class
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class RecyclerViewHolders extends RecyclerView.ViewHolder implements View.OnClickListener{
public ImageView displayedImage;
public TextView textTitle;
public RecyclerViewHolders(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
displayedImage = (ImageView)itemView.findViewById(R.id.iconSpot);
textTitle = (TextView)itemView.findViewById(R.id.textLabel);
}
#Override
public void onClick(View view) {
}
}
ObjectEntity class
public class ItemObject {
private int image;
private String title;
public ItemObject(int image, String title) {
this.image = image;
this.title = title;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
The Result is below. Try and see if it works for you.