RecyclerView 不显示所有项目

时间:2021-01-06 19:35:43

标签: java android mobile android-recyclerview

我创建了一个 RecyclerView 来显示我的应用程序的一些测试帖子。但是当我运行我的应用程序时,当我在我的资源文件上创建时,我只能看到用户名而不是测试帖子 imageView。我今天开始学习 RecyclerView,但我对这个视图有很多问题。

注意:我现在不想显示来自任何 url 的任何图像,但只显示我已经保存在我的可绘制文件夹中的图像。而且我知道什么时候不需要在模型中添加 getImageUrl 方法,但也许我会在生产中需要它,这就是我不删除此方法的原因

家庭活动代码:

public class HomeActivity extends AppCompatActivity {

public Uri imguri;
DatabaseReference mRef;
final StorageReference mStorageRef = FirebaseStorage.getInstance().getReference("images");
List<PostModel> postList;

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


    final RecyclerView recyclerView = findViewById(R.id.recyclerView);
    RecyclerView.Adapter recyclerAdapter;
    final FirebaseAuth mAuth = FirebaseAuth.getInstance();
    final FirebaseUser user = mAuth.getCurrentUser();
    final ImageButton new_post = findViewById(R.id.new_post_btn);
    final ImageButton settings = findViewById(R.id.settingsButton);


    if (user == null) {
        finish();
        startActivity(new Intent(HomeActivity.this, MainActivity.class));
    }

    mRef = FirebaseDatabase.getInstance().getReference("users");

    postList = new ArrayList<>();

    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    for (int i = 0; i < 3; i++) {
        PostModel postModel = new PostModel("user " + i, "hello world");

        postList.add(postModel);
}

    recyclerAdapter = new RecyclerAdapter(postList, this);
    recyclerView.setAdapter(recyclerAdapter);


    settings.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity(new Intent(HomeActivity.this,SettingsActivity.class));
        }
    });

    new_post.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            fileChoose();
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null){
        imguri = data.getData();
    }
}

public String getFileExtension(Uri uri){
    ContentResolver cr = getContentResolver();
    MimeTypeMap typeMap = MimeTypeMap.getSingleton();
    return typeMap.getExtensionFromMimeType(cr.getType(uri));
}

public void FileUpload(){
    StorageReference ref = mStorageRef.child(System.currentTimeMillis() + "." + getFileExtension(imguri));

    ref.putFile(imguri)
            .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    // Get a URL to the uploaded content
                    //Uri downloadUrl = taskSnapshot.getDownloadUrl();

                    Toast.makeText(HomeActivity.this, "Meme image successfully uploaded.", Toast.LENGTH_SHORT).show();
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    // Handle unsuccessful uploads
                    // ...
                    Toast.makeText(HomeActivity.this, "error: " + exception, Toast.LENGTH_SHORT).show();
                }
            });
}

public void fileChoose(){
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(intent.ACTION_GET_CONTENT);
    startActivityForResult(intent,1);
}

}

适配器代码:

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

List<PostModel> postList;
Context context;

public RecyclerAdapter(List<PostModel> postList, Context context) {
    this.postList = postList;
    this.context = context;
}

@NonNull
@NotNull
@Override
public ViewHolder onCreateViewHolder(@NonNull @NotNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.post_item,parent, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull @NotNull ViewHolder holder, int position) {
    PostModel postModel = postList.get(position);

    holder.username.setText(postModel.getName());
}

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

public class ViewHolder extends RecyclerView.ViewHolder{
    TextView username;
    ImageView postImg;

    public ViewHolder(@NonNull @NotNull View itemView) {
        super(itemView);

        username = itemView.findViewById(R.id.post_username);
        postImg = itemView.findViewById(R.id.post_image);
    }
}

}

XML 资源文件:

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 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"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:padding="15dp"
    app:cardCornerRadius="20dp"
    android:layout_gravity="center_horizontal"
    app:cardElevation="20dp"
    android:outlineSpotShadowColor="@color/teal_200">

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="wrap_content"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/post_username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="start"
        android:layout_marginStart="10dp"
        android:layout_marginTop="5dp"
        android:clickable="true"
        android:focusable="true"
        android:text="By george sepetadelis"
        android:textColor="@color/black"
        android:textSize="17sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toTopOf="@+id/post_image"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="1.0" />

    <ImageView
        android:id="@+id/post_image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginTop="10dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/post_username"
        tools:srcCompat="@drawable/m1" />

</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>

还有我的模型代码:

public class PostModel {
String name;
String imgUrl;

public PostModel(String name, String imgUrl) {
    this.name = name;
    this.imgUrl = imgUrl;
}

public String getName() {
    return name;
}

public String getImgUrl() {
    return imgUrl;
}
}

1 个答案:

答案 0 :(得分:2)

tools:srcCompat 更改为 app:scrCompat,因为 tools 命名空间仅用于预览 Android Studio 预览选项卡中的内容,并且在您运行应用程序时,会从xml文件

查看 official docs 以获取有关 tools ns 的更多信息

相关问题