Android using findViewById from another activity

3

I need to assign a value to an element that is in another activity

I'm trying this way:

MainActivity activityprincipal = new MainActivity();

WebView view = (WebView) activityprincipal.findViewById(R.id.webView);
    
asked by anonymous 22.02.2017 / 17:42

1 answer

1

As said by @GiulianaBezerra in the comment, use if a Intent to provide links between Activity's at runtime.

Here's an example:

public class MainActivity extends AppCompatActivity {
    public final static String EXTRA_URL = "MainActivity.URL";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    public void startActivity(String url) {
        Intent intent = new Intent(this, OtherActivity.class);
        // Adiconamos a url ao intent...
        intent.putExtra(EXTRA_URL, url);
        startActivity(intent);
    }
}

In the other Activity, we get the value:

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_other);

   Intent intent = getIntent();
   String url = intent.getStringExtra(MainActivity.EXTRA_URL);

  WebView view = (WebView)findViewById(R.id.webView);
 view.loadUrl(url);

}

SOURCE

    
22.02.2017 / 18:14