2

There is a flexboxlayout in my UI and I want to dynamically add textviews to it. Please find the code below.

private void addOption(String option) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            TextView textView = new TextView(_context);
            textView.setText(option);
            textView.setBackgroundResource(R.drawable.profile_round_coner_shape);
            textView.setTextColor(Color.parseColor("#00324b"));
            textView.setAllCaps(true);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10f);
            textView.setPadding((int) Utils.dp2px(_context, 6), (int) Utils.dp2px(_context, 7), (int) Utils.dp2px(_context, 6), (int) Utils.dp2px(_context, 7));
            FlexboxLayout.LayoutParams params = new FlexboxLayout.LayoutParams(FlexboxLayout.LayoutParams.WRAP_CONTENT, FlexboxLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(0, (int) Utils.dp2px(_context, 2), (int) Utils.dp2px(_context, 4), 0);
            textView.setLayoutParams(params);
            handlerOverlow.post(new Runnable() {
                @Override
                public void run() {
                    flexboxLayoutOptions.addView(textView);
                }
            });

        }
    }).start();
}

I'm calling this method inside a for loop.

for (int i = 1; i < allOptions.size(); i++) {
    addOption(allOptions.get(i).getOptionName());
}

Even I write it inside a thread, It will take a considerable time to execute and during this time the UI will not respond. Any idea to fix this? ( Array size more than 200 )

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Anjula
  • 1,690
  • 23
  • 29

1 Answers1

0

Since you are using different threat to create a your list of textview ,so you cannot modify the main thread directly from some different thread . So have to use following way.

 new Thread(new Runnable() {

        @Override
        public void run() {

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
//your code
                }
            });
        }
    });
Vishwa Pratap
  • 374
  • 6
  • 14