Android - RecyclerViewer无法填充数据

时间:2018-04-12 22:26:06

标签: android android-recyclerview

我对Android开发很陌生,而且我试图通过让这个工作混淆我的方式。

我尝试搜索网页,但我发现的提示专注于确保你的getItemCount不返回0,这不是,并确保我将适配器连接到RecyclerView,我相信我有。

我希望我只是遗漏了一些愚蠢的东西,这将是一个快速解决方案,提前感谢任何回复(如果您需要更多信息,请告诉我)!

适配器:

public class MessageListAdapter extends RecyclerView.Adapter {
private static final int VIEW_TYPE_MESSAGE_SENT = 1;
private static final int VIEW_TYPE_MESSAGE_RECEIVED = 2;

private Context mContext;
private List<SocketMessage> mMessageList;
private String username;

public MessageListAdapter(Context context, List<SocketMessage> messageList, String username) {
    mContext = context;
    mMessageList = messageList;
    this.username = username;
}

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

// Determines the appropriate ViewType according to the sender of the message.
@Override
public int getItemViewType(int position) {
    SocketMessage message = (SocketMessage) mMessageList.get(position);

    if (message.Username.contentEquals(this.username)) {
        // If the current user is the sender of the message
        return VIEW_TYPE_MESSAGE_SENT;
    } else {
        // If some other user sent the message
        return VIEW_TYPE_MESSAGE_RECEIVED;
    }
}

// Inflates the appropriate layout according to the ViewType.
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view;

    if (viewType == VIEW_TYPE_MESSAGE_SENT) {
        view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_message_sent, parent, false);
        return new SentMessageHolder(view);
    } else if (viewType == VIEW_TYPE_MESSAGE_RECEIVED) {
        view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_message_received, parent, false);
        return new ReceivedMessageHolder(view);
    }

    return null;
}

// Passes the message object to a ViewHolder so that the contents can be bound to UI.
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
    SocketMessage message = (SocketMessage) mMessageList.get(position);

    switch (holder.getItemViewType()) {
        case VIEW_TYPE_MESSAGE_SENT:
            ((SentMessageHolder) holder).bind(message);
            break;
        case VIEW_TYPE_MESSAGE_RECEIVED:
            ((ReceivedMessageHolder) holder).bind(message);
    }
}

public void add(SocketMessage socketMessage) {
    mMessageList.add(socketMessage);
    notifyDataSetChanged();
}

class MessageViewHolder {
    public TextView name;
    public TextView messageBody;
}

class ReceivedMessageHolder extends RecyclerView.ViewHolder {
    TextView messageText, timeText, nameText;

    ReceivedMessageHolder(View itemView) {
        super(itemView);
        messageText = (TextView) itemView.findViewById(R.id.text_message_body);
        nameText = (TextView) itemView.findViewById(R.id.text_message_name);
    }

    void bind(SocketMessage message) {
        messageText.setText(message.MessageText);
        // Format the stored timestamp into a readable String using method.
        nameText.setText(message.Username);
    }
}

class SentMessageHolder extends RecyclerView.ViewHolder {
    TextView messageText, timeText;

    SentMessageHolder(View itemView) {
        super(itemView);
        messageText = (TextView) itemView.findViewById(R.id.text_message_body);
    }

    void bind(SocketMessage message) {
        messageText.setText(message.MessageText);
    }
}}

活动OnCreate:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_socket_chat);
    app = (HMCTHubApplication) getApplication();
    socket = app.getSocket();
    setContentView(R.layout.activity_socket_chat);
    mMessageList = new ArrayList<SocketMessage>();
    mMessageAdapter = new MessageListAdapter(this,mMessageList,app.getUsername());
    messagesView = (RecyclerView) findViewById(R.id.reyclerview_message_list);
    messagesView.setAdapter(mMessageAdapter);
    messagesView.setLayoutManager(new LinearLayoutManager(this));

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            mMessageAdapter.add(new SocketMessage("test","this is a test msg"));
        }
    });
    socket.on("receivedMessage",ReceivedMessage);
    Button sendButton = (Button) findViewById(R.id.button_chatbox_send);
    sendButton.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View view){
            EditText input = (EditText)findViewById(R.id.edittext_chatbox);
            final SocketMessage message = new SocketMessage(app.getUsername(),input.getText().toString());
            try{
                socket.emit("ChatMessage", new ObjectMapper().writeValueAsString(message));
                input.setText("");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mMessageAdapter.add(message);
                    }
                });
            }
            catch(Exception ex){
                Log.v("[ChatActivity]", "Fail on send message");
                Log.v("[ChatActivity]",ex.getMessage());
            }
        }
    });
}

活动布局:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="dotsoflight.hmcthub.SocketChatActivity">

<android.support.v7.widget.RecyclerView
    android:id="@+id/reyclerview_message_list"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent">
</android.support.v7.widget.RecyclerView>

<!-- A horizontal line between the chatbox and RecyclerView -->
<View
    android:layout_width="0dp"
    android:layout_height="2dp"
    android:background="#dfdfdf"
    android:layout_marginBottom="0dp"
    app:layout_constraintBottom_toTopOf="@+id/layout_chatbox"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"/>

<LinearLayout
    android:id="@+id/layout_chatbox"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:minHeight="48dp"
    android:background="#ffffff"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintLeft_toLeftOf="parent">

    <EditText
        android:id="@+id/edittext_chatbox"
        android:hint="Enter message"
        android:background="@android:color/transparent"
        android:layout_gravity="center"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:maxLines="6"/>

    <Button
        android:id="@+id/button_chatbox_send"
        android:text="SEND"
        android:textSize="14dp"
        android:background="?attr/selectableItemBackground"
        android:clickable="true"
        android:layout_width="64dp"
        android:layout_height="48dp"
        android:gravity="center"
        android:layout_gravity="bottom" />

</LinearLayout>

</android.support.constraint.ConstraintLayout>

编辑:我不相信this问题是相关的,因为我从一个活动而不是一个片段中调用这个问题,我看了一下答案,但似乎没有一个适用于他们&# #39;重新使用片段。

EDIT2:Levi发现了问题!我必须在设置适配器之前设置LayoutManager,并将以下内容添加到RecyclerView布局的底部:

应用程式:layout_constraintBottom_toBottomOf =&#34;父&#34;

正如我告诉它在不设置底部约束时适合高度约束。

1 个答案:

答案 0 :(得分:0)

在布局管理器之后设置适配器:

messagesView.setLayoutManager(new LinearLayoutManager(this));
messagesView.setAdapter(mMessageAdapter);

修改

回收器视图的底部没有约束,但您将高度设置为匹配约束。在这种情况下,您需要限制顶部和底部:

 app:layout_constraintBottom_toBottomOf="parent"