1

I'm using thread (runOnUiThread) for adding imageView to mainActivity.
i don't know what should i import to constructor! It want context and i tried MainActivity.this and getApplicationContext() and getBaseContext() but it doesn't work!

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);   
        }
    });
}

and call it :

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

any help appreciated!

1 Answers1

2

I assume your addImageView method is not in Activity class.. Maybe in custom view.. (but that is my assumption)

So, if it is another class (not Activity class) where you implement your addImageView method, then:

Activity class:

MyCustomComponent component = new MyCustomComponent(this);

MyCustomComponent class:

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() {
       ....
    }
}

In case if you are running your method from the Activity, then use: (you can see an example here)

MainActivity.this.runOnUiThread(new Runnable() {...});
Community
  • 1
  • 1
Boris Mocialov
  • 3,439
  • 2
  • 28
  • 55