2012-02-25 2 views
1

나는 퀴즈와 같은 것을 만들고 있고, 정확하게 대답 된 질문의 수를 보여주는 카운터가 있다고 가정 해보십시오. 하나의 질문에 올바르게 대답하고 새 화면 (활동)이 표시되면 다음 화면으로 번호를 어떻게 옮길 수 있습니까?클래스간에 변수를 공유하려면 어떻게합니까?

답변

5

화면이란 말은 활동을 의미합니까? 그렇다면 당신은 아마도 당신의 의도를 엑스트라를 통해 전달하기를 원할 것입니다.

활동 1 :

int score; 

    ... 
    Intent Intent = new Intent(...); 
    intent.putExtra("score_key", score); 
    startActivity(intent); 

활동 2의 onCreate() : 당신은 당신의 의도와 번들 등 숫자, 문자열을 보낼 수 있습니다

int score; 
    ... 

    Bundle extras = getIntent().getExtras(); 

    // Read the extras data if it's available. 
    if (extras != null) 
    { 
     score = extras.getInt("score_key"); 
    } 
+0

당신이 바꿀 수 있습니다 "다음과 같이

<application android:name="MyApp" android:icon="@drawable/icon" android:label="@string/app_name"> 

지금 당신은 모든 활동에 변수를 조작 할 수 있습니다 :

public class MyApp extends android.app.Application { private String myVariable; public String getMyVariable() { return myVariable; } public void setMyVariable(String var) { this.myVariable = var; } 

응용 프로그램 태그 내부의 Manifest.xml에 새 클래스 추가 score_key "를 모든 문자열과 비교합니다. 여분인지 확인하는 것이 중요합니다. 같은 데이터를 넣고 설정할 때 두 개의 키가 일치하는지 확인하십시오. – triad

1

.

Bundle b = new Bundle(); 
b.putInt("testScore", numCorrect); 
Intent i = new Intent(this, MyClass.class); 
i.putExtras(b); 
startActivity(intent) 

당신은 또한 StringArrays과 다른 몇 가지 간단한 바르

당신이 전체 프로젝트 사이에서 데이터를 공유 할 수있는이 방법의
0

하나를 넣을 수 있습니다, 다른 클래스/활동에서

public class mainClass 
{ 
    private static int sharedVariable = 0; 


    public static int getSharedVariable() 
    { 
      return sharedVariable; 
    } 
} 

, 당신은 classname 및을 사용하여 직접 액세스 할 수 있습니다. (도트) 연산자. 예 : mainClass.getSharedVariable();

0

Activitiys에서 변수를 저장하는 좋은 방법은 응용 프로그램 클래스의 자체 구현을 사용하는 것입니다.

MyApp ctx = (MyApp)getApplicationContext(); 
String var = ctx.getMyVariable(); 
관련 문제