简体   繁体   English

以编程方式添加视图阻止主线程

[英]adding view programmatically blocking the main thread

There is a flexboxlayout in my UI and I want to dynamically add textviews to it. 我的UI中有一个flexboxlayout,我想向其中动态添加文本视图。 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循环中调用此方法。

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. 即使我将其编写在线程中,也将花费大量时间来执行,在此期间,UI不会响应。 Any idea to fix this? 有解决这个问题的主意吗? ( Array size more than 200 ) (数组大小超过200)

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 . 由于使用不同的威胁来创建textview列表,因此无法直接从其他线程修改主线程。 So have to use following way. 因此必须使用以下方式。

 new Thread(new Runnable() {

        @Override
        public void run() {

            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
//your code
                }
            });
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM