[英]get main activity context for imageView
我正在使用线程(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();
任何帮助表示赞赏!
我假设您的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() {...});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.