Java Android应用程序中的RecyclerView适配器存在问题
我的RecyclerView和适配器有问题。RecyclerView中的消息在布局中显示得太小,您可以在图像中看到: MessageAdapter.java:Java Android应用程序中的RecyclerView适配器存在问题,java,android,android-recyclerview,recyclerlistview,Java,Android,Android Recyclerview,Recyclerlistview,我的RecyclerView和适配器有问题。RecyclerView中的消息在布局中显示得太小,您可以在图像中看到: MessageAdapter.java: public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageAdapterViewHolder> { private Context context; private List<Message> me
public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.MessageAdapterViewHolder> {
private Context context;
private List<Message> messages;
public static final int MSG_TYPE_LEFT = 0;
public static final int MSG_TYPE_RIGHT = 1;
public MessageAdapter(Context context, List<Message> 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("username", 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("Messages");
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);
}
}
}
公共类MessageAdapter扩展了RecyclerView.Adapter{
私人语境;
私人列表消息;
公共静态最终int MSG_TYPE_LEFT=0;
公共静态最终int MSG_TYPE_RIGHT=1;
公共消息适配器(上下文、列表消息){
this.context=上下文;
this.messages=消息;
}
@凌驾
public int getItemViewType(int位置){
FirebaseUser FirebaseUser=FirebaseAuth.getInstance().getCurrentUser();
断言firebaseUser!=null;
if(messages.get(position).getName().equals(firebaseUser.getDisplayName())){
返回消息类型右;
}否则{
返回消息类型左;
}
}
@非空
@凌驾
public MessageAdapterViewHolder onCreateViewHolder(@NonNull ViewGroup父级,int viewType){
if(viewType==MSG\u TYPE\u RIGHT){
视图=LayoutFlater.from(context).充气(R.layout.fragment\u chat\u message\u sent,parent,false);
返回新消息AdapterViewer(视图);
}否则{
视图=LayoutFlater.from(context).充气(R.layout.fragment\u chat\u message\u received,parent,false);
返回新消息AdapterViewer(视图);
}
}
@凌驾
public void onBindViewHolder(@NonNull final MessageAdapterViewHolder,final int position){
最终消息=messages.get(位置);
ConstraintLayout constraintLayoutMessageSent;
int viewType=holder.getItemViewType();
if(viewType==MSG\u TYPE\u LEFT){
holder.textViewChatName.setText(message.getName());
holder.textViewChatMessage.setText(message.getMessage());
holder.textViewChatMessageDate.setText(message.getHourminute());
holder.imageViewChatUserProfile.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
意向意向=新意向(上下文,UserProfileActivity.class);
intent.putExtra(“用户名”,message.getName());
背景。开始触觉(意图);
}
});
}否则{
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(新视图。OnLongClickListener(){
@凌驾
仅长按公共布尔值(视图v){
AlertDialog.Builder=新建AlertDialog.Builder(holder.itemView.getContext());
builder.setMessage(R.string.delete_消息)
.setPositiveButton(R.string.yes,新的DialogInterface.OnClickListener(){
@凌驾
公共void onClick(DialogInterface,inti){
删除消息(位置);
}
}).setNegativeButton(R.string.no,新的DialogInterface.OnClickListener(){
@凌驾
public void onClick(DialogInterface,int-which){
dialogInterface.dismise();
}
});
builder.create();
builder.show();
返回false;
}
});
}
}
私有void deleteMessage(int位置){
字符串messageKey=messages.get(position.getKey();
DatabaseReference DatabaseReference=FirebaseDatabase.getInstance().getReference(“消息”);
databaseReference.child(messageKey.removeValue();
}
@凌驾
public int getItemCount(){
返回消息。size();
}
公共静态类MessageAdapterViewHolder扩展了RecyclerView.ViewHolder{
私有文本视图文本视图聊天信息;
私有文本视图文本视图聊天室名称;
私有文本视图文本视图聊天信息日期;
私有ImageView imageViewChatMessageStatus;
私有ImageView imageViewChatUserProfile;
public MessageAdapterViewHolder(@NonNull final View 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 = "";
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("username");
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 = "";
String gender = "";
String profile_picture = "";
Response response = HttpRequests.getUserInformation(username);
String responseBody = Objects.requireNonNull(response.body()).string();
responseBody = responseBody.replace("\r\n", "");
JSONArray responseArray = new JSONArray(responseBody);
for (int i = 0; i < responseArray.length(); i++) {
JSONObject jsonobject = responseArray.getJSONObject(i);
description = jsonobject.getString("description");
gender = jsonobject.getString("gender");
profile_picture = jsonobject.getString("profile_picture");
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<Message> userMessageList = new ArrayList<>();
String name = "";
String comment = "";
Response response = HttpRequests.getUserComments(username);
String responseBody = Objects.requireNonNull(response.body()).string();
responseBody = responseBody.replace("\r\n", "");
JSONArray responseArray = new JSONArray(responseBody);
for (int i = 0; i < responseArray.length(); i++) {
Message message = new Message();
JSONObject jsonobject = responseArray.getJSONObject(i);
name = jsonobject.getString("from_user");
comment = jsonobject.getString("comment");
if (!name.isEmpty() && !comment.isEmpty()) {
message.setName(name);
message.setMessage(comment);
userMessageList.add(message);
}
}
if (userMessageList.size() > 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 + " - " + getString(R.string.user_profile));
textViewUserProfileName.setText(username);
if (description.equals("null")) {
textViewUserProfileDescription.setText("");
} else {
textViewUserProfileDescription.setText(description);
}
loadingLayout.setVisibility(View.GONE);
lottieAnimationViewLoading.cancelAnimation();
}
});
}
};
thread.start();
}
private void updateComments(final List<Message> 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();
}
}
公共类UserProfileActivity扩展了AppCompatActivity{
私人语境;
专用工具栏;
私有字符串用户名=”;
私有ImageView ImageViewUserProfile配置文件;
私有TextView textViewUserProfileName;
私有TextView textViewUserProfileDescription;
私有约束加载布局;
私有LottieAnimationView lottieAnimationViewLoading;
私人RecyclerView recyclerViewUserProfileComments;
私有TextView textViewUserProfileNoComments;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u user\u profile
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:id="@+id/linearLayoutChatParent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="6dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="6dp"
android:orientation="horizontal">
<ImageView
android:id="@+id/imageViewChatUserProfile"
android:layout_width="50sp"
android:layout_height="50sp"
android:layout_marginEnd="5dp"
android:background="@drawable/circle"
android:padding="5dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/ic_person_blue" />
<androidx.constraintlayout.widget.ConstraintLayout
android:id="@+id/constraintLayoutMessageItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/message_received_background"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="@+id/textViewChatName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:fontFamily="@font/among_us_font"
android:padding="5dp"
android:textAppearance="?attr/textAppearanceListItem"
android:textColor="@android:color/black"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="@+id/textViewChatMessage"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="Administrator" />
<TextView
android:id="@+id/textViewChatMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="4dp"
android:layout_marginBottom="8dp"
android:fontFamily="@font/among_us_font"
android:padding="5dp"
android:textAppearance="?attr/textAppearanceListItem"
android:textColor="@android:color/black"
app:layout_constrainedWidth="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/textViewChatMessageDate"
app:layout_constraintStart_toStartOf="@+id/textViewChatName"
app:layout_constraintTop_toBottomOf="@+id/textViewChatName"
tools:text="This is a test message This is a test This is a test message" />
<TextView
android:id="@+id/textViewChatMessageDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:fontFamily="@font/among_us_font"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="12:20" />
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/constraintLayoutMessageSent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="8dp">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/message_sent_background"
android:fontFamily="@font/among_us_font"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="@+id/textViewChatMessage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="4dp"
android:layout_marginBottom="8dp"
android:fontFamily="@font/among_us_font"
android:padding="5dp"
android:textAppearance="?attr/textAppearanceListItem"
android:textColor="@android:color/black"
app:layout_constrainedWidth="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/textViewChatMessageDate"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="Test message sent!" />
<TextView
android:id="@+id/textViewChatMessageDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="4dp"
android:fontFamily="@font/among_us_font"
app:layout_constraintBottom_toBottomOf="@+id/imageViewChatMessageStatus"
app:layout_constraintEnd_toStartOf="@+id/imageViewChatMessageStatus"
app:layout_constraintStart_toEndOf="@+id/textViewChatMessage"
app:layout_constraintTop_toTopOf="@+id/imageViewChatMessageStatus"
tools:text="12:02" />
<ImageView
android:id="@+id/imageViewChatMessageStatus"
android:layout_width="18sp"
android:layout_height="18sp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/ic_message_waiting" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>