在Android应用中的RecyclerView适配器问题

huangapple go评论97阅读模式
英文:

Problem with RecyclerView Adapter in Android App

问题

以下是您提供的代码部分的中文翻译:

// MessageAdapter.java
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageAdapterViewHolder> {
    // ... 省略其他代码 ...
}

// UserProfileActivity.java
public class UserProfileActivity extends AppCompatActivity {
    // ... 省略其他代码 ...
}

// chat_message_received.xml
<!--
    此处为chat_message_received布局的XML内容省略了一些属性和值
    如果您需要完整的布局内容请查看原始代码
-->

// chat_message_sent.xml
<!--
    此处为chat_message_sent布局的XML内容省略了一些属性和值
    如果您需要完整的布局内容请查看原始代码
-->

// UserComments Layout:
<!--
    此处为UserComments布局的XML内容省略了具体代码
    您可以在提供的链接中查看完整的布局内容
-->

// 更新部分
// 问题出在message布局的android:textAppearance属性上,已经将其移除以解决问题。

请注意,由于篇幅较长,上述内容只是代码的主要部分和重点,省略了一些细节。如果您需要特定部分的更多细节,请随时告诉我。

英文:

I'm having a problem with RecyclerView and my adapter. The messages inside the RecyclerView are showing too small in the layout, here you can see in an image: Click to see the Image

MessageAdapter.java:

public class MessageAdapter extends RecyclerView.Adapter&lt;MessageAdapter.MessageAdapterViewHolder&gt; {

    private Context context;
    private List&lt;Message&gt; messages;
    public static final int MSG_TYPE_LEFT = 0;
    public static final int MSG_TYPE_RIGHT = 1;

    public MessageAdapter(Context context, List&lt;Message&gt; messages) {
        this.context = context;
        this.messages = messages;
    }

    @Override
    public int getItemViewType(int position) {
        FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        assert firebaseUser != null;
        if (messages.get(position).getName().equals(firebaseUser.getDisplayName())) {
            return MSG_TYPE_RIGHT;
        } else {
            return MSG_TYPE_LEFT;
        }
    }

    @NonNull
    @Override
    public MessageAdapterViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        if (viewType == MSG_TYPE_RIGHT) {
            View view = LayoutInflater.from(context).inflate(R.layout.fragment_chat_message_sent, parent, false);
            return new MessageAdapterViewHolder(view);
        } else {
            View view = LayoutInflater.from(context).inflate(R.layout.fragment_chat_message_received, parent, false);
            return new MessageAdapterViewHolder(view);
        }
    }

    @Override
    public void onBindViewHolder(@NonNull final MessageAdapterViewHolder holder, final int position) {
        final Message message = messages.get(position);
        ConstraintLayout constraintLayoutMessageSent;
        int viewType = holder.getItemViewType();
        if (viewType == MSG_TYPE_LEFT) {
            holder.textViewChatName.setText(message.getName());
            holder.textViewChatMessage.setText(message.getMessage());
            holder.textViewChatMessageDate.setText(message.getHourminute());
            holder.imageViewChatUserProfile.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, UserProfileActivity.class);
                    intent.putExtra(&quot;username&quot;, message.getName());
                    context.startActivity(intent);
                }
            });
        } else {
            constraintLayoutMessageSent = holder.itemView.findViewById(R.id.constraintLayoutMessageSent);
            holder.textViewChatMessage.setText(message.getMessage());
            holder.textViewChatMessageDate.setText(message.getHourminute());
            holder.imageViewChatMessageStatus.setImageDrawable(ResourcesCompat.getDrawable(context.getResources(), R.drawable.ic_message_sent, null));
            constraintLayoutMessageSent.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(holder.itemView.getContext());
                    builder.setMessage(R.string.delete_message)
                            .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    deleteMessage(position);
                                }
                            }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int which) {
                            dialogInterface.dismiss();
                        }
                    });
                    builder.create();
                    builder.show();
                    return false;
                }
            });
        }
    }

    private void deleteMessage(int position) {
        String messageKey = messages.get(position).getKey();
        DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference(&quot;Messages&quot;);
        databaseReference.child(messageKey).removeValue();
    }

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

    public static class MessageAdapterViewHolder extends RecyclerView.ViewHolder {
        private TextView textViewChatMessage;
        private TextView textViewChatName;
        private TextView textViewChatMessageDate;
        private ImageView imageViewChatMessageStatus;
        private ImageView imageViewChatUserProfile;

        public MessageAdapterViewHolder(@NonNull final View itemView) {
            super(itemView);
            textViewChatName = itemView.findViewById(R.id.textViewChatName);
            textViewChatMessage = itemView.findViewById(R.id.textViewChatMessage);
            textViewChatMessageDate = itemView.findViewById(R.id.textViewChatMessageDate);
            imageViewChatMessageStatus = itemView.findViewById(R.id.imageViewChatMessageStatus);
            imageViewChatUserProfile = itemView.findViewById(R.id.imageViewChatUserProfile);
        }
    }
}

