【问题标题】:Passing value in an EditText from activity to view class将 EditText 中的值从活动传递到视图类
【发布时间】:2014-03-12 19:21:56
【问题描述】:

我有这个 EditText,其中包含我想传递给视图类(不是活动)的值。但是,我做不到。我尝试将值传递回 MainActivity 并尝试从视图类访问该值,但失败了。

这是来自 EditText 包含名称的 NameActivity :

 Intent intent = new Intent(NameActivity.this, MainActivity.class);
           String name = nameEditText.getText().toString();
           intent.putExtra("name",name);

这是来自我的 MainActivity:

public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

         Intent i = getIntent();
         String name = i.getStringExtra("name"); 

         }
}

我做对了吗?我该怎么做才能访问视图类中的值?

【问题讨论】:

  • 视图类在哪里MainActivity也是一个Activity类
  • 您的意思是您正在尝试根据在 EditText 视图中传递的值来更新视图内容?你似乎采取了正确的步骤。你从哪里开始你的意图?
  • 您可以使用 SharedPreferences 保存数据并在另一个类或活动中检索它们。

标签: android android-intent view android-activity


【解决方案1】:

一些事情。

您缺少 MainActivity 中 onCreate(Bundle savedInstanceState) 方法的 @Override 注释。

您还应该确保您的 nameEditText 是一个类成员变量,而不仅仅是 NameActivity.class 的 onCreate(Bundle savedInstance) 方法中的一个成员,这样您就可以在执行操作后访问它,例如单击按钮.

如:

public class NameActivity extends Activity(){

   // Now the EditText is accessible anywhere in this Activity
   TextView nameEditText = null;

   // Dont forget to add the override annotation
   @Override
   protected void onCreate(Bundle savedInstanceState){
       super.onCreate(savedInstanceState);
       setContentView(R.layout.name_activity_layout);

       // Find the UI ELement by its Id
       nameEditText = (EditText) findViewById(R.id.nameEditTextId);


    }

    // Then whatever Action Triggers your new Intent should include 
    // the code above which creates and starts the new intent however your are doing this
    public void actionPerformedAndNewActivity(){

      // Create a new Intent
      Intent intent = new Intent(NameActivity.this, MainActivity.class);
      // get the text from the UI EditText
      String name = nameEditText.getText().toString();

      // Add it to the intent Extras
      intent.putExtra("name",name);

      // Missing this Line, start the new Activity
      startActivity(intent);
    }

}

然后在你的 MainActivity 中:

public class MainActivity extends Activity {

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

     // Get the Intent that started this Activity
     Intent i = getIntent();

     // Grab the Name from the calling Intent Extras
     String name = i.getStringExtra("name"); 

 }
}

【讨论】:

  • 我明白了!但是我如何从另一个类(不是活动)访问字符串名称?我有这个绘制矩形的视图类。
  • 好的,这有点多,但也能做到。你能分享一下绘制矩形的视图类吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-04
  • 2016-03-01
  • 1970-01-01
  • 2015-07-04
相关资源
最近更新 更多