从其他活动更改TextView文本?

3
我目前正在设计一款电子书阅读器应用作为我的项目,我在从其他活动中更改TextView的文本方面遇到了问题。
我的项目内容如下,
Activity1包含两个按钮,当单击button1时,"Some Text"应出现,当单击button2时,在Activity2中的TextView1中应该显示"Some Other Text"。
我的意思是文本应仅出现在TextView1中。没有其他TextView。好的。
请提供一个简单的代码示例来解决我的问题。
对于问题的任何错误,请谅解,因为这是我第一次在互联网上提问。
谢谢您。

请确认一下,您的Activity2中只有一个TextView,而两个按钮在Activity1中,是这样吗? - Hiral Vadodaria
5个回答

0
希望您了解Android中SharedPreferences的概念。使用它,您可以满足此要求。这是一个全局位置,在其中您可以从应用程序的任何地方设置其值,并在同一应用程序中的任何地方使用它!
在Activity1中,
SharedPreference s_pref=PreferenceManager.getDefaultSharedPreferences(context);
Editor edit=s_pref.edit();

button1.setOnClick....()
{
     ... onClick()
     {
         edit.putString("textview_text","some text");
         edit.commit();
         /* you can start activity from here

         Intent intent = new Intent(Activity1.this, Activity2.class); 
         startActivity(intent);

         */
         //even if you don't start activity from here,text changed would be reflected in textView1 when activity2 is loded
     }
}

button2.setOnClick....()
{
     ... onClick()
     {
         edit.putString("textview_text","some other text");
         edit.commit();
         /* you can start activity from here

         Intent intent = new Intent(Activity1.this, Activity2.class); 
         startActivity(intent);

         */
         //even if you don't start activity from here,text changed would be reflected in textView1 when activity2 is loded
     }
}

在Activity2中,

...
SharedPreference s_pref=PreferenceManager.getDefaultSharedPreferences(context);
Editor edit=s_pref.edit();

String text=s_pref.getString("textview_text", "default text");
textView1.setText(text);
...

0

嘿,如果你想在另一个activity上显示textview中的文本,那么很简单,只需使用PutExtras传递值,并使用getExtras获取该值,使用Intent调用另一个activity即可。

请参见以下示例代码,以从一个activity传递值到另一个activity:

    Intent i = new Intent(Insert.this,Select_msg.class);
    i.putExtra("name", name.getText().toString());
        i.putExtra("emailid", emailid.getText().toString());
            i.putExtra("contact", contactno.getText().toString());
            startActivity(i);

Select_msg.class

 Intent i = getIntent();
    name=i.getStringExtra("name");
    email = i.getStringExtra("emailid");
    cntct = i.getStringExtra("contact");

希望这对你有用,只需将变量中的值设置到textview中即可。

0

0

你不能在另一个活动中设置文本。使用意图将值传递到下一个活动,然后在Activity2的onCreate()方法中从意图中检索后设置文本。


0

您可以使用一个名为MyText()的类,在其中可以设置和重置文本或文本视图的任何其他属性。

例如,如果您有一个名为setTextView(String text)的方法和另一个名为getText()的方法以及一个全局变量textVal,则第一个方法将设置textVal = text,即发送作为参数的值,第二个方法将返回textVal。 现在您可以从任何地方设置文本并从任何地方获取值,只需使用setText(MyText.getText)

希望这可以解决您的问题,请在评论中指出我的错误。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接