更新片段中的计时器滴答的TextView

时间:2013-05-14 09:49:18

标签: java android

我无法在标签片段中更新我的TextView。我希望在每一秒都使用全局变量数据在TextView上设置文本。这在活动中工作正常,但不在片段中。错误是: textView2无法解析。如果有更好的更新方法,或者这不好,请告诉我。

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");
                         }
                     });                    
                }};      
        }             
}

2 个答案:

答案 0 :(得分:1)

试试这个

textView3声明为字段。   TextView textView3;

并在onCreateView()

中对其进行初始化
textView3 = (TextView)myFragmentView.findViewById(R.id.TextView3);

onCreateView内初始化您的处理程序,以便它允许访问您的UI。 也为Handler做同样的事情

Handler timerHandler;

在oncrateView

timerHandler=new Handler();

答案 1 :(得分: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(){

.....

}


}