我有一個擴展片段的「HomeFragment」類。一切工作正常,第一次創建片段。但是,當我切換到其他片段並回到此時,UI不會更新。實際上它在TextSwitcher中沒有任何顯示。我使用Log.d檢查了ChangeText線程始終在後臺運行。錯誤在哪裏?AsyncTask在片段恢復時不更新UI
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]);
}
}
在asynctask中添加onPostExecute()方法並調用它doUpdate() –
onPostExecute()應該怎麼做? – gomchikbhoka
call doUpdate()我想,如果該方法更新片段,沒有真正閱讀所有代碼:D 檢查示例:http://stackoverflow.com/questions/9671546/asynctask-android-example?rq=1 –