Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

android - findViewById in non activity class

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

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

I'm gonna use the webview in a Snackbar.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Or, call findViewById() in the activity and pass the WebView to the non-activity class.

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).

I'm gonna use the webview in a Snackbar.

Using a Snackbar is fine. Using one from an AsyncTask is not, unless you do so very carefully. In particular:

  • Only try doing this from the main application thread (i.e., not doInBackground())

  • 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...