Alex M
Alex M

Reputation: 21

Android - How do I change this findViewById to work?

Image Link

I'm trying to open a webpage through an app and this seems to be the problem.

myWebView = (WebView) findViewById(R.id.webView);

I'm not sure what to change here.

Upvotes: 2

Views: 176

Answers (2)

Sagar
Sagar

Reputation: 24907

Its just a warning and your execution shouldn't be blocked.

Starting with SDK 26, findViewById returns Generic type (<T extends View> T findViewById(int id)) hence the type cast using (WebView) is redundant.

Instead of

myWebView = (WebView) findViewById(R.id.webView);

Use

myWebView = findViewById(R.id.webView);

You can also remove it for FloatingActionButton as follows:

FloatingActionButton fab = findViewById(R.id.fab);

Note: Clean and rebuild once you have done the changes. The compiler error is not due to this warning.

Upvotes: 4

Vikasdeep Singh
Vikasdeep Singh

Reputation: 21756

It was just lint warning that you don't need to cast this to WebView. If you will not do anything, it will work but if you want to avoid this warning do like below:

Current:

myWebView = (WebView) findViewById(R.id.webView);

Change to:

myWebView = findViewById(R.id.webView);

Extra Tip:

Just noticed in the screenshot you attached that same thing you need to change in case of Toolbar and FloatingActionButton as well.

Remove casting (Toolbar) and (FloatingActionButton).

For more information about this type casting warning check this article.


Compile time error:

Above changes are not related to compilation error.

To fix the compilation error, try by File > Invalid Caches/Restart

Screenshot for Invalid Caches/Restart: enter image description here

Upvotes: 3

Related Questions