I have a "HomeFragment" class which extends Fragment. Everything is working fine fragment is created for the first time. But when I switch to some other fragment and come back to this, the UI does not get updated. In fact it shows nothing in that TextSwitcher. I checked using Log.d that ChangeText thread is running in background all the time. Where is the mistake ?
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]);
}
}