繁体   English   中英

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

[英]adding view programmatically blocking the main thread

我的UI中有一个flexboxlayout,我想向其中动态添加文本视图。 请在下面找到代码。

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();
}

我在for循环中调用此方法。

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

即使我将其编写在线程中,也将花费大量时间来执行,在此期间,UI不会响应。 有解决这个问题的主意吗? (数组大小超过200)

由于使用不同的威胁来创建textview列表,因此无法直接从其他线程修改主线程。 因此必须使用以下方式。

 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