将EditText中的值从活动传递到视图类

时间:2014-03-12 19:21:57

标签: android android-intent view android-activity

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

这是来自NameActivity,其中EditText包含名称:

 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"); 

         }
}

我是以正确的方式做到的吗?我能做什么才能访问视图类中的值?

1 个答案:

答案 0 :(得分:0)

一些事情。

您缺少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"); 

 }
}