当Fragment恢复时,AsyncTask不会更新UI

时间:2014-01-23 10:52:40

标签: android android-asynctask

我有一个" HomeFragment"扩展Fragment的类。一切都工作正常碎片是第一次创建。但是,当我切换到其他片段并回到此状态时,UI不会更新。实际上它在TextSwitcher中没有显示任何内容。我使用Log.d检查了ChangeText线程一直在后台运行。错误在哪里?

public class HomeFragment extends Fragment {

    private TextSwitcher mSwitcher;
    String textToShow[]={"Main HeadLine","Your Message"};
    int messageCount=textToShow.length;
    int currentIndex=-1;
    private Handler myHandler;
    ChangeText CT;

    public HomeFragment(){}

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

        View rootView = inflater.inflate(R.layout.fragment_home, container, false);

        mSwitcher = (TextSwitcher) rootView.findViewById(R.id.textSwitcher);
        mSwitcher.setFactory(new ViewFactory() {

            public View makeView() {
                // TODO Auto-generated method stub
                TextView myText = new TextView(getActivity());
                myText.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
                myText.setTextSize(36);
                myText.setTextColor(Color.BLUE);
                return myText;
            }
        });

// Declare the in and out animations and initialize them  
Animation in = AnimationUtils.loadAnimation(getActivity(),android.R.anim.slide_in_left);
Animation out = AnimationUtils.loadAnimation(getActivity(),android.R.anim.slide_out_right);
        mSwitcher.setInAnimation(in);
        mSwitcher.setOutAnimation(out);


        myHandler = new Handler() {
            public void handleMessage(Message msg) {
                doUpdate();
            }
        };




        CT = new ChangeText();
        CT.execute();

        return rootView;
    }

class ChangeText extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... f_url) {
            try {

                while(true)
                {
                    if (isCancelled())  break;
                    myHandler.sendEmptyMessage(currentIndex);
                    SystemClock.sleep(1500);
                }


            } catch (Exception e) {
                Log.e("VIVEK: ", e.getMessage());
            }

            return null;
        }

    }

private void doUpdate() {
        currentIndex++;
        if(currentIndex==messageCount)
        {
            currentIndex=0;
        }
        Log.d("VIVEK", textToShow[currentIndex]);
        mSwitcher.setText(textToShow[currentIndex]);
    }
}

2 个答案:

答案 0 :(得分:0)

你应该使用asynctask,尝试使用其他线程的处理程序 这是一个例子:Change View from other thread

另一个不错的例子:http://androidexample.com/Thread_With_Handlers_-_Android_Example/index.php?view=article_discription&aid=58&aaid=83

希望它有所帮助, 问候

答案 1 :(得分:0)

首先,我强烈建议你看一下CountDownTimer课程。我认为它更适合您的用例。 其次,尝试移动这些:

CT = new ChangeText();
CT.execute();

到片段的onResume()并查看它是否解决了您的问题。