I'm writing a coursework project and I need to create a custom material card.
But when I inherit a material card, the styles disappear. I have tried all the solutions I found on the Internet. I will be grateful for any help.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Case aCase = new Case();
aCase.setId(183928);
aCase.setStatus("Status");
aCase.setDescription("fermentum dui faucibus in ornare quam viverra orci sagittis eu");
CaseView caseView = findViewById(R.id.caseView);
caseView.setCase(aCase);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.card.MaterialCardView
android:id="#+id/card"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/title"
android:textAppearance="?attr/textAppearanceHeadline6" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="secondary_text"
android:textAppearance="?attr/textAppearanceBody2"
android:textColor="?android:attr/textColorSecondary" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="supporting_text"
android:textAppearance="?attr/textAppearanceBody2"
android:textColor="?android:attr/textColorSecondary" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:orientation="horizontal">
<com.google.android.material.button.MaterialButton
style="?attr/borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:text="action_1" />
<com.google.android.material.button.MaterialButton
style="?attr/borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="action_2" />
</LinearLayout>
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
<com.barmatograf.interpolith.view.CaseView
android:id="#+id/caseView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
screenshot https://i.stack.imgur.com/htRq0.png
model class for custom card
package com.barmatograf.interpolith.model;
public class Case {
private Integer id;
private String description;
private String status;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
CaseView.java
package com.barmatograf.interpolith.view;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.TextView;
import com.barmatograf.interpolith.R;
import com.barmatograf.interpolith.model.Case;
import com.google.android.material.card.MaterialCardView;
public class CaseView extends MaterialCardView {
private Case aCase;
private TextView number;
private TextView status;
private TextView description;
public CaseView(Context context) {
this(context, null);
}
public CaseView(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.materialCardViewStyle);
}
public CaseView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
inflate(context, R.layout.case_view_layout, this);
number = findViewById(R.id.case_number);
status = findViewById(R.id.case_status);
description = findViewById(R.id.case_description);
}
public void setCase(Case aCase) {
this.aCase = aCase;
if (aCase != null) {
if (aCase.getId() != null)
number.setText(String.valueOf(aCase.getId()));
if (aCase.getStatus() != null)
status.setText(aCase.getStatus());
if (aCase.getDescription() != null) {
String descriptionText = aCase.getDescription();
int length = Math.min(descriptionText.length(), 100);
descriptionText = descriptionText.substring(0, length);
descriptionText = descriptionText.trim();
descriptionText = descriptionText + "...";
description.setText(descriptionText);
}
}
}
public Case getCase() {
return aCase;
}
}
case_view_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:orientation="horizontal">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/title"
android:textAppearance="?attr/textAppearanceHeadline6" />
<TextView
android:id="#+id/case_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?attr/textAppearanceHeadline6" />
</LinearLayout>
<TextView
android:id="#+id/case_status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:textAppearance="?attr/textAppearanceBody2"
android:textColor="?android:attr/textColorSecondary" />
<TextView
android:id="#+id/case_description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:textAppearance="?attr/textAppearanceBody2"
android:textColor="?android:attr/textColorSecondary" />
</LinearLayout>
</com.google.android.material.card.MaterialCardView>
styles
<style name="AppTheme" parent="Theme.MaterialComponents">
<item name="materialCardViewStyle">#style/Widget.MaterialComponents.CardView</item>
</style>
note that your CaseView IS a MaterialCardView (extends), but you have also another MaterialCardView as a root of your inflated XML. this is another View without style set (no xml style attr), in fact your CaseView contains one child - another MaterialCardView.
imho it should respect "global" setting from AppTheme, but still worth fix this double-CardView case - use <merge tag instead of root MaterialCardView in XML. inflate method will add all childs placed inside <merge> tag to CaseView
Related
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 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 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.
I am trying to implement a list of Card views, and the list is fine, but the layout inside the card is nothing like what i have defined in the XML. Any ideas why this is not showing properly? Here is my card XML:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
android:id="#+id/cvAdvertFavourite"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="2dip"
android:layout_marginBottom="2dip"
card_view:cardUseCompatPadding="true"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
>
<ImageView
android:id="#+id/ivCardFavouriteAnimalPhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginRight="8dp"
/>
<TextView
android:id="#+id/tvCardFavouriteTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/ivCardFavouriteAnimalPhoto"
android:textSize="30sp"
/>
<TextView
android:id="#+id/tvCardFavouriteRace"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvCardFavouriteTitle"
android:layout_toRightOf="#+id/ivCardFavouriteAnimalPhoto"
/>
<TextView
android:id="#+id/tvCardFavouritePrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvCardFavouriteRace"
android:layout_toRightOf="#+id/ivCardFavouriteAnimalPhoto"
/>
</RelativeLayout>
</android.support.v7.widget.CardView>
I use this RecyclerView 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="wrap_content"
android:padding="16dp"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/rvCardFavourite"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
Here is my CardItem class:
public class FavouriteCardItem {
Bitmap animal;
int price;
String title, race;
public FavouriteCardItem(Bitmap animal, int price, String title, String race){
this.animal = animal;
this.price = price;
this.title = title;
this.race = race;
}
public Bitmap getAnimal() {
return animal;
}
public void setAnimal(Bitmap animal) {
this.animal = animal;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getRace() {
return race;
}
public void setRace(String race) {
this.race = race;
}
}
Here is how I call my adapter and set the data for the adapter:
private void loadSetData() {
List<FavouriteCardItem> items = new ArrayList<FavouriteCardItem>();
Bitmap bitmap = BitmapFactory.decodeResource(getActivity().getResources(),
R.drawable.bird);
FavouriteCardItem item1 = new FavouriteCardItem(bitmap, 100, "birds", "birds");
items.add(item1);
Bitmap bitmap2 = BitmapFactory.decodeResource(getActivity().getResources(),
R.drawable.dog);
FavouriteCardItem item2 = new FavouriteCardItem(bitmap2, 200, "dogs", "dogs");
items.add(item2);
Bitmap bitmap3 = BitmapFactory.decodeResource(getActivity().getResources(),
R.drawable.cat);
FavouriteCardItem item3 = new FavouriteCardItem(bitmap3, 1000, "cats", "cats");
items.add(item3);
FavouriteCardAdapter adapter = new FavouriteCardAdapter(getActivity(), R.layout.card_view, items);
recyclerView.setAdapter(adapter);
}
And this is my Adapter class:
public class FavouriteCardAdapter extends RecyclerView.Adapter<FavouriteCardAdapter.CardViewHolder> {
private Context mContext;
private int resourceId;
List<FavouriteCardItem> cardItems;
public FavouriteCardAdapter(Context context, int resource, List<FavouriteCardItem> cardItems){
mContext = context;
resourceId = resource;
this.cardItems = cardItems;
}
#Override
public CardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view, parent, false);
CardViewHolder cvh = new CardViewHolder(v);
return cvh;
}
#Override
public void onBindViewHolder(CardViewHolder holder, int position) {
DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
int screenHeight = metrics.heightPixels;
holder.cardView.getLayoutParams().height = screenHeight / 4;
int price = cardItems.get(position).getPrice();
String price1 = Integer.toString(price);
holder.tvPrice.setText(price1);
holder.tvRace.setText(cardItems.get(position).getRace());
holder.tvTitle.setText(cardItems.get(position).getTitle());
holder.ivAnimal.setImageBitmap(cardItems.get(position).getAnimal());
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public int getItemCount() {
return cardItems.size();
}
public class CardViewHolder extends RecyclerView.ViewHolder{
CardView cardView;
ImageView ivAnimal;
TextView tvPrice, tvTitle, tvRace;
public CardViewHolder(View itemView) {
super(itemView);
cardView = (CardView) itemView.findViewById(R.id.cvAdvertFavourite);
ivAnimal = (ImageView) itemView.findViewById(R.id.ivCardFavouriteAnimalPhoto);
tvPrice = (TextView) itemView.findViewById(R.id.tvCardFavouritePrice);
tvTitle = (TextView) itemView.findViewById(R.id.tvCardFavouriteTitle);
tvRace = (TextView) itemView.findViewById(R.id.tvCardFavouriteRace);
}
}
}
BTW I am aware that I am not supposed to load images like this and so on, but I just wanted to create some test data to get the layout right before i start loading the data from the online data storage.
Here is how the whole Card view looks like. It should have 3 textViews and 1 imageView, but it only shows one imageView.....
You can try this as one of the solution if you do not want to specify the dimension for width and height of Image
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
android:id="#+id/cvAdvertFavourite"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="2dip"
android:layout_marginBottom="2dip"
card_view:cardUseCompatPadding="true"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="8dp"
>
<ImageView
android:id="#+id/ivCardFavouriteAnimalPhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
android:weight = "2"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:weight = "1" />
<TextView
android:id="#+id/tvCardFavouriteTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:textSize="20sp"
/>
<TextView
android:id="#+id/tvCardFavouriteRace"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvCardFavouriteTitle"
/>
<TextView
android:id="#+id/tvCardFavouritePrice"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvCardFavouriteRace"
/>
</RelativeLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
In this I have used LinearLayout which will distribute the screen width in the ratio 2:1 between ImageView and RelativeLayout with text.
Also I have reduced the size of text from 30sp to 20sp
try to make your card xml look like this:
<android.support.v7.widget.CardView
android:id="#+id/cvAdvertFavourite"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="2dip"
android:layout_marginBottom="2dip"
card_view:cardUseCompatPadding="true"
>
<RelativeLayout
android:id="#+id/something"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
>
<ImageView
android:id="#+id/ivCardFavouriteAnimalPhoto"
android:layout_width="#dimen/your_size_of_image" // the important part
android:layout_height="#dimen/your_size_of_image" // the important part
android:layout_centerVertical="true"
android:scaleType="centerCrop"/>
<LinearLayout // make sure you are using a linearlyout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toEndOf="#id/ivCardFavouriteAnimalPhoto"
android:layout_toRightOf="#id/ivCardFavouriteAnimalPhoto"
android:orientation="vertical">
<TextView
android:id="#+id/tvCardFavouriteTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" />
<TextView
android:id="#+id/tvCardFavouriteRace"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" />
<TextView
android:id="#+id/tvCardFavouritePrice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" />
</LinearLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>