0

我的代码有错误的问题,

public class MainActivity2 extends Activity {

EditText et;
ImageView iv;
Runnable stream;
Handler hand = new Handler();
    Runnable run ;
    public Button tombol2;
@SuppressLint("NewApi")
@Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main2);
 Intent intent = getIntent();
     String url= intent.getStringExtra("URL");
tombol2 = (Button) findViewById(R.id.button2);

iv = (ImageView) findViewById(R.id.imageView1);
Drawable d1=LoadImageFromWebOperations(url);
iv.setImageDrawable(d1);
    Handler handler = new Handler();
     handler.postDelayed(new Runnable() {
     @Override
public void run() {
        // TODO Auto-generated method stub
        iv.setImageDrawable(d1);
        }
    }, 10000);
}
    private Drawable LoadImageFromWebOperations(String url)
{
     try
     {
         InputStream is = (InputStream) new URL(url).getContent();
         Drawable d = Drawable.createFromStream(is, "src name");
         return d;
     }catch (Exception e) {
         System.out.println("Exc="+e);
         return null;
     }  
}

}

使用 runnable 和处理程序函数后,我在应用程序中看不到图像,我在 void 运行时出现错误,iv.setImageDrawable(d1);如何解决?显示并运行该图像

4

1 回答 1

1

首先,您的函数确实获得了可绘制对象,应该如下所示:

private Drawable LoadImageFromWebOperations(String url)
{
    Drawable drawable = null;

    try {
        InputStream inputStream = new URL(url).openStream();
        drawable = Drawable.createFromStream(inputStream, null);
        inputStream.close();
    }
    catch(Exception ex) {
        System.out.println("Exc=" + e);
        return null;
    }

    return drawable;
}

现在我不明白 Handler 的使用......如果你希望图像在 10 秒的活动创建后出现,那么使用这个:

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        ImageView iv = (ImageView) MainActivity2.this.findViewById(R.id.imageView1);
        Drawable d1 = LoadImageFromWebOperations(url);
        iv.setImageDrawable(d1);
    }
}, 10000);

如果不只是使用 post() 而不是 postDelayed()。

于 2013-08-29T01:01:57.373 回答