自定义recyclerview项目android

问题描述 投票:-3回答:1

我想创建如下所示的视图。这是水平回收站视图中的视图:

  1. 视图的背景透明。
  2. 使用下面的代码,我能够实现图像中显示的视图。
  3. 生成的视图具有背景白色

enter image description here

enter image description here

下面是生成的图像的源代码,这里我使用协调器布局作为父布局和包含文本和加号图标的相对布局。显示人类图标的图像视图。提前致谢。

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 
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="280dp"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/sixteen_dp"
android:layout_marginEnd="@dimen/sixteen_dp"
android:background="@null">

<RelativeLayout
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="60dp"
    android:background="@drawable/dotted_corner"
    android:paddingBottom="16dp">

    <TextView
        android:id="@+id/add_user_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="68dp"
        android:layout_marginBottom="8dp"
        android:fontFamily="sans-serif"
        android:text="@string/add_user_txt"
        android:textColor="@android:color/black"
        android:textSize="24sp" />

    <ImageView
        android:id="@+id/add_user"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/add_user_tv"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="@dimen/eight_dp"
        android:gravity="center"
        android:src="@drawable/icon_add_new_user"
        tools:ignore="ContentDescription" />/>
</RelativeLayout>

<ImageView
    android:id="@+id/civProfilePic"
    android:layout_width="90dp"
    android:layout_height="90dp"
    android:background="@drawable/dotted_circle"
    android:scaleType="centerInside"
    android:src="@drawable/icon_user_profile_silhoutte_big"
    app:layout_anchor="@id/relativeLayout"
    app:layout_anchorGravity="top|center"
    tools:ignore="ContentDescription" />

android android-layout android-recyclerview android-xml recyclerview-layout
1个回答
1
投票

我想创建如下所示的视图。这是水平回收站视图中的视图

我没有看到任何RecyclerView样品为您的图像,它看起来像只有ImageView在Android存储中选择照片。

..包含文字和加号图标。显示人类图标的图像视图。

如果你想要Horizontal RecyclerView有两个图像和一个文本:

"@+id/civProfilePic"

"@+id/add_user"

"@+id/add_user_tv"

你必须制作类MyAdapter.classMyContain.class并请将您的XML重命名为my_content.xml

这里你需要的代码:

请注意,此代码使用的是FirebaseFirestore

请在build.gradle中添加

dependencies {
    // Firestore
    implementation 'com.google.firebase:firebase-firestore:18.1.0'
    implementation 'com.google.firebase:firebase-storage:16.1.0'

    // Other Firebase
    // don't forget add this in your Manifest.xml , <uses-permission android:name="android.permission.INTERNET" />
    implementation 'com.google.firebase:firebase-auth:16.1.0' 
    implementation 'com.google.android.gms:play-services-auth:16.0.1'

    // Third-party libraries
    // circle image
    implementation 'de.hdodenhof:circleimageview:2.2.0'

    // cropper if you need cropper when pick image from android storage don't forget this in your Manifest <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> and <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    implementation 'com.theartofdev.edmodo:android-image-cropper:2.6.0'

    // reducing size image
    implementation 'com.github.bumptech.glide:glide:4.6.1'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.6.1'
}

MyContain.class

public class MyContain {

     private String civProfilePic;
     private String add_user;         

     // need Empty contructor
     public MyContain(){}

     public MyContain(String civProfilePic, String add_user){
          this.civProfilePic = civProfilePic;
          this.add_user = add_user;
          // don't enter add_user_tv because the Text should not has any getter method, 
     }

     // get your image using this getter
     public String getCivProfilePic() {return civProfilePic;}

     public String getAddUserIcon() {return add_user;}   

} 

MyAdapter.class

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {

    public List<MyContent> contentList;
    public Context context;

    public MyContain(List<MyContent> contentList){
        this.contentList = contentList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_profile_seen_dashboard, parent, false);
        context = parent.getContext();

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

        holder.setIsRecyclable(false);


        // get position of RecyclerView Items and getImage from MyContain class
        String civProfilePic = contentList.get(position).getImage();

        // set photo using String which contain http taken using getImage and load from firestore
        holder.setProfilePhoto(civProfilePic);

        // get position of RecyclerView Items and getAddUserIcon from MyContain class
        String icon_add = contentList.get(position).getAddUserIcon();

        // set icon using String which contain http taken using getAddUserIcon and load from firestore
        holder.setIconAdd(icon_add);



    }

    @Override
    public int getItemCount() {
        return contentList.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        private View mView;

        private ImageView civProfilePic;
        private ImageView add_user;

        public ViewHolder(View itemView){
            super(itemView);
            mView = itemView;

        }

        public void setProfilePhoto(String image) {

            civProfilePic = mView.findViewById(R.id.civProfilePic);
            RequestOptions requestOptions = new RequestOptions();
            requestOptions.placeholder(R.drawable.icon_user_profile_silhoutte_big);
            Glide.with(context).applyDefaultRequestOptions(requestOptions).load(image).into(civProfilePic);
        }


        public void setIcon(String icon) {

            add_user = mView.findViewById(R.id.add_user);
            RequestOptions requestOptions = new RequestOptions();
            requestOptions.placeholder(R.drawable.icon_add_new_user);
            Glide.with(context).applyDefaultRequestOptions(requestOptions).load(icon).into(add_user);
        }
    }

