Android use findViewById from other Activity

Asked

Viewed 469 times

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

    It can’t be done like this. Explain what you want to achieve with it.

  • i have a class, in this class I want to spend a loadurl on webview, but this webview is in another Activity, how can I do it

  • Why don’t you save the loadurl or the webview object and pass it on to another Activity by Intent?

  • how to do this ? I don’t many on android/java

  • You want to pass an Activity B value to an Activity A (where Activity A is the "first" and Activity B is called by A)?

1 answer

2


As stated by @Giulianabezerra in the comment, uses if a Intent to provide links between Activity’s at runtime.

Follow 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 take the amount :

@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

  • what I saw you passing the Activity one url to a webview on Activity 2 is this ?

  • huum in my case has to be the opposite, I think it will help I’ll try

  • in EXTRA_URL this giving cannot resolve Symbol

  • @Jeffersonmelloolynyki If it is the other way around use startActivityForResult(), in the Activity that has webView to call the other Activity, and implement the onActivityResult() method. Behold How to get results from an activity

  • which would be Intent Intent = new Intent(this, Otheractivity.class); Otheractivity , the current class or the one that will receive the url

  • got it here, thanks

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.