从片段内部刷新TextView

时间:2013-11-17 02:21:28

标签: android refresh fragment

我是android的新手,我在尝试开发应用时遇到了问题。

我想在我的活动中制作一个倒数计时器,但我需要在一个片段中进行,所以我需要设置一个从0到10计数的for循环并刷新该片段内的TextView。

我需要片段独立于活动。

感谢您的合作

public class fragmento_3 extends Fragment {

int count= 10;
TextView texto_count;
View v;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.fragmento_3, container, false);
    texto_count = (TextView)v.findViewById(R.id.texto_count);
    return v;
}
}

我想把它放在

里面
 for(int x = count; x >= 0 ; x--){
        texto_count.setText(String.valueOf(x));
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

感谢,

2 个答案:

答案 0 :(得分:2)

最好将Timer用于定期任务,而不是使用Thread.sleep

试试此代码

public class fragmento_3 extends Fragment{

    int count= 10;
    TextView texto_count;
    Timer t;
    View v;

    TimerTask timer= new TimerTask(){

        @Override
        public void run() {

            getActivity().runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    count--;
                    if(count >= 0) {
                    texto_count.setText(Integer.toString(count));
                    }
                }
            });
            if (count <= 0) {
                t.cancel();
            }
        }

    };

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    v = inflater.inflate(R.layout.fragmento_3, container, false);
    texto_count = (TextView)v.findViewById(R.id.texto_count);

    t = new Timer();
    t.scheduleAtFixedRate(timer , 0 , 2000);


    return v;
}


}

答案 1 :(得分:0)

可能是因为您使用了错误的变量texto_conteo。您已将texto_count声明为实例变量,因此您可能希望使用它。

相关问题