UserCommentsActivity.java:

    public class UserProfileActivity extends AppCompatActivity {
private Context context;
private Toolbar toolbar;
private String username = &quot;&quot;;
private ImageView imageViewUserProfileProfile;
private TextView textViewUserProfileName;
private TextView textViewUserProfileDescription;
private ConstraintLayout loadingLayout;
private LottieAnimationView lottieAnimationViewLoading;
private RecyclerView recyclerViewUserProfileComments;
private TextView textViewUserProfileNoComments;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_profile);
username = getIntent().getStringExtra(&quot;username&quot;);
context = getApplicationContext();
toolbar = findViewById(R.id.toolbarUserProfile);
// TODO set the title of the user profile visiting.
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
bindUI();
}
private void bindUI() {
loadingLayout = findViewById(R.id.loadingLayout);
lottieAnimationViewLoading = findViewById(R.id.lottieAnimationViewLoading);
imageViewUserProfileProfile = findViewById(R.id.imageViewUserProfileProfile);
textViewUserProfileName = findViewById(R.id.textViewUserProfileName);
textViewUserProfileDescription = findViewById(R.id.textViewUserProfileDescription);
recyclerViewUserProfileComments = findViewById(R.id.recyclerViewUserProfileComments);
textViewUserProfileNoComments = findViewById(R.id.textViewUserProfileNoComments);
getUserInformation();
getUserComments();
}
private void getUserInformation() {
loadingLayout.setVisibility(View.VISIBLE);
Thread thread = new Thread() {
@Override
public void run() {
try {
String description = &quot;&quot;;
String gender = &quot;&quot;;
String profile_picture = &quot;&quot;;
Response response = HttpRequests.getUserInformation(username);
String responseBody = Objects.requireNonNull(response.body()).string();
responseBody = responseBody.replace(&quot;\r\n&quot;, &quot;&quot;);
JSONArray responseArray = new JSONArray(responseBody);
for (int i = 0; i &lt; responseArray.length(); i++) {
JSONObject jsonobject = responseArray.getJSONObject(i);
description = jsonobject.getString(&quot;description&quot;);
gender = jsonobject.getString(&quot;gender&quot;);
profile_picture = jsonobject.getString(&quot;profile_picture&quot;);
updateUI(description, gender, profile_picture);
}
} catch (IOException | JSONException e) {
showErrors();
e.printStackTrace();
}
}
};
thread.start();
}
private void getUserComments() {
loadingLayout.setVisibility(View.VISIBLE);
Thread thread = new Thread() {
@Override
public void run() {
try {
List&lt;Message&gt; userMessageList = new ArrayList&lt;&gt;();
String name = &quot;&quot;;
String comment = &quot;&quot;;
Response response = HttpRequests.getUserComments(username);
String responseBody = Objects.requireNonNull(response.body()).string();
responseBody = responseBody.replace(&quot;\r\n&quot;, &quot;&quot;);
JSONArray responseArray = new JSONArray(responseBody);
for (int i = 0; i &lt; responseArray.length(); i++) {
Message message = new Message();
JSONObject jsonobject = responseArray.getJSONObject(i);
name = jsonobject.getString(&quot;from_user&quot;);
comment = jsonobject.getString(&quot;comment&quot;);
if (!name.isEmpty() &amp;&amp; !comment.isEmpty()) {
message.setName(name);
message.setMessage(comment);
userMessageList.add(message);
}
}
if (userMessageList.size() &gt; 0) {
updateComments(userMessageList);
}else{
updateCommentSection();
}
} catch (IOException | JSONException e) {
showErrors();
updateCommentSection();
e.printStackTrace();
}
}
};
thread.start();
}
private void showErrors() {
Thread thread = new Thread() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(context, getString(R.string.generic_error), Toast.LENGTH_LONG).show();
}
});
}
};
thread.start();
}
private void updateUI(final String description, final String gender, final String pictureURL) {
Thread thread = new Thread() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
//Picasso.get()
//        .load(pictureURL)
//        .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
//        .into(imageViewUserProfileProfile);
toolbar.setTitle(username + &quot; - &quot; + getString(R.string.user_profile));
textViewUserProfileName.setText(username);
if (description.equals(&quot;null&quot;)) {
textViewUserProfileDescription.setText(&quot;&quot;);
} else {
textViewUserProfileDescription.setText(description);
}
loadingLayout.setVisibility(View.GONE);
lottieAnimationViewLoading.cancelAnimation();
}
});
}
};
thread.start();
}
private void updateComments(final List&lt;Message&gt; userMessageList) {
Thread thread = new Thread() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
linearLayoutManager.setStackFromEnd(true);
recyclerViewUserProfileComments.setLayoutManager(linearLayoutManager);
MessageAdapter messageAdapter = new MessageAdapter(context, userMessageList);
recyclerViewUserProfileComments.setAdapter(messageAdapter);
messageAdapter.notifyDataSetChanged();
recyclerViewUserProfileComments.scrollToPosition(userMessageList.size() - 1);
loadingLayout.setVisibility(View.GONE);
}
});
}
};
thread.start();
}
private void updateCommentSection() {
Thread thread = new Thread() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
recyclerViewUserProfileComments.setVisibility(View.GONE);
textViewUserProfileNoComments.setVisibility(View.VISIBLE);
loadingLayout.setVisibility(View.GONE);
}
});
}
};
thread.start();
}
}