你想在哪里显示回收者视图?片段还是活动?

例如,当您在MainActivity中使用recyclerView时。

MainActivity.class

public class MainActivity extends AppCompatActivity {

    private RecyclerView myRecycler;
    private List<MyContent> contentList;
    private MyAdapter myAdapter;
    private Boolean isFirstPageFirstLoad = true;
    private MyContent myContent;

    private FirebaseFirestore firestore;
    private FirebaseAuth mAuth;
    private DocumentSnapshot lastVisible;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        firebaseAuth = FirebaseAuth.getInstance();
        firebaseFirestore = FirebaseFirestore.getInstance();

        contentList = new ArrayList<>();


        myRecycler = view.findViewById(R.id.my_recycler);
        myAdapter = new MyAdapter(contentList);

        //horizontal recycler
        myRecycler.setLayoutManager(new LinearLayoutManager(container.getContext(), LinearLayoutManager.HORIZONTAL, false));

        myRecycler.setAdapter(myAdapter);

}

@Override
    public void onStart() {
        super.onStart();

        loadFirstQuery();
    }


    public void loadFirstQuery() {

        contentList.clear();

        if (firebaseAuth.getCurrentUser() != null) {       

            myRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);

                    // horizontal
                    Boolean reachRightSide = !recyclerView.canScrollHorizontally(-1);                  

                    // when recycler reach last right side
                    if (reachRightSide) {
                        loadMorePost();
                    }
                }
            });

            // RETRIEVING PROFILE PHOTOS AND ICONS
            Query firstQuery = firestore
                    .collection("ProfilePhoto")                    
                    .orderBy("timestamp", Query.Direction.DESCENDING)
                    .limit(5);

            firstQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
                @Override
                public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {

                    if (isFirstPageFirstLoad) {
                        lastVisible = documentSnapshots.getDocuments().get(documentSnapshots.size() - 1); 
                    }

                    for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {

                        if (doc.getType() == DocumentChange.Type.ADDED) {

                            myContent = doc.getDocument().toObject(MyContent.class);

                            if (isFirstPageFirstLoad) {
                                contentList.add(myContent);
                            } else {
                                contentList.add(0, myContent);
                            }

                            // fire the event                            adapterSeen.notifyDataSetChanged();
                        }
                    }

                    isFirstPageFirstLoad = false;
                }
            });
        }
    }


    public void loadMorePost() {        

        Query nextQuery = firestore
                .collection("ProfilePhoto")                
                .orderBy("timestamp", Query.Direction.DESCENDING)
                .startAfter(lastVisible)
                .limit(5);

        nextQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {

                if (!documentSnapshots.isEmpty()) {

                    lastVisible = documentSnapshots.getDocuments().get(documentSnapshots.size() - 1);
                    for (DocumentChange doc : documentSnapshots.getDocumentChanges()) {

                        if (doc.getType() == DocumentChange.Type.ADDED) {

                            myContent = doc.getDocument().toObject(MyContent.class);
                            contentList.add(myContent);

                            adapterSeen.notifyDataSetChanged();

                        }
                    }
                }
            }
        });
    }

不要忘记这一个,请使用约束,它易于处理

main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".MainActivity">

 <FrameLayout        
        android:layout_width="0dp"
        android:layout_height="85dp"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="@drawable/line"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/constraint">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/my_recycler"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            app:layoutManager="android.support.v7.widget.LinearLayoutManager" />
    </FrameLayout>


</android.support.constraint.ConstraintLayout>

再来一次

在drawable中创建line.xml

这是非常小的一线

<item>
    <shape android:shape="rectangle">
        <stroke
            android:color="@color/line"
            android:width="0.5dp" />
    </shape>
</item>

在colors.xml中

<color name="line">#f1ecec</color>

任何问题 ?

© www.soinside.com 2019 - 2024. All rights reserved.