'value'에 해당되는 글 1건

  1. 2014.11.04 Activity(View) 사이에 데이터 주고 받기 (1)
dngchn's [Android]2014. 11. 4. 22:47

지난 예제를 조금 확장해보자.

우선 새롭게 뜨는 뷰에 부모(?)뷰에서 데이터를 전달해보기로 한다.

이를 위해 필요한 것은 아래와 같다.

anotherIntent.putExtra("key", "value");

말 그대로 어떠한 값(value)을 하나의 키(key)로 넣어두는 것이다.

왜? 넣어두어야 새로운 뷰에서 꺼내어 참조할 수 있으니까.


그럼 어떻게 꺼낼까? 간단하다.

Intent myIntent = getIntent();
myIntent.getStringExtra("key");

알고있는 키를 통해 얻어내면 된다.


그럼 이와 같은 기본 개념을 갖고 예제를 통해 확인해보자.

우선 부모 뷰에서 EditText를 하나 두어, 사용자가 무언가 데이터를 입력하도록 하고,

이 데이터가 새로이 보여지는 뷰에 전달되도록(정확히는 새로운 뷰에서 꺼낼수 있도록) 하여,

뷰간의 데이터가 전달됨을 확인해보자.


우선 부모 뷰의 레이아웃(activity_main.xml)이다.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    
    <EditText
        android:id="@+id/toSend"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
    
    <Button
        android:id="@+id/nextButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Next"
        /> 

</LinearLayout>

EditText를 배치하여 새로운 뷰로 전달할 메시지를 입력 받는다.


부모 뷰의 액티비티(MainActivity.java) 코드이다.

public class MainActivity extends ActionBarActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		Button btnNext = (Button) findViewById(R.id.nextButton);
		btnNext.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {				
				Intent anotherIntent = new Intent(getApplicationContext(), AnotherActivity.class);
				TextView toSend = (TextView) findViewById(R.id.toSend);				
				anotherIntent.putExtra("message", toSend.getText().toString());
				startActivity(anotherIntent);				
			}
		});
	}

startActivity를 호출하기 전에 'putExtra'를 통해 EditText에 입력된 텍스트를 'message'를 키로 삼아 넣어둔다.


새롭게 뜨는 뷰의 레이아웃(activity_another.xml)이다.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    
    <TextView
        android:id="@+id/sentFrom"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
    
    <Button
        android:id="@+id/closeButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Close"
        />   

</LinearLayout>

부모 뷰로부터 받은 메시지를 보여주기 위한 TextView를 위치 시킨다.


새롭게 뜨는 뷰의 액티비티(AnotherActivity.java) 코드이다.

public class AnotherActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);	
		setContentView(R.layout.activity_another);
		
		TextView sendMessage = (TextView) findViewById(R.id.sentFrom);
		Intent myIntent = getIntent();		
		sendMessage.setText(myIntent.getStringExtra("message"));		
		
		Button btnClose = (Button) findViewById(R.id.closeButton);
		btnClose.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {				
				finish();				
			}
		});
	}
}

'getStringExtra'를 통해 부모 뷰로부터 전달된 데이터를 받아 표시한다.

데이터를 넘길 때 사용한 키('message')를 이용하여 얻어낸다.


이렇게 하여 실행해보면 아래와 같이 잘 동작됨을 확인할 수 있다.



만약 데이터의 흐름을 이번과 반대로 즉, 새로운 뷰에서 생성된 데이터가 부모 뷰로 가게 하려면 어떻게 해야 할까?

이는 다음 글에서 계속해서 알아보도록 하자.


Posted by dngchn