到目前的文章為止我們針對後端的部分進行很多測試了,接下來就讓我們回到前端雨後端進行對接,並且測試效果吧!
本次的設計會是以聊天室為主題進行設計,大概功能就是用戶說一句,AI說一句,達到來回的對話的效果
對話的部分會使用RecyclerView來做,透過綁定不同布局就可以做到快速切換對話內容的效果
添加網路權限,並且指定 networkSecurityConfig
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:networkSecurityConfig="@xml/network_security_config">
</application>
networkSecurityConfig 的設定就跟前面 [Day9] 的文章設定方式一樣
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/chatRecyclerView"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toTopOf="@+id/inputLayout"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:id="@+id/inputLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="16dp"
app:layout_constraintBottom_toBottomOf="parent">
<EditText
android:id="@+id/messageEditText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="輸入訊息" />
<Button
android:id="@+id/sendButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="發送" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
API的設定這次的架構如下
public class SemanticKernelApiClient {
private static final String BASE_URL = "http://自己的IP:8080/semantic-kernel/demo/";
private static SemanticKernelApiClient instance = new SemanticKernelApiClient();
private SemanticKernelApiService apiService;
private SemanticKernelApiClient() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addCallAdapterFactory(RxJava3CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
apiService = retrofit.create(SemanticKernelApiService.class);
}
public SemanticKernelApiService getApiService() {
return apiService;
}
public static SemanticKernelApiClient getApiInstance() {
return instance;
}
}
public interface SemanticKernelApiService {
@POST("lights")
Observable<SemanticKernelResponse> getSemanticKernel(@Body SemanticKernelRequest request);
}
public class SemanticKernelRequest {
private String input;
public SemanticKernelRequest(String input) {
this.input = input;
}
}
public class SemanticKernelResponse {
private String message;
public SemanticKernelResponse(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
接著要來新增跟 Adapter 相關的設定
這裡我們規定了Adapter 資料的格式
public class ChatMessage {
public String text;
public boolean isUser;
public ChatMessage(String text, boolean isUser) {
this.text = text;
this.isUser = isUser;
}
}
這次用到比較特別的方式自動切換回文的元件,這是因為我想要做到 User的輸入內容靠右,AI 的回文內容靠左的效果,因此選擇使用不同 ViewHolder 搭配到 ItemViewType 以及 OnBindViewHolder 來幫我自動切會現在要使用的元件
public class ChatAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private List<ChatMessage> messages;
private static final int VIEW_TYPE_USER = 0;
private static final int VIEW_TYPE_GPT = 1;
public ChatAdapter(List<ChatMessage> messages) {
this.messages = messages;
}
@Override
public int getItemViewType(int position) {
ChatMessage message = messages.get(position);
if (message.isUser) {
return VIEW_TYPE_USER;
} else {
return VIEW_TYPE_GPT;
}
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view;
switch (viewType) {
case VIEW_TYPE_USER:
view = inflater.inflate(R.layout.user_message_item, parent, false);
return new UserMessageViewHolder(view);
case VIEW_TYPE_GPT:
view = inflater.inflate(R.layout.gpt_message_item, parent, false);
return new GPTMessageViewHolder(view);
default:
throw new IllegalArgumentException("Invalid viewType");
}
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
ChatMessage message = messages.get(position);
if (holder instanceof UserMessageViewHolder) {
((UserMessageViewHolder) holder).messageTextView.setText(message.text);
} else if (holder instanceof GPTMessageViewHolder) {
((GPTMessageViewHolder) holder).messageTextView.setText(message.text);
}
}
@Override
public int getItemCount() {
return messages.size();
}
public void addMessage(ChatMessage message) {
messages.add(message);
notifyItemInserted(messages.size() - 1);
}
public class UserMessageViewHolder extends RecyclerView.ViewHolder {
TextView messageTextView;
public UserMessageViewHolder(@NonNull View itemView) {
super(itemView);
messageTextView = itemView.findViewById(R.id.user_message_textView);
}
}
public class GPTMessageViewHolder extends RecyclerView.ViewHolder {
TextView messageTextView;
public GPTMessageViewHolder(@NonNull View itemView) {
super(itemView);
messageTextView = itemView.findViewById(R.id.gpt_message_textView);
}
}
}
這次會使用到兩個 Item 的布局,一個是使用者使用的 user_message_item,另一個是 AI 使用到的 gpt_message_item
設定 user 的布局會靠右
<?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"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:gravity="end"
android:orientation="horizontal">
<TextView
android:layout_width="70dp"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="20sp"
android:textColor="#9C27B0"
android:text="USER" />
<TextView
android:id="@+id/user_message_textView"
android:layout_width="230dp"
android:layout_height="wrap_content"
android:textSize="15sp"
android:textColor="@color/black"
android:text="" />
</LinearLayout>
AI 的則會靠左
<?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"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:gravity="start"
android:orientation="horizontal">
<TextView
android:layout_width="70dp"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="20sp"
android:textColor="#4CAF50"
android:text="GPT" />
<TextView
android:id="@+id/gpt_message_textView"
android:layout_width="230dp"
android:layout_height="wrap_content"
android:textSize="15sp"
android:textColor="@color/black"
android:text="" />
</LinearLayout>
到此基本上準備工作都結束了,接著就進到 MainActivity 的部分
在這裡其實設定的東西也不多,因為最重要的 AI 回覆的內容是交給 後端 去處理,前端負責接訊息而已
public class MainActivity extends AppCompatActivity {
private List<ChatMessage> messages = new ArrayList<>();
private ChatAdapter chatAdapter;
private EditText messageEditText;
private Button sendButton;
private RecyclerView chatRecyclerView;
private SemanticKernelApiClient apiClient = SemanticKernelApiClient.getApiInstance();
private SemanticKernelApiService apiService = apiClient.getApiService();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindUI();
setRecyclerView();
setButtonClickListener();
}
private void setRecyclerView() {
chatAdapter = new ChatAdapter(messages);
chatRecyclerView.setLayoutManager(new LinearLayoutManager(this));
chatRecyclerView.setAdapter(chatAdapter);
}
private void setButtonClickListener() {
sendButton.setOnClickListener(v -> {
String message = messageEditText.getText().toString();
sendMessage(message);
});
}
private void bindUI() {
messageEditText = findViewById(R.id.messageEditText);
sendButton = findViewById(R.id.sendButton);
chatRecyclerView = findViewById(R.id.chatRecyclerView);
}
private void sendMessage(String message) {
chatAdapter.addMessage(new ChatMessage(message, true));
getSemanticKernelResponse(message);
}
private void getSemanticKernelResponse(String message) {
SemanticKernelRequest request = new SemanticKernelRequest(message);
apiService.getSemanticKernel(request)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new DisposableObserver<SemanticKernelResponse>() {
@Override
public void onNext(SemanticKernelResponse response) {
Log.e("MainActivity", "onNext: " + response.getMessage());
receiveMessage(response.getMessage());
}
@Override
public void onError(Throwable e) {
Log.e("MainActivity", "onError: " + e.getMessage());
}
@Override
public void onComplete() {
}
});
}
private void receiveMessage(String message) {
chatAdapter.addMessage(new ChatMessage(message, false));
}
}