Layouts:

-chat_message_received:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
xmlns:tools=&quot;http://schemas.android.com/tools&quot;
android:id=&quot;@+id/linearLayoutChatParent&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;wrap_content&quot;
android:layout_marginStart=&quot;16dp&quot;
android:layout_marginTop=&quot;6dp&quot;
android:layout_marginEnd=&quot;16dp&quot;
android:layout_marginBottom=&quot;6dp&quot;
android:orientation=&quot;horizontal&quot;&gt;
&lt;ImageView
android:id=&quot;@+id/imageViewChatUserProfile&quot;
android:layout_width=&quot;50sp&quot;
android:layout_height=&quot;50sp&quot;
android:layout_marginEnd=&quot;5dp&quot;
android:background=&quot;@drawable/circle&quot;
android:padding=&quot;5dp&quot;
app:layout_constraintStart_toStartOf=&quot;parent&quot;
app:layout_constraintTop_toTopOf=&quot;parent&quot;
app:srcCompat=&quot;@drawable/ic_person_blue&quot; /&gt;
&lt;androidx.constraintlayout.widget.ConstraintLayout
android:id=&quot;@+id/constraintLayoutMessageItem&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:background=&quot;@drawable/message_received_background&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot;
app:layout_constraintStart_toStartOf=&quot;parent&quot;
app:layout_constraintTop_toTopOf=&quot;parent&quot;&gt;
&lt;TextView
android:id=&quot;@+id/textViewChatName&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:layout_marginStart=&quot;8dp&quot;
android:layout_marginTop=&quot;8dp&quot;
android:fontFamily=&quot;@font/among_us_font&quot;
android:padding=&quot;5dp&quot;
android:textAppearance=&quot;?attr/textAppearanceListItem&quot;
android:textColor=&quot;@android:color/black&quot;
android:textStyle=&quot;bold&quot;
app:layout_constraintBottom_toTopOf=&quot;@+id/textViewChatMessage&quot;
app:layout_constraintStart_toStartOf=&quot;parent&quot;
app:layout_constraintTop_toTopOf=&quot;parent&quot;
tools:text=&quot;Administrator&quot; /&gt;
&lt;TextView
android:id=&quot;@+id/textViewChatMessage&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:layout_marginEnd=&quot;4dp&quot;
android:layout_marginBottom=&quot;8dp&quot;
android:fontFamily=&quot;@font/among_us_font&quot;
android:padding=&quot;5dp&quot;
android:textAppearance=&quot;?attr/textAppearanceListItem&quot;
android:textColor=&quot;@android:color/black&quot;
app:layout_constrainedWidth=&quot;true&quot;
app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
app:layout_constraintEnd_toStartOf=&quot;@+id/textViewChatMessageDate&quot;
app:layout_constraintStart_toStartOf=&quot;@+id/textViewChatName&quot;
app:layout_constraintTop_toBottomOf=&quot;@+id/textViewChatName&quot;
tools:text=&quot;This is a test message This is a test This is a test message&quot; /&gt;
&lt;TextView
android:id=&quot;@+id/textViewChatMessageDate&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:layout_marginEnd=&quot;8dp&quot;
android:fontFamily=&quot;@font/among_us_font&quot;
app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot;
app:layout_constraintTop_toTopOf=&quot;parent&quot;
tools:text=&quot;12:20&quot; /&gt;
&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;
&lt;/LinearLayout&gt;

