gpt4 book ai didi

android - 如何从android中的线程设置文本或发送数组列表

转载 作者:行者123 更新时间:2023-11-29 20:46:38 25 4
gpt4 key购买 nike

我正在尝试制作一个新闻板,我已经用谷歌搜索了很多次并尝试使用“Handler”,但总是崩溃

这是原始代码:

public void onViewCreated(final View view, Bundle savedInstanceState) {
final TextView t1 = (TextView) view.findViewById(R.id.txt1);
final TextView t2 = (TextView) view.findViewById(R.id.txt2);
final TextView t3 = (TextView) view.findViewById(R.id.txt3);
new Thread(new Runnable() {
@Override
public void run() {
try {
final ArrayList arrayList = XMLPullParser.parse("http://localhost/news.xml", "news", 1, 2, 3);
System.out.println(arrayList.size() + "return from arraylist");
/*
t1.setText(arrayList.get(0).toString());
t2.setText(arrayList.get(1).toString());
t3.setText(arrayList.get(2).toString());
*/
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}).start();
}

然后我这样编辑:

public void onViewCreated(final View view, Bundle savedInstanceState) {
final Handler handler = new Handler();
final TextView t1 = (TextView) view.findViewById(R.id.txt1);
final TextView t2 = (TextView) view.findViewById(R.id.txt2);
final TextView t3 = (TextView) view.findViewById(R.id.txt3);
new Thread(new Runnable() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
final ArrayList arrayList = XMLPullParser.parse("http://localhost/news.xml", "news", 1, 2, 3);
System.out.println(arrayList.size() + "return from arraylist");
t1.setText(arrayList.get(0).toString());
t2.setText(arrayList.get(1).toString());
t3.setText(arrayList.get(2).toString());
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
});
}
}).start();
}

原代码是susses show arraylist details and String,问题是如何设置Text。

最佳答案

试试这个

   public void onViewCreated(final View view, Bundle savedInstanceState) {
// main thread
final Handler handler = new Handler();
final TextView t1 = (TextView) view.findViewById(R.id.txt1);
final TextView t2 = (TextView) view.findViewById(R.id.txt2);
final TextView t3 = (TextView) view.findViewById(R.id.txt3);
new Thread(new Runnable() {
@Override
public void run() {
// background thread
final ArrayList arrayList = XMLPullParser.parse("http://localhost/news.xml", "news", 1, 2, 3);
System.out.println(arrayList.size() + "return from arraylist");
handler.post(new Runnable() {
public void run() {
try {
// main thread
t1.setText(arrayList.get(0).toString());
t2.setText(arrayList.get(1).toString());
t3.setText(arrayList.get(2).toString());
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
});
}
}).start();
}

为了解释发生了什么,您在主线程中创建了一个 Handler 对象,因为在那里调用了 onCreateView。

然后您创建了另一个网络线程,该线程执行 XML 解析,并使用处理程序将 Runnable 传递给 UI/主线程。

处理程序获取 massage/Runnable,并在主线程(唯一允许接触 UI 的线程)上调用它。

关于android - 如何从android中的线程设置文本或发送数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30225624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com