How to use intent to open another activity in Android Studio.

NewImage

An Intent is an object that provides runtime binding between separate components such as two activities.

To build intent use the following code. You should create a button with onclick function set to OpenNewForm and textfield with id (edit_message)


public final static String EXTRA_MESSAGE = "com.example.yourapp.MESSAGE";

public void openNewForm(View view) {

    Intent intent = new Intent(this, Main2Activity.class);
    EditText editText = (EditText) findViewById(R.id.edit_message);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);
}
 
NewImage
 
Create New Empty Activity and paste the following code.
 
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);

ViewGroup layout = (ViewGroup) findViewById(R.id.activity_main2);
layout.addView(textView);
 


If you get can't resolve symbol error. Try pressing Alt + Enter (or Option + Return on Mac) to automatically import the files.

No comments:

Post a Comment