-chat_message_sent:

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;androidx.constraintlayout.widget.ConstraintLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
xmlns:tools=&quot;http://schemas.android.com/tools&quot;
android:id=&quot;@+id/constraintLayoutMessageSent&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;wrap_content&quot;
android:layout_marginStart=&quot;16dp&quot;
android:layout_marginTop=&quot;8dp&quot;
android:layout_marginEnd=&quot;16dp&quot;
android:layout_marginBottom=&quot;8dp&quot;&gt;
&lt;androidx.constraintlayout.widget.ConstraintLayout
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:background=&quot;@drawable/message_sent_background&quot;
android:fontFamily=&quot;@font/among_us_font&quot;
app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot;
app:layout_constraintTop_toTopOf=&quot;parent&quot;&gt;
&lt;TextView
android:id=&quot;@+id/textViewChatMessage&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:layout_marginStart=&quot;8dp&quot;
android:layout_marginTop=&quot;8dp&quot;
android:layout_marginEnd=&quot;4dp&quot;
android:layout_marginBottom=&quot;8dp&quot;
android:fontFamily=&quot;@font/among_us_font&quot;
android:padding=&quot;5dp&quot;
android:textAppearance=&quot;?attr/textAppearanceListItem&quot;
android:textColor=&quot;@android:color/black&quot;
app:layout_constrainedWidth=&quot;true&quot;
app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
app:layout_constraintEnd_toStartOf=&quot;@+id/textViewChatMessageDate&quot;
app:layout_constraintStart_toStartOf=&quot;parent&quot;
app:layout_constraintTop_toTopOf=&quot;parent&quot;
tools:text=&quot;Test message sent!&quot; /&gt;
&lt;TextView
android:id=&quot;@+id/textViewChatMessageDate&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:layout_marginEnd=&quot;4dp&quot;
android:fontFamily=&quot;@font/among_us_font&quot;
app:layout_constraintBottom_toBottomOf=&quot;@+id/imageViewChatMessageStatus&quot;
app:layout_constraintEnd_toStartOf=&quot;@+id/imageViewChatMessageStatus&quot;
app:layout_constraintStart_toEndOf=&quot;@+id/textViewChatMessage&quot;
app:layout_constraintTop_toTopOf=&quot;@+id/imageViewChatMessageStatus&quot;
tools:text=&quot;12:02&quot; /&gt;
&lt;ImageView
android:id=&quot;@+id/imageViewChatMessageStatus&quot;
android:layout_width=&quot;18sp&quot;
android:layout_height=&quot;18sp&quot;
android:layout_marginTop=&quot;8dp&quot;
android:layout_marginEnd=&quot;8dp&quot;
android:layout_marginBottom=&quot;8dp&quot;
app:layout_constraintBottom_toBottomOf=&quot;parent&quot;
app:layout_constraintEnd_toEndOf=&quot;parent&quot;
app:layout_constraintTop_toTopOf=&quot;parent&quot;
app:srcCompat=&quot;@drawable/ic_message_waiting&quot; /&gt;
&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;
&lt;/androidx.constraintlayout.widget.ConstraintLayout&gt;

-UserComments Layout:

Code Link

Why is doing that to me? I can't even see the messages.

UPDATE

The problem was the android:textAppearance="?attr/textAppearanceListItem" property in message layouts. I have just removed that and It's working fine.

答案1

得分: 2

可能有两件事情..

1. android:textAppearance="attr/textAppearanceListItem"

2. 字体

尝试移除这些.. 希望这能解决问题。

英文:

There might be 2 things..

1. android:textAppearance="?attr/textAppearanceListItem"

2. fonts

try removing these.. Hope this will solve the issue.

huangapple
  • 本文由 发表于 2020年10月26日 22:27:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/64539081.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定