Содержимое моего второго действия не отображается при запуске приложения. Спасибо за помощь

#android

#Android

Вопрос:

Это мой MainActivity

 package com.example.learning1;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
    public static final String EXTRA_MESSAGE = "com.example.learning1.MESSAGE";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    /** Called when the user taps the Send button */
    public void sendMessage(View view) {
        Intent intent = new Intent(MainActivity.this, DisplayMessageActivity.class);
        startActivity(intent);
        EditText editText = (EditText) findViewById(R.id.editTextTextPersonName);
        String message = editText.getText().toString();
        intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
    }
 

Это мой actvity_main.xml

 <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <EditText
        android:id="@ id/editTextTextPersonName"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:hint="@string/edit_message"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toStartOf="@ id/button"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:autofillHints="" />

    <Button
        android:id="@ id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginLeft="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:onClick="sendMessage"
        android:text="@string/button_send"
        app:layout_constraintBaseline_toBaselineOf="@ id/editTextTextPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@ id/editTextTextPersonName" />
</androidx.constraintlayout.widget.ConstraintLayout>
 

Это мое второе действие DisplayMessageActivity.java

     package com.example.learning1;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class DisplayMessageActivity extends AppCompatActivity {

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

        // Get the Intent that started this activity and extract the string
        Intent intent = getIntent();
        String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

        // Capture the layout's TextView and set the string as its text
        TextView textView = findViewById(R.id.editTextTextPersonName);
        textView.setText(message);

    }
}
 

Это мой второй activity xml activity_display_message.xml

     <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DisplayMessageActivity">

    <TextView
        android:id="@ id/editTextTextPersonName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="@string/textview"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
 

Это мой главный манифест AndroidManifest.xml

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.learning1">

    <application
        android:allowBackup="true"
        android:fullBackupContent="@xml/backup_descriptor"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.Learning1">
        <activity android:name=".MainActivity2"></activity>
        <activity
            android:name=".DisplayMessageActivity"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
 

Комментарии:

1. Пара сомнений из файла манифеста. Почему DisplayMessageActivity имеет фильтр намерений ЗАПУСКА? Почему MainActivity написано как MainActivity2 ?

Ответ №1:

Попробуйте это

 public class MainActivity extends AppCompatActivity {
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    editText = (EditText) findViewById(R.id.editTextTextPersonName);
}
/** Called when the user taps the Send button */
public void sendMessage(View view) {
    Intent intent = new Intent(MainActivity.this, DisplayMessageActivity.class);
    String message = editText.getText().toString();
    intent.putExtra("EXTRA_MESSAGE", message);
    startActivity(intent);
}
 

Отображение активности

 public class DisplayMessageActivity extends AppCompatActivity {

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

    // Get the Intent that started this activity and extract the string
    Intent intent = getIntent();
    String message = intent.getStringExtra("EXTRA_MESSAGE");

    // Capture the layout's TextView and set the string as its text
    TextView textView = findViewById(R.id.editTextTextPersonName);
    textView.setText(message);

}
 

}

AndroidManifest.xml

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.learning1">
<application
    android:allowBackup="true"
    android:fullBackupContent="@xml/backup_descriptor"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.Learning1">
    <activity android:name=".DisplayMessageActivity"></activity>
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
 

Комментарии:

1. проверьте еще раз с помощью MainActivity, DisplayMessageActivity и AndroidManifest.xml просто скопируйте и вставьте мой код в свои файлы.

2. Хорошо, я только что это сделал, и теперь это работает, большое спасибо за вашу помощь. Если позволите, что заставило его работать не так, как должно было раньше?

3. пожалуйста. в вашем коде есть две основные проблемы 1. В MainActivity вы запускаете активность, прежде чем вводить значение в intent. 2. В AndroidManifest.xml … вы устанавливаете launcher в фильтре намерений для DisplayActivity, который должен быть в первом действии вашего приложения, которое является MainActivity.

4. О! Я понимаю, большое спасибо за вашу помощь.