0

我在标签片段中更新我的 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");
                         }
                     });                    
                }};      
        }             
}
4

2 回答 2

1

尝试这个

声明textView3为字段。文本视图 textView3;

并在onCreateView()

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

并且

在 中初始化您的 Handler onCreateView,以便它允许访问您的 UI。对 Handler 也做同样的事情

Handler timerHandler;

在 oncrateView

timerHandler=new Handler();
于 2013-05-14T10:02:53.217 回答
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(){

.....

}


}
于 2013-05-14T10:01:41.647 回答