When
layout or image or any UI component has to be show or hide after specific period of time like 3 secs.
In this case, we think about thread but when we use thread directly and try to update UI, we will be
facing "android.view.ViewRoot$CalledFromWrongThreadException:
Only the original thread that created a view hierarchy can touch its views.”
Cause:
This error is common if you tried to send
UI events to the UI thread from outside the UI thread.
The test method Thread tried to interact
with the UI outside the UI thread.
Suggested:
Use Handler to solve the cause.
Sample Code:
private TextView titleTV;
/**
* handler is used for information bar.
*/
final Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
titleTV = (TextView) findViewById(R.id.textView1);
handler.postDelayed(new HideThread(), 3000);
}
private void hideTitle() {
titleTV.setVisibility(View.INVISIBLE);
}
public class HideThread implements Runnable {
public void run() {
try {
hideTitle();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Thanks... thats simple but really helpful.
ReplyDelete