Android聊天应用:优化UI交互与错误处理
Android聊天应用:优化UI交互与错误处理
本文提供了一个优化的Android聊天应用代码示例,包含以下功能:
- 错误处理: 在网络请求或数据解析过程中,如果出现错误,会显示相应的错误提示。* 加载提示: 在发送网络请求时,会显示一个进度条,提示用户正在加载数据。* UI交互优化: 发送消息后,会清空输入框,并将聊天记录滚动到最新的位置。
以下是完整的代码:
**Java代码 (ChatActivity.java):**javapackage com.example.pg_helper;
import android.os.AsyncTask;import android.os.Bundle;import android.view.View;import android.widget.EditText;import android.widget.ProgressBar;import android.widget.TextView;import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONException;import org.json.JSONObject;
import java.io.BufferedReader;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLEncoder;
public class ChatActivity extends AppCompatActivity {
private EditText inputEditText; private TextView chatTextView; private ProgressBar progressBar;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat);
inputEditText = findViewById(R.id.inputEditText); chatTextView = findViewById(R.id.chatTextView); progressBar = findViewById(R.id.progressBar); }
public void onSendClick(View view) { String message = inputEditText.getText().toString().trim(); if (!message.isEmpty()) { // 显示加载提示 progressBar.setVisibility(View.VISIBLE); // 异步发送请求给API,并处理响应 new ChatRequestTask().execute(message); } }
private class ChatRequestTask extends AsyncTask<String, Void, String> {
@Override protected String doInBackground(String... params) { String message = params[0]; try { // 构建API请求URL String url = 'http://api.qingyunke.com/api.php?key=free&appid=0&msg=' + URLEncoder.encode(message, 'UTF-8');
// 发送GET请求给API,并获取响应 HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod('GET');
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } reader.close();
return response.toString(); } catch (Exception e) { e.printStackTrace(); } return null; }
@Override protected void onPostExecute(String response) { // 隐藏加载提示 progressBar.setVisibility(View.GONE); if (response != null) { try { // 解析API响应 JSONObject jsonObject = new JSONObject(response); String reply = jsonObject.getString('content'); chatTextView.append('Bot: ' + reply + '
'); // 清空输入框 inputEditText.setText(''); // 滚动到最新的聊天记录 chatTextView.post(new Runnable() { @Override public void run() { chatTextView.scrollTo(0, chatTextView.getBottom()); } }); } catch (JSONException e) { e.printStackTrace(); // 显示错误提示 Toast.makeText(ChatActivity.this, 'Failed to parse response', Toast.LENGTH_SHORT).show(); } } else { // 显示错误提示 Toast.makeText(ChatActivity.this, 'Failed to get response', Toast.LENGTH_SHORT).show(); } } }}
**XML代码 (activity_chat.xml):**xml
<ScrollView android:layout_width='match_parent' android:layout_height='match_parent' android:layout_above='@+id/inputLayout'>
<TextView android:id='@+id/chatTextView' android:layout_width='match_parent' android:layout_height='wrap_content' android:textSize='16sp' /> </ScrollView>
<LinearLayout android:id='@+id/inputLayout' android:layout_width='match_parent' android:layout_height='wrap_content' android:layout_alignParentBottom='true' android:orientation='horizontal'>
<EditText android:id='@+id/inputEditText' android:layout_width='0dp' android:layout_height='50dp' android:layout_weight='1' android:hint='Type a message' />
<Button android:layout_width='wrap_content' android:layout_height='wrap_content' android:text='Send' android:onClick='onSendClick' /> </LinearLayout>
<ProgressBar android:id='@+id/progressBar' android:layout_width='wrap_content' android:layout_height='wrap_content' android:layout_centerInParent='true' android:visibility='gone' />
这段代码创建了一个简单的聊天应用界面,用户可以在其中输入消息并发送,应用会将消息发送到API,并显示API返回的回复。同时,应用还提供了一些友好的UI交互,例如加载提示和自动滚动聊天记录。
原文地址: https://www.cveoy.top/t/topic/cv1B 著作权归作者所有。请勿转载和采集!