补全上面代码的xml代码和activity
时间: 2023-11-24 13:08:21 浏览: 28
XML代码:
```
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/editText"
android:divider="@null"
android:dividerHeight="0dp"
android:stackFromBottom="true" />
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:hint="Type message here"
android:inputType="text" />
</RelativeLayout>
```
Activity代码:
```
public class MainActivity extends AppCompatActivity {
private ListView listView;
private EditText editText;
private ChatAdapter chatAdapter;
private List<Message> messageList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.listView);
editText = findViewById(R.id.editText);
messageList = new ArrayList<>();
chatAdapter = new ChatAdapter(this, messageList);
listView.setAdapter(chatAdapter);
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
if (i == EditorInfo.IME_ACTION_SEND) {
String message = editText.getText().toString();
if (!message.isEmpty()) {
sendMessage(message);
editText.setText("");
}
return true;
}
return false;
}
});
}
private void sendMessage(String message) {
messageList.add(new Message(message, true));
chatAdapter.notifyDataSetChanged();
// AI回复逻辑
String reply = ChitGPT.getReply(message);
messageList.add(new Message(reply, false));
chatAdapter.notifyDataSetChanged();
// 滚动到最后一条消息
listView.smoothScrollToPosition(messageList.size() - 1);
}
}
```