我制作了一个简单的聊天应用程序,在我的聊天片段中,EditText(用户输入)返回“”(空字符串)。我在按钮单击时调用它,因此在用户输入值方案之前无法进行任何访问。请查看我的代码,并告诉我我做错了什么。
EditText newMessage;
TextView message;
Button send;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_private_chat, container, false);
message = (TextView) view.findViewById(R.id.tv_private_chat);
newMessage =(EditText) view.findViewById(R.id.edit_private_chat);
send = view.findViewById(R.id.btn_private_chat);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String message=newMessage.getText().toString();//here the value of message remains empty
send("message : "+message);//this method sends data to socket
}
});
return view;
}
这是xml文件。
<?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"
android:background="@color/cardview_light_background"
tools:context=".PrivateChatFragment">
<TextView
android:id="@+id/tv_private_chat"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_margin="6dp"
app:layout_constraintBottom_toTopOf="@+id/edit_private_chat"
android:textColor="@color/colorBlack"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
<EditText
android:id="@+id/edit_private_chat"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:textColor="@color/colorBlack"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="@+id/btn_private_chat"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="@+id/btn_private_chat"
android:layout_width="50dp"
android:layout_height="42dp"
android:layout_margin="8dp"
android:background="@drawable/ic_send_black_24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</android.support.constraint.ConstraintLayout>