自定义recyclerview项目android

时间:2019-03-14 15:49:36

标签: android android-layout android-recyclerview android-xml recyclerview-layout

我想创建下面所示的视图。这是卧式回收机视图中的视图:

  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" />

1 个答案:

答案 0 :(得分:1)

  

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

我没有看到<?php use Illuminate\Support\Str; use Faker\Generator as Faker; $factory->define(App\User::class, function (Faker $faker) { return [ 'name' => $faker->name, 'email' => $faker->unique()->safeEmail, 'email_verified_at' => now(), 'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret 'remember_token' => Str::random(10), ]; }); 的图像样本,看起来只有RecyclerView才能在Android存储设备中选择照片。

  

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

如果您想要ImageView有两张图片和一个文本:

Horizontal RecyclerView

"@+id/civProfilePic"

"@+id/add_user"

您必须创建类"@+id/add_user_tv"MyAdapter.class,然后将上面的XML重命名为MyContain.class

此处是您需要的代码:

请注意,此代码正在使用my_content.xml

请在您的build.gradle中添加

FirebaseFirestore

MyContain.class

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'
}

MyAdapter.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;}   

} 

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

例如,当您在MainActivity中查看recyclerView时。

MainActivity.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);
        }
    }

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

main_activity.xml

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();

                        }
                    }
                }
            }
        });
    }

再一次

使line.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>

colors.xml

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

有什么问题吗?