Issue
Based on user inputs I'm dynamically adding many textviews to a relative layout in a loop.
The problem is that as the number of tv increase the amount of time it takes to build the layout also increases to the point when the user will get the "wait/force close" message.
I know this due to being on the main UI thread but as far as I know I cannot add views to a layout asynchronously, say in doInBackground as you get "Only the original thread that created a view hierarchy can touch its views" error.
Each new tv is either to the right_of or below the previous tv, calculated in the loop, so I cannot move the addview statement into AsyncTask onPostExecute.
Is there a way to add the tvs, in the for loop, to a layout while using AsyncTask?
This is how it needs to be done:
public class LoadData extends AsyncTask<Void, Void, Void> {
protected void onPreExecute(){ ....
protected Void doInBackground(Void... params){ ...
while (yCoord + CellSizeH < b2.getHeight()) {
while (xCoord + CellSizeW < b2.getWidth() ) {
tv = new TextView(this);
tv.setTextSize(DisplayCellSizeH * 0.5f);
tv.setWidth(DisplayCellSizeW);
tv.setHeight(DisplayCellSizeH);
tv.setOnClickListener(new View.OnClickListener() {...
}
//this will error so needs to be in onPostExecute
thelayout.addView(tv, params1);
}
}
protected void onPostExecute(Void result){ ...
Hope this makes sense. Thanks
Solution
Adding this to AsyncTask doinbaground allow the views to be adding during the async task loop
Viewchart.this.runOnUiThread(new Runnable() {
public void run() {
thelayout.addView(tv, params1);
}
});
Answered By - Mark
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.