Search code examples
androidandroid-webviewonclicklistenerandroid-cardview

How to open WebView when click on Card View


I trying to open WebView when I click on Card View. The WebView is implemented in Main Activity. It is not working. I am new in coding. This is the Dashboard Activity 👇. Please tell me how can I solve the problem.

public class DashBoardActivity extends MainActivity implements View.OnClickListener {

public CardView card1, card2;

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

    card1 = findViewById( R.id.c1 );
    card2 = findViewById( R.id.c2 );



    card1.setOnClickListener( this );
    card2.setOnClickListener( this );
    
}


@Override
public void onClick(View v) {
    int id = v.getId();
    if (id == R.id.nav_home1) {
        web_view( "example1.com" );
    } else if (id == R.id.nav_home2) {
        web_view( "example2.com");
    }
}

}


Solution

  • You don't need to extend your Main Activity.

    Just pass the URL in Intent Extras to your Main Activity and start it there.

    @Override
    public void onClick(View v) {
        Intent intent = new Intent(this, MainActivity.class);   
        String example1 = "example1.com";
        String example2="example2.com";
        int id = v.getId();
        if (id == R.id.nav_home1) {
            intent.putExtra("URL", example1);
        } else if (id == R.id.nav_home2) {
            intent.putExtra("URL", example2);
        }
    startActivity(intent);
    }
    

    Then retrieve these extras in your onCreate MainActivity

    private WebView wv1;
    @Override
       protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          String url;
      
        if (savedInstanceState == null) {
        Bundle extras = getIntent().getExtras();
    
        if(extras == null) {
            url= null;
          } else {
            url= extras.getString("URL");
          }
    
        } else {
    
           url= (String) savedInstanceState.getSerializable("URL");
        
        }
    
        wv1=(WebView)findViewById(R.id.webView);
        wv1.setWebViewClient(new MyBrowser());
    
        wv1.getSettings().setLoadsImagesAutomatically(true);
        wv1.getSettings().setJavaScriptEnabled(true);
        wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        wv1.loadUrl(url);
    
    }