从URL获取文本并将其放入TextView可以通过以下步骤实现:
<uses-permission android:name="android.permission.INTERNET" />
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
private class DownloadTextTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
reader.close();
inputStream.close();
connection.disconnect();
return stringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
protected void onPostExecute(String result) {
if (result != null) {
TextView textView = findViewById(R.id.textView);
textView.setText(result);
}
}
}
String url = "https://example.com/text.txt";
DownloadTextTask task = new DownloadTextTask();
task.execute(url);
以上代码将从指定的URL获取文本,并在获取成功后将其设置到TextView组件中显示。
推荐的腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云