Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

android - Extra from Activity B to Activity A

I have two activities. In Activity A I have Textview. After click this I go to Activity B with EditText.

How can I pass the value from the EditText in activity B back to the TextView in activity A, keeping activity A's original state in the process?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Write Activity A like this

public class MainActivity extends Activity {  
TextView textView1;  
Button button1;  
@Override  
protected void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);  
    setContentView(R.layout.activity_main);  
    textView1=(TextView)findViewById(R.id.textView1);  
    button1=(Button)findViewById(R.id.button1);  
    button1.setOnClickListener(new OnClickListener() {  
        @Override  
        public void onClick(View arg0) {  
            Intent intent=new Intent(MainActivity.this,SecondActivity.class);  
            startActivityForResult(intent, 2);// Activity is started with requestCode 2  
        }  
    });  
}  
// Call Back method  to get the Message form other Activity  
@Override  
   protected void onActivityResult(int requestCode, int resultCode, Intent data)  
   {  
             super.onActivityResult(requestCode, resultCode, data);  
              // check if the request code is same as what is passed  here it is 2  
               if(requestCode==2)  
                     {  
                        String message=data.getStringExtra("MESSAGE");   
                        textView1.setText(message);  
                     }  
 }  
 }

Insted of startActivity use startActivityForResult

Intent intent=new Intent(MainActivity.this,SecondActivity.class);  
        startActivityForResult(intent, 2);// Activity is started with requestCode 2  

and in Activity B set result like this

   Intent intent=new Intent();  
                intent.putExtra("MESSAGE",message);  
                setResult(2,intent);  
                finish();//finishing activity  

you can get intent.putExtra("MESSAGE",message); in Activity A(onActivityResult)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...