我在profile fragment中有一个保存用户爱好的RecyclerView。我用StaggeredGridLayout在RecyclerView中放置了项目。如下所示:

但我想展示一下我的项目的一些自定义视图。我想要的自定义视图:

这是我的项目XML文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:gravity="center_horizontal"
android:orientation="vertical"
android:layout_width="match_parent" android:layout_height="wrap_content">
<TextView
android:id="@+id/hobby_profile_title"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:background="@drawable/hobby_background_3"
android:text="Spor"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:textSize="11sp"
android:layout_marginBottom="10dp"
android:gravity="center"
android:textColor="#fff"
android:fontFamily="@font/inter_semibold"/>
</LinearLayout>HobbyAdapter:
public class ProfileHobbyAdapter extends RecyclerView.Adapter<ProfileHobbyViewPager> {
private ArrayList<ProfileHobby> hobby_title;
public ProfileHobbyAdapter(ArrayList<ProfileHobby> hobby_title) {
this.hobby_title = hobby_title;
}
@NonNull
@Override
public ProfileHobbyViewPager onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.profil_hobby_card, parent, false);
ProfileHobbyViewPager profileHobbyViewPager = new ProfileHobbyViewPager(view);
return profileHobbyViewPager;
}
@Override
public void onBindViewHolder(@NonNull ProfileHobbyViewPager holder, int position) {
holder.hobby_profile_title.setText(hobby_title.get(position).getHobby_title());
}
@Override
public int getItemCount() {
return hobby_title.size();
}
}我能用StaggeredGrid得到这个视图吗?或者我应该寻找另一种选择?谢谢你的帮助。
发布于 2020-09-24 00:22:41
你最好用GridLayoutManager代替StaggeredGridLayout
我认为下面的代码可以解决你的问题:
在kotlin:
val layoutManager= GridLayoutManager(activity, 3)
layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
return when (position % 2) {
0 -> 2 //in even rows you have two columns
else -> 3 //in odd rows you have three columns
}
}
}
recyclerView.layoutManager = layoutManager在java中:
GridLayoutManager layoutManager = new GridLayoutManager(this, 3);
layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
switch (position % 2) {
case 0: return 2; //in even rows you have two columns
case 1: return 3; //in odd rows you have two columns
}
}
});
recyclerview.setlayoutmanager(layoutManager)在这段代码中,第一个网格布局已经创建了3列,然后偶数行(由位置%2指定的偶数行)将返回2个跨度,奇数行将显示3个跨度。
https://stackoverflow.com/questions/64029825
复制相似问题