【问题标题】:adding view programmatically blocking the main thread以编程方式添加视图阻塞主线程
【发布时间】:2018-07-26 09:54:29
【问题描述】:

我的 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)

【问题讨论】:

    标签: android view textview viewgroup android-flexboxlayout


    【解决方案1】:

    由于您使用不同的威胁来创建您的 textview 列表,因此您不能直接从某个不同的线程修改主线程。 所以必须使用以下方式。

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

    【讨论】:

    • 谢谢,但问题仍然存在。
    猜你喜欢
    • 1970-01-01
    • 2018-02-16
    • 1970-01-01
    • 2015-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多