1

我正在使用线程(runOnUiThread)将 imageView 添加到 mainActivity。
我不知道我应该将什么导入构造函数!它需要上下文,我尝试过,MainActivity.this但它不起作用!getApplicationContext()getBaseContext()

public void addImageView(final int belowId,final int id){
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            RelativeLayout rSub= (RelativeLayout) findViewById(R.id.rSub);
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);
            lp.addRule(RelativeLayout.BELOW, belowId);
            lp.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
            ImageView iv = new ImageView(?????);
            iv.setImageResource(R.drawable.ic_launcher);
            iv.setId(id);
            rSub.addView(iv, lp);   
        }
    });
}

并称之为:

new Thread(new Runnable() {
    @Override
    public void run() {
        addImageView(belowId, tempId);
     }
}).start();

任何帮助表示赞赏!

4

1 回答 1

2

我假设您的addImageView方法不在 Activity 类中..也许在自定义视图中..(但这是我的假设)

因此,如果它是您实现addImageView方法的另一个类(不是 Activity 类),那么:

活动类:

MyCustomComponent component = new MyCustomComponent(this);

MyCustomComponent 类:

private Context context;

public MyCustomComponent(Context context){
  this.context = context;
}

public void addImageView(final int belowId,final int id){
    ((Activity)this.context).runOnUiThread(new Runnable() {
       ....
    }
}

如果您从 Activity 运行您的方法,请使用:(您可以在此处查看示例)

MainActivity.this.runOnUiThread(new Runnable() {...});
于 2013-08-02T13:39:11.720 回答