Search code examples
androidandroid-studior.java-file

How to properly create a particular R.id in Android Studio?


I'm trying to learn Android / Android Studio. I'm working on an app that is basically a very simple web browser set to start at google.com.

The project can't find the symbol variable webview and I'm not sure how to properly create it.

package obfuscated.obfuscated;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebSettings;
import android.webkit.WebViewClient;

public class WebViewActivity extends Activity {

    private static final String URL = "http://www.google.com";

    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_web_view);

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

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);

        webView.loadUrl(URL);
        webView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url){
                webView.loadUrl(url);
                return false;
            }
        });
    }
}

The particular problem line is webView = (WebView) findViewById(R.id.webview);

How can I create this resource properly? I understand that R is generated so I am curious how to do that in Android Studio.

I don't know if it matters, but the above onCreate method is taken from a previously working Eclipse project.


Solution

  • How can I create this resource properly?

    There should be a <WebView> element in your layout (presumably located in res/layout/activity_web_view) whose android:id value is @+id/webview.

    I understand that R is generated so I am curious how to do that in Android Studio.

    The same way that you would in Eclipse, IntelliJ IDEA, NetBeans, AIDE, or a plain text editor -- have a widget in your layout with the specified ID.