I have a problem with my LayoutInflater. First of all here is my item.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="100dp"
android:background="@drawable/button" >
</RelativeLayout>
(I deleted all unneccessary stuff for this question)
When I set my LayoutInflater in my RecyclerViewAdapter like this:
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, null);
Everything works fine and it looks like I want it to be:
In many documentations and articles about LayouInflater they recommend using the LayoutInflater like this:
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
But when I do that it ignores the attributes from the item.xml file :
There are a lot of articles out there who explain that the first method (the one who works for me) should be avoided. Here is one of those articles: https://web.archive.org/web/20190528213406/https://possiblemobile.com/2013/05/layout-inflation-as-intended/
Here is my full RecyclerView.Adapter class:
public class AdapterTest extends RecyclerView.Adapter<AdapterTest.TestViewHolder> {
@Override
public TestViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, null);
return new TestViewHolder(v);
}
@Override
public void onBindViewHolder(final TestViewHolder holder, int position) {
}
@Override
public int getItemCount() {
return 10;
}
public class TestViewHolder extends RecyclerView.ViewHolder {
public TestViewHolder(View itemView) {
super(itemView);
}
}
}
How can I use the recommended way but still have the results I want?
I fixed it by adding these two lines inside the onCreateViewHolder:
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
v.setLayoutParams(lp);
My onCreateViewHolder now looks like this:
@NonNull
@Override
public TestViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.item, parent, false);
RecyclerView.LayoutParams lp = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
v.setLayoutParams(lp);
return new TestViewHolder(v);
}
Here is the answer where I got that from: https://stackoverflow.com/a/30692398/7735807
I can't really explain why it works now because my RecyclerView was set on MatchParent width and hight from the beginning on. I'm just glad it works now