2014-09-29 60 views
0

這是我的代碼。在onClick方法中,我想刷新textView。所以每次點擊按鈕時,該方法都會調用int value = SecondFragment.getSmashValue();。從那裏我得到了我在另一個片段中設置的價值。我必須在我的我的onCreate方法中設置的TextView中使用這個變量。但它總是告訴我值0!我認爲它顯示0,因爲我試圖使全局變量和全局值爲0.如何將我的本地變量用作全局變量?

那麼,如何讓這個變量在不丟失其值的情況下在全局變量?

import com.example.viewpagertest2.R; 

import android.os.Bundle; 
import android.support.v4.app.Fragment; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.Button; 
import android.widget.TextView; 

public class Tab1Activity extends Fragment { 

Button b1; 
static int theValue; 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 
    View rootView = inflater.inflate(R.layout.firsttabview, container, false); 
    b1 = (Button) rootView.findViewById(R.id.refreshButton1); 
    b1.setOnClickListener(handler); 

    TextView tv = (TextView) rootView.findViewById(R.id.SP); 
    tv.setText("" + theValue); 

    b99.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      theValue = SecondFragment.getSmashValue(); 
      tv.setText("" + theValue); 

     } 
    }); 


    return rootView; 


} 

回答

-2

爲什麼る聲明一個局部變量用不着它來獲得value.Use全局變量only.you可以這樣做:

 if(b1==v){ 
      theValue = SecondFragment.getSmashValue(); //use theValue wherever u wanted to use 


    } 
+0

是的,你是對的,但這不是問題,我開始認爲我的變量分配 – gewhjhfkgad 2014-09-29 08:51:58

+0

5月失敗如果你正在做的錯誤是,在獲得值的價值之後,你再次用「theValue」變量初始化它。因此它取得了「theValue」變量值。你這樣做:theValue = value; – 2014-09-29 08:57:17

+0

是的,這是真的! @Seçkin說也是,我將它改爲'theValue = ....'但它仍然不起作用,也許我必須過時我的變量賦值 – gewhjhfkgad 2014-09-29 09:01:18

0

你分配未初始化theValue到本地value變量。翻轉該聲明。

int value = SecondFragment.getSmashValue(); 
theValue = value; // was value = theValue; 

此外,還要tv一個字段,這樣你就可以從你的事件處理程序更新的TextView。

tv.setText("" + theValue); 
+0

的第一件事情是一個非常愚蠢的錯誤... 但是,我應該創造什麼樣的領域? – gewhjhfkgad 2014-09-29 08:23:07

+0

將它聲明爲一個字段,從你的'onCreateView()'之外。所以你可以從其他方法訪問它。 – 2014-09-29 12:26:31

+0

啊okey,我發現主要問題,它不是附件,它是TextView。它沒有更新後點擊按鈕,我必須更改Tab,以便舊的Tab重新加載... – gewhjhfkgad 2014-09-29 19:31:59