gpt4 book ai didi

java - 在 Android 中使用线程时出现错误

转载 作者:行者123 更新时间:2023-12-01 15:25:20 24 4
gpt4 key购买 nike

I create a simple Project to load all images in drawable

这是我的代码

public void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list = (ImageView)findViewById(R.id.tung);
ct = getApplicationContext();
try
{
IDs = getAllResourceIDs(R.drawable.class);
n= IDs.length;
dem=0;
list.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
++dem;
list.setImageResource(IDs[dem]);
if(dem==n-1)
dem=0;
}
});

Thread x = new Thread(
new Runnable ()
{
public void run()
{
while(true)
{
try
{
++dem;
//Toast.makeText(ct, ""+dem, 20).show();
list.setImageResource(IDs[dem]);
if(dem==n-1)
dem=0;
}
catch(Exception e)
{
//Toast.makeText(ct,e.toString(), 200).show();
}
}
}
}
);
x.start();
}
catch(Exception e)
{
Toast.makeText(this,e.toString(), 200).show();
}
}

anh 这里是 getAllResourceIDs 函数来获取所有 id

private int[] getAllResourceIDs(Class<?> aClass) throws IllegalArgumentException{
/* Get all Fields from the class passed. */
Field[] IDFields = aClass.getFields();

/* int-Array capable of storing all ids. */
int[] IDs = new int[IDFields.length];

try {
/* Loop through all Fields and store id to array. */
for(int i = 0; i < IDFields.length; i++){
/* All fields within the subclasses of R
* are Integers, so we need no type-check here. */

// pass 'null' because class is static
IDs[i] = IDFields[i].getInt(null);
}
} catch (Exception e) {
/* Exception will only occur on bad class submitted. */
throw new IllegalArgumentException();
}
return IDs;

文件 main.xml 只有一个 id = "tung"的 ImageView我尝试使用名为 x 的 Thead 加载所有图像通过使用代码list.setImageResource(IDs[dem]);正如你在我的代码中看到的但什么也没发生你能给我解释一下吗!非常感谢!

最佳答案

对于初学者来说,catch (Exception e) 几乎从来都不是一个好主意,因为它隐藏了发生错误时可以获得的所有有意义的信息。

您的错误特别出现在后台线程中的这一行:

list.setImageResource(IDs[dem]);

后台线程不允许操作 UI 对象。相反,您需要使用 AsyncTask (更简单)或 Handler (高级)

关于java - 在 Android 中使用线程时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10250372/

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