2013-05-14 62 views
0

我有麻煩更新我的TextView中的選項卡片段。我想用全局變量數據在TextView上每秒設置一次Text。這在活動中正常工作,但不在分段中。錯誤是:textView2無法解析。如果有更好的方法來更新它,或者這是不好的,請告訴我。在片段中更新TextView on計時器刻度

public class FragmentA extends Fragment { 

    //timer 
     private TimerTask mTimerTask; 
     private Timer timer = new Timer(); 

     private final Handler timerHandler = new Handler(); 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     View myFragmentView = inflater.inflate(R.layout.fragment_a, container, false); 


     //TextView for Device name 
     TextView textView3 = (TextView)myFragmentView.findViewById(R.id.TextView3); 
     //TextView for Serial number 
     TextView textView5 = (TextView)myFragmentView.findViewById(R.id.TextView5); 
     //TextView for Software version 
     TextView textView7 = (TextView)myFragmentView.findViewById(R.id.TextView7); 

     onTimerTick(); 
     timer.schedule(mTimerTask, 10, 1000); 

     return myFragmentView; 
    } 

     //timer tick on every 1 s 
     public void onTimerTick() { 
      mTimerTask = new TimerTask() { 
       //this method is called every 1ms 
       public void run() {     
        timerHandler.post(new Runnable() { 
         public void run() { 
          //update textView 
          //ERROR:textView2 cannot be resolved 
           textView2.setText(m_info.deviceName); 
          Log.d("tag", "Hello from timer fragment"); 
         } 
        });      
       }};  
     }    
} 
+0

哪裏是'textView2'在你的代碼? – Pragnani 2013-05-14 09:50:43

+0

對不起,TextView3例如... textView3.setText(m_info.deviceName); – anze87 2013-05-14 09:58:12

+0

好的檢查我的答案 – Pragnani 2013-05-14 10:03:09

回答

1

試試這個

聲明textView3作爲一個字段。 TextView textView3;

並初始化它在onCreateView()

textView3 = (TextView)myFragmentView.findViewById(R.id.TextView3); 

而且還

初始化的onCreateView內部處理程序,因此它允許訪問你的UI。 做處理程序同樣也

Handler timerHandler; 

而且在oncrateView

timerHandler=new Handler(); 
+0

這個工程就像一個魅力:)當我沒有選擇onPause方法時,我是否需要停止計時器?因爲在調試中,我可以看到計時器運行甚至沒有選擇標籤。這個問題可以解決嗎? – anze87 2013-05-14 10:19:46

0

onTimerTick()應該在你的MainActivity類中; 然後在你的主要活動類

TextView textViewForTimerTick=this.findViewById(R.id.text_view_2);// id of a textView in your fragment; 

就是這樣。

這樣:

class MainActivity{ 
private TextView tv2; 

protected void onCreate(Bundle...){ 
. 
. 
setFragmentToContainer(new FragmentA);// i dont' know how you are setting up your fragment 
. 
. 
tv2=(TextView)this.findViewById(R.id.text_view_in_fragment);// only after you'v set up your fragment 
onTimerTick(); 
} 

public void onTimerTick(){ 

..... 

} 


}