2012-02-16 14 views
1

傳遞一個簡單變量的正確方法是將其值設置爲在另一個類中使用的正確方法是什麼?我有一個計數器,它會隨着按鈕的增加而增加,當計數器= 3時,會調用一個方法來加載另一個活動,該活動使用一個表示該按鈕被按下的字符串加載另一個屏幕。這裏是我想包含從前一課中計數器變量傳遞的數字3,但我不確定正確的方法來做到這一點。 我試着創建類的一個實例,並連接到變量,但值永遠不會傳遞,它始終爲0.傳遞一個簡單的變量值用於Android中的另一個類

+0

不一樣的問題,但相同的答案:http://stackoverflow.com/questions/9308026/listview-onitemclicklistener-with-a-new-activity/9308067#9308067 – MByD 2012-02-16 09:06:40

回答

5

下面的代碼試試,

public class First 
{ 
    private static int myVarible = 0; 


    private void myMethod() 
    { 
     myVariable = 5; // Assigning a value; 
    } 

    public static int getVariable() 
    { 
     return myVariable; 
    } 
} 

public class Second 
{ 
    int i = First.getVariable(); // Accessing in Another class 
} 
+0

這工作完美!謝謝!我知道這很簡單,但我無法弄清楚。 – deucalion0 2012-02-16 09:18:33

5

您可以通過Intent - 資源包傳遞值。從當前活動

通行證值,

Intent intent=new Intent(this,ResultActivity.class); 
intent.putExtra("no",10); 
startActivity(intent); 

和ResultActivity(的onCreate)

Bundle bundle=getIntent().getExtras(); 
int value=bundle.getInt("no"); 

在非活性的類的情況下,用戶還可以定義一個公共方法。

例如,

public Integer getValue() //returns a value 
{ 
    return 10; 
} 

或者

public void setValue(Integer value) 
{ 
    ... 
} 
+0

我會給這個嘗試! – deucalion0 2012-02-16 09:14:57

1

一種方式做,當你建立你的新意圖這樣做將是:

Intent itn = new Intent(...,...); 
itn.putExtra(KEY,VALUE); 
startctivity(itn); 

和另一類這樣做:

this.getIntent.getStringExtra(KEY); 
or 
this.getIntent.getWHATEVERYOURVARIABLEWASExtra(KEY); 

希望它可以幫助你,這是更好的方式來2個活動:)

1

你也可以做到這一點通過定義變量之間傳遞參數「靜態」在一個活動和在第二活動使用該變量使用<<classname>>.<<variableb>>

例如:

Activity1:

Static var = 5;

活性2:

的System.out.println(Activity1.var);

1

可以使用意圖

Intent new_intent=new Intent(this,SecondActivity.class); 
intent.putExtra("counter",10); //here the value is integer so you use the new_intent.putExtra(String name,int value) 
startActivity(new_intent); 

後,在第二個活動類,你可以得到的值使用捆綁

Bundle bundle = getIntent().getExtras(); 
int count = bundle.getInt("counter"); 

我認爲這可以幫助你傳遞的價值。

相關問題