簡體   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