想要从其他活动更改TextView的文本?

时间:2012-02-09 06:07:32

标签: android textview

我目前正在设计一个电子书阅读器应用作为我的项目,我在从其他活动更改 textview 的文字时遇到了问题。

我的项目内容,

活动1 包含两个按钮,当点击 button1 时,应显示“Some Text”,当点击 button2 时“其他文字” sholud出现在 TextView1 中,位于 Activity2 中。

我的意思是文本应该只出现在TextView1中。没有其他textview。好的。

请用一个简单的代码示例来解决我的问题。

对于问题中的任何错误表示不好意思,因为这是我第一次尝试在互联网上提问。

谢谢

5 个答案:

答案 0 :(得分:0)

据我所知,您在第一次活动时无法访问第二个活动的UI组件。所以最好的方法是通过putExtra意图方法传递值,然后通过获取它在第二个活动的oncreate中将其设置为textview。以下是显示此方法的链接

http://mobileorchard.com/android-app-development-using-intents-to-pass-data-and-return-results-between-activities/

答案 1 :(得分:0)

您无法在其他活动上设置文字。使用intent将值传递给下一个活动,然后在Activity 2的onCreate()方法上从intent中检索后设置文本。

答案 2 :(得分: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);
...

答案 3 :(得分:0)

如果你想在textview上显示另一个activity上的文字然后在PutExtras的帮助下传递这些值,并在getExtras的帮助下获取这些值,那么它非常简单{1}}使用Intent来调用其他活动

请参阅示例代码以将值从一个活动传递到另一个活动

    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

答案 4 :(得分:0)

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

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

希望这会解决您的问题,如果我错了,请发表评论..

相关问题