单击按钮更改EditText

问题描述 投票:-5回答:2

我有个问题。我想从除按钮之外的其他活动更改EditText字段中的文本。

这是我的主要xml:

<EditText
    android:id="@+id/articlename"
    android:layout_width="278dp"
    android:layout_height="75dp"
    android:layout_marginStart="16dp"
    android:layout_marginTop="4dp"
    android:clickable="false"
    android:cursorVisible="false"
    android:ems="10"
    android:focusable="false"
    android:inputType="textMultiLine"
    android:text="Name of article"
    android:textColor="#FFF"
    android:textSize="22dp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />
<Button
    android:id="@+id/button"
    android:layout_width="90dp"
    android:layout_height="90dp"
    android:layout_marginStart="16dp"
    android:layout_marginTop="108dp"
    android:background="@drawable/circle"
    android:onClick="onClicknews"
    android:text="news\n(click me)"
    android:textColor="#FFFF"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

这是我的MainActivity按钮所在的位置:

  public void onClicknews(View v) {
    Intent intent = new Intent(getApplicationContext(), NewsActivity.class);
    String titel1 = "Trumps brutales Kalkül";
    EditText news = (EditText) findViewById(R.id.news);
    EditText article = (EditText) findViewById(R.id.articlename);
    String s = article.getText().toString();
    if (s.equalsIgnoreCase(titel1)){
        news.setText("Hallo");
    }
    startActivity(intent);
}

这是我的第二个xml,其中EditText是:

 <EditText
    android:id="@+id/news"
    android:layout_width="350dp"
    android:layout_height="407dp"
    android:layout_marginBottom="23dp"
    android:layout_marginEnd="11dp"
    android:layout_marginStart="11dp"
    android:clickable="false"
    android:cursorVisible="false"
    android:ems="10"
    android:focusable="false"
    android:inputType="textMultiLine"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

我知道有类似的问题,但没有一个解决方案对我有帮助。

android onclick android-edittext
2个回答
0
投票

在您的MainActivity.java中:

public void onClicknews(View v) {

   String titel1 = "Trumps brutales Kalkül";

   EditText article = (EditText) findViewById(R.id.articlename);
   String s = article.getText().toString();
   Intent intent = new Intent(getApplicationContext(), NewsActivity.class);
   intent.putExtra("articalName",s);
   startActivity(intent);
}

在你的NewsActivity.java中:

EditText news = (EditText) findViewById(R.id.news);

String newsName = getIntent().getStringExtra("articalName");

news.setText(newsName );

0
投票

没有安全的方法只使用Android流程来做到这一点。 Android系统总是可以销毁目前看不到的活动,因此您的EditText可能不存在。您可以使用dagger创建Singleton或dependency以在活动之间保存数据。

© www.soinside.com 2019 - 2024. All rights reserved.