非活动类中的findViewById [英] findViewById in non activity class
问题描述
我知道StackOverFlow中有一些主题在问这个问题,但是所有这些问题在特殊情况下都没有人回答.
谁能说出如何在非活动类中使用findViewById?
以我的情况为例,我想定义一个网络视图:
I know there are some topics in StackOverFlow asking this But all of them are answering in special cases No one answers this question generally.
Can anyone say how to use findViewById in non activity classes?
For Example in my case I want to define a webview:
WebView view=(WebView)findViewById(R.id.webview);
但是我不能,我真的不明白为什么android使一切变得复杂.为什么你可以在main活动中使用所有东西,但不能在非活动类中使用很多:(
更新
我无法扩展班级,因为活动导致其他方面的扩展.
更新
这是课程:
But I can't and I really don't understand why android makes everything complicated.Why you can use everything in main activity but you can't use many of them in non activity class :(
UPDATE
I can't extend my class as activity cause it extends sth else.
UPDATE
This is the class:
class DownloadTask extends AsyncTask<String, Void, Void> {
protected Void doInBackground(String... sUrl) {
...
WebView view=(WebView)findViewById(R.id.webview);
final Snackbar snackbar = Snackbar.make(view,"message",Snackbar.LENGTH_LONG);
...
}
}
我将在Snackbar中使用Webview.
I'm gonna use the webview in a Snackbar.
推荐答案
谁能说出如何在非活动类中使用findViewById?
Can anyone say how to use findViewById in non activity classes?
将活动传递到您要在非活动类上调用的方法.
Pass the activity into the method you are calling on the non-activity class.
或者,将活动传递到非活动类的构造函数中.
Or, pass the activity into the constructor of the non-activity class.
或者,在活动中调用findViewById()
并将WebView
传递给非活动类.
Or, call findViewById()
in the activity and pass the WebView
to the non-activity class.
存在许多其他模式.您需要注意,不要尝试使用该活动,或者不要长时间使用WebView
(例如,在用户旋转屏幕,按BACK或以其他方式导致活动被破坏之后).
Plenty of other patterns exist. You need to be careful that you do not try using the activity or WebView
longer than you should (e.g., after the user rotates the screen, presses BACK, or otherwise causes the activity to be destroyed).
我要在Snackbar中使用Webview.
I'm gonna use the webview in a Snackbar.
使用Snackbar
很好.除非非常小心地使用AsyncTask
中的一个.特别是:
Using a Snackbar
is fine. Using one from an AsyncTask
is not, unless you do so very carefully. In particular:
-
仅尝试从主应用程序线程(即不是
doInBackground()
)执行此操作
确保正确处理配置更改,BACK按下等操作.特别是,您不能在被破坏的活动上显示Snackbar
Make sure that you are handling configuration changes, BACK presses, and the like properly. In particular, you cannot show a Snackbar
on a destroyed activity
这篇关于非活动类中的findViewById的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!