버튼 클릭시 새로운 활동을 시작하는 방법 다른 활동의 단추를

Android 애플리케이션에서 다른 활동의 단추를 클릭 할 때 새 활동 (GUI)을 시작하는 방법과이 두 활동간에 데이터를 전달하는 방법은 무엇입니까?



답변

쉬운.

Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
myIntent.putExtra("key", value); //Optional parameters
CurrentActivity.this.startActivity(myIntent);

추가 정보는 다음을 통해 다른 쪽에서 검색됩니다.

@Override
protected void onCreate(Bundle savedInstanceState) {
    Intent intent = getIntent();
    String value = intent.getStringExtra("key"); //if it's a string you stored.
}

AndroidManifest.xml에 새로운 활동을 추가하는 것을 잊지 마십시오 :

<activity android:label="@string/app_name" android:name="NextActivity"/>

답변

ViewPerson 활동에 대한 의도를 작성하고 PersonID를 전달하십시오 (예 : 데이터베이스 검색).

Intent i = new Intent(getBaseContext(), ViewPerson.class);
i.putExtra("PersonID", personID);
startActivity(i);

그런 다음 ViewPerson Activity에서 추가 데이터 번들을 가져 와서 null이 아닌지 확인하고 (때로는 데이터를 전달하지 않는 경우) 데이터를 가져옵니다.

Bundle extras = getIntent().getExtras();
if(extras !=null)
{
     personID = extras.getString("PersonID");
}

이제 두 활동간에 데이터를 공유해야하는 경우 글로벌 싱글 톤을 가질 수도 있습니다.

public class YourApplication extends Application
{
     public SomeDataClass data = new SomeDataClass();
}

그런 다음 다음을 수행하여 활동에서 호출하십시오.

YourApplication appState = ((YourApplication)this.getApplication());
appState.data.CallSomeFunctionHere(); // Do whatever you need to with data here.  Could be setter/getter or some other type of logic

답변

현재 답변은 훌륭하지만 초보자에게는보다 포괄적 인 답변이 필요합니다. Android에서 새로운 활동을 시작하는 방법은 3 가지가 있으며 모두 Intent클래스를 사용합니다 . 의도 | 안드로이드 개발자 .

  1. onClick버튼 의 속성을 사용합니다 . (초보자)
  2. OnClickListener()익명 클래스를 통해 할당 . (중급)
  3. switch명령문을 사용한 활동 전체 인터페이스 방법 . (찬성)

따라하고 싶다면 내 예에 대한 링크 가 있습니다.

1. onClick버튼 의 속성 사용 . (초보자)

버튼에는 onClick.xml 파일 내에 있는 속성이 있습니다.

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="goToAnActivity"
    android:text="to an activity" />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="goToAnotherActivity"
    android:text="to another activity" />

자바 클래스에서 :

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

public void goToAnActivity(View view) {
    Intent intent = new Intent(this, AnActivity.class);
    startActivity(intent);
}

public void goToAnotherActivity(View view) {
    Intent intent = new Intent(this, AnotherActivity.class);
    startActivity(intent);
}

장점 : 쉽고 빠르게 모듈 식으로 만들 수 있으며 여러 onClick의도를 동일한 의도로 쉽게 설정할 수 있습니다 .

단점 : 검토 할 때 어려운 가독성.

2. OnClickListener()익명 클래스를 통해 할당 . (중급)

이것은 setOnClickListener()각각을 개별적 으로 설정하고 button각각 onClick()의 의도 로 각각 을 재정의하는 경우 입니다.

자바 클래스에서 :

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

        Button button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(view.getContext(), AnActivity.class);
                view.getContext().startActivity(intent);}
            });

        Button button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(view.getContext(), AnotherActivity.class);
                view.getContext().startActivity(intent);}
            });

장점 : 즉석에서 쉽게 만들 수 있습니다.

단점 : 검토 할 때 가독성을 떨어 뜨리는 익명 클래스가 많이있을 것입니다.

3. switch문장을 사용한 활동 전반의 인터페이스 방법 . (찬성)

메소드 switch내에서 단추에 대한 명령문을 사용하여 onClick()모든 활동 단추를 관리 할 때입니다.

자바 클래스에서 :

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

    Button button1 = (Button) findViewById(R.id.button1);
    Button button2 = (Button) findViewById(R.id.button2);
    button1.setOnClickListener(this);
    button2.setOnClickListener(this);
}

@Override
public void onClick(View view) {
    switch (view.getId()){
        case R.id.button1:
            Intent intent1 = new Intent(this, AnActivity.class);
            startActivity(intent1);
            break;
        case R.id.button2:
            Intent intent2 = new Intent(this, AnotherActivity.class);
            startActivity(intent2);
            break;
        default:
            break;
    }

장점 : 모든 버튼 의도가 단일 onClick()방법으로 등록되어있어 간편한 버튼 관리


질문의 두 번째 부분 인 데이터 전달에 대해서는 Android 애플리케이션의 활동간에 데이터를 전달하는 방법을 참조하십시오 .


답변

사용자가 버튼을 클릭하면 XML 내부에서 다음과 같이 직접 수행됩니다.

<Button
         android:id="@+id/button"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="TextButton"
         android:onClick="buttonClickFunction"/>

속성 android:onClick을 사용하여 부모 활동에 존재해야하는 메소드 이름을 선언합니다. 따라서 다음과 같이 활동 내에서이 메소드를 작성해야합니다.

public void buttonClickFunction(View v)
{
            Intent intent = new Intent(getApplicationContext(), Your_Next_Activity.class);
            startActivity(intent);
}

답변

Intent iinent= new Intent(Homeactivity.this,secondactivity.class);
startActivity(iinent);

답변

    Intent in = new Intent(getApplicationContext(),SecondaryScreen.class);
    startActivity(in);

    This is an explicit intent to start secondscreen activity.

답변

엠마누엘,

액티비티를 시작하기 전에 추가 정보를 넣어야한다고 생각합니다. 그렇지 않으면 NextActivity의 onCreate 메소드에서 액세스하면 데이터를 사용할 수 없습니다.

Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);

myIntent.putExtra("key", value);

CurrentActivity.this.startActivity(myIntent);