获取imageView的主要活动上下文

时间:2013-08-02 13:33:23

标签: java android multithreading uiimageview

我正在使用线程(runOnUiThread)将imageView添加到mainActivity 我不知道我应该导入什么构造函数!它需要上下文,我尝试MainActivity.thisgetApplicationContext()以及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();

任何帮助表示赞赏!

1 个答案:

答案 0 :(得分: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中运行方法,请使用:(您可以看到示例here

MainActivity.this.runOnUiThread(new Runnable() {...});