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>
Related
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.
I want to create an text editor with options at the top (bold,..).
I also want to be able to hide those options; using the exact transition style shown in the picture below.
My problem is that the EditText that I use never has the intended behavious. (In the GIF below for exemple it does not resize after being moved).
I tried using animate (which is what is shown here on the picture).
I also tried with layout animation, combined with setVisibility(View.GONE) when the animation ends (its nearly perfect but for one frame between the two we can see what's happening).
I finally tried setting android:animateLayoutChanges="true". Which works great but I cannot animate the transition as I want.
I also tried combining the three in various ways, but never was successful.
Java:
public class MainActivity extends AppCompatActivity {
boolean optionVisible = true;
LinearLayout Main;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Main = findViewById(R.id.main);
}
public void show(View v) {
if (optionVisible) {
Main.animate().setDuration(300).translationYBy(-Options.getHeight());
} else {
Main.animate().setDuration(300).translationYBy(Options.getHeight());
}
optionVisible = !optionVisible;
}
}
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/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:id="#+id/options"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:fillAfter="true">
... Defining buttons and slider ...
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
... Defining Title EditText ...
</RelativeLayout>
<EditText
android:id="#+id/writter"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:gravity="top"
android:padding="0dp"
android:text="azertyuio"
android:textAlignment="gravity"
android:textColor="#color/text"
android:textSize="20sp"
tools:ignore="HardcodedText"
android:background="#null"
/>
</LinearLayout>
Well I finally managed to get it working properly. I still find the solution akward and would be glad to here another suggestion.
Anyway what I finally did was to use Animations (and not animate), and to have 2 main view basically being set GONE and VISIBLE at oppisite time depending on the presence of options or not.
Here is the code (I used an external class to synchronize the two EditText)
activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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">
<LinearLayout
android:id="#+id/main_with_opt"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:visibility="gone">
<LinearLayout
android:id="#+id/options"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:fillAfter="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<Button
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/underline"/>
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<Button
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/italic"/>
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<Button
style="#style/Widget.AppCompat.Button.Borderless"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="#string/bold"/>
</FrameLayout>
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/size"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="aA"
android:paddingHorizontal="10dp"
android:paddingVertical="5dp"
tools:ignore="HardcodedText"
android:layout_alignParentStart="true"/>
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toEndOf="#id/size"
android:layout_toStartOf="#+id/size_int"/>
<TextView
android:id="#+id/size_int"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/text_size"
android:paddingHorizontal="10dp"
android:paddingVertical="5dp"
tools:ignore="HardcodedText"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<EditText
android:id="#+id/title_with_opt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:lines="1"
android:text="#string/title"
android:maxLines="1"
android:textColor="#color/title"
android:layout_marginStart="10dp"
android:layout_toStartOf="#+id/arrow_with_opt"/>
<ImageButton
style="#style/Widget.AppCompat.Button.Borderless"
android:id="#+id/arrow_with_opt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:src="#drawable/arrow_less"
android:onClick="show"/>
</RelativeLayout>
<com.example.mynotes.SyncEditText
android:id="#+id/typer_with_opt"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:gravity="top"
android:padding="0dp"
android:textAlignment="gravity"
android:textColor="#color/text"
android:textSize="20sp"
android:background="#null"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp">
<EditText
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLines="1"
android:text="#string/title"
android:textColor="#color/title"
android:layout_marginStart="10dp"
android:layout_toStartOf="#+id/arrow"/>
<ImageButton
style="#style/Widget.AppCompat.Button.Borderless"
android:id="#+id/arrow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:src="#drawable/arrow_less"
android:onClick="show"/>
</RelativeLayout>
<com.example.mynotes.SyncEditText
android:id="#+id/typer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:gravity="top"
android:padding="0dp"
android:textAlignment="gravity"
android:textColor="#color/text"
android:textSize="20sp"
android:background="#null"
/>
</LinearLayout>
</FrameLayout>
Main Activity.java :
package com.example.mynotes;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
LinearLayout Options;
boolean optionVisible = false;
LinearLayout Main;
LinearLayout Main_with_opt;
LayoutAnimationController show_lessAnimation;
LayoutAnimationController show_moreAnimation;
com.example.mynotes.SyncEditText Typer;
com.example.mynotes.SyncEditText Typer_with_opt;
int mSelection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Main_with_opt = findViewById(R.id.main_with_opt);
Options = findViewById(R.id.options);
Main = findViewById(R.id.main);
Typer = findViewById(R.id.typer);
Typer_with_opt = findViewById(R.id.typer_with_opt);
Typer.setDependencies(Typer_with_opt);
Typer_with_opt.setDependencies(Typer);
show_lessAnimation = AnimationUtils.loadLayoutAnimation(this, R.anim.show_less_layout);
show_moreAnimation = AnimationUtils.loadLayoutAnimation(this, R.anim.show_more_layout);
}
public void show(View v) {
if (optionVisible) {
Main_with_opt.setLayoutAnimationListener(show_lessAnimationListener);
Main_with_opt.setLayoutAnimation(show_lessAnimation);
Typer.requestFocus();
Typer.setSelection(Typer_with_opt.getSelectionStart());
Typer.scrollTo(Typer_with_opt.getScrollX(), Typer_with_opt.getScrollY());
Main_with_opt.startLayoutAnimation();
} else {
Main_with_opt.setLayoutAnimationListener(show_moreAnimationListener);
Main_with_opt.setLayoutAnimation(show_moreAnimation);
Main_with_opt.setVisibility(View.VISIBLE);
Typer_with_opt.requestFocus();
Typer_with_opt.setSelection(Typer.getSelectionStart());
Typer_with_opt.scrollTo(Typer.getScrollX(), Typer.getScrollY());
Main.setVisibility(View.GONE);
Main_with_opt.startLayoutAnimation();
}
optionVisible = !optionVisible;
}
Animation.AnimationListener show_lessAnimationListener = new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
Main.setVisibility(View.VISIBLE);
Main_with_opt.setVisibility(View.GONE);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
};
Animation.AnimationListener show_moreAnimationListener = new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
}
#Override
public void onAnimationRepeat(Animation animation) {
}
};
}
And the cutom class :
SyncEditText.java :
package com.example.mynotes;
import android.content.Context;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
public class SyncEditText extends AppCompatEditText implements TextWatcher {
private SyncEditText[] mDependencies;
private boolean shouldSync = true;
public SyncEditText(Context context) {
super(context);
}
public SyncEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SyncEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// This is to avoid text changed event is called multiple time per character because auto suggestion
setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
addTextChangedListener(this);
}
private void addTextChangedListener(SyncEditText syncEditText) {
}
public void setDependencies(SyncEditText... dependencies) {
mDependencies = dependencies;
}
public void setText(CharSequence text, boolean syncDependencies) {
shouldSync = syncDependencies;
setText(text);
Log.d("Log", "Text sync: " + text);
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { }
#Override
public void afterTextChanged(Editable editable) { }
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (mDependencies == null)
return;
if (!shouldSync) {
// If this text is sync from other SyncEditText, ignore the change
shouldSync = true;
return;
}
Log.d("Log", "Text input: " + charSequence);
// Sync to all dependencies
for (SyncEditText syncEditText : mDependencies) {
syncEditText.setText(charSequence, false);
}
}
}
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 created a Recyclerview in my main_activity and I wanted to use this cardview in a partial activity... I put extras variables and data to the new activity but any thing not showing in new activity...
this is my partial xml code (hotel_page.xml) :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
android:orientation="vertical">
<android.support.v7.widget.CardView
android:id="#+id/card_view1"
android:layout_width="match_parent"
android:layout_height="288dp"
android:layout_margin="#dimen/card_margin"
android:elevation="3dp"
card_view:cardCornerRadius="0dp"
android:gravity="top">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/card"
android:focusable="true"
android:contextClickable="true"
android:gravity="top"
android:layout_alignParentBottom="true">
</RelativeLayout>
</android.support.v7.widget.CardView>
<TextView
android:id="#+id/title1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="25dp"
android:paddingTop="10dp"
android:textColor="#color/cardview_dark_background"
android:textSize="15dp"
android:layout_above="#+id/count1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ImageView
android:id="#+id/thumbnail1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackgroundBorderless"
android:clickable="true"
android:scaleType="fitXY"
android:contextClickable="true"
android:layout_alignTop="#+id/title1" />
<TextView
android:id="#+id/count1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="5dp"
android:paddingLeft="10dp"
android:paddingRight="25dp"
android:textSize="12dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</LinearLayout>
This is My HotelPageList.java :
package ir.homa;
public class HotelPageList {
private String name;
private int numOfRooms;
private int thumbnail;
public HotelPageList() {
}
public HotelPageList(String name, int numOfRooms, int thumbnail) {
this.name = name;
this.numOfRooms = numOfRooms;
this.thumbnail = thumbnail;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumOfRooms() {
return numOfRooms;
}
public void setNumOfRooms(int numOfRooms) {
this.numOfRooms = numOfRooms;
}
public int getThumbnail() {
return thumbnail;
}
public void setThumbnail(int thumbnail) {
this.thumbnail = thumbnail;
}
}
This is HotelPageAdapter.java :
package ir.homa;
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.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.List;
/**
* Created by SMQ on 7/20/2016.
*/
public class HotelPageAdapter extends RecyclerView.Adapter<HotelPageAdapter.MyViewHolder> {
private Context mContext;
private List<HotelPageList> hotelPage;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView title1, count1;
public ImageView thumbnail1, overflow1;
public MyViewHolder(View view) {
super(view);
title1 = (TextView) view.findViewById(R.id.title1);
count1 = (TextView) view.findViewById(R.id.count1);
thumbnail1 = (ImageView) view.findViewById(R.id.thumbnail1);
overflow1 = (ImageView) view.findViewById(R.id.overflow);
}
}
public HotelPageAdapter(Context mContext, List<HotelPageList> hotelPage) {
this.mContext = mContext;
this.hotelPage = hotelPage;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.hotel_page, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
final HotelPageList hotel = hotelPage.get(position);
holder.title1.setText(hotel.getName());
holder.count1.setText(hotel.getNumOfRooms() + " اتاق");
// loading hotel cover using Glide library
Glide.with(mContext).load(hotel.getThumbnail()).into(holder.thumbnail1);
}
#Override
public int getItemCount() {return hotelPage.size();}
}
and this is result:
Where is problem ?
Try this way
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true"
android:orientation="vertical">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="288dp">
<android.support.v7.widget.CardView
android:id="#+id/card_view1"
android:layout_width="match_parent"
android:layout_height="288dp"
android:elevation="3dp"
card_view:cardCornerRadius="0dp"
android:gravity="top">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/card"
android:focusable="true"
android:contextClickable="true"
android:gravity="top"
android:layout_alignParentBottom="true">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView2"
android:src="#drawable/ic_launcher"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
<TextView
android:id="#+id/title1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="25dp"
android:paddingTop="10dp"
android:textColor="#color/cardview_dark_background"
android:textSize="15dp"
android:text="Title"
android:layout_above="#+id/count1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ImageView
android:id="#+id/thumbnail1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackgroundBorderless"
android:clickable="true"
android:src="#drawable/ic_launcher"
android:contextClickable="true"
android:layout_alignTop="#+id/title1" />
<TextView
android:id="#+id/count1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="5dp"
android:paddingLeft="10dp"
android:paddingRight="25dp"
android:textSize="12dp"
android:text="sub title"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</LinearLayout>
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.