如何在不加载其他代码的情况下在ArrayList中实现字符串和SpannableString的混合

时间:2018-09-13 21:41:53

标签: java android arrays arraylist

是否可以在String中同时包含SpannableStringArrayList的混合,而无需增加代码负载?

public class MyFragment extends android.support.v4.app.Fragment {
    public MyFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_rv, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        View v = getView();
        assert v != null;

        recyclerView = v.findViewById(R.id.my_recyclerview);

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));

        // SpannableStrings
        SpannableStringBuilder ssb = new SpannableStringBuilder();

        SpannableString str1 = new SpannableString(" Hello World ");
        str1.setSpan(new BackgroundColorSpan(Color.BLACK), 0, str1.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        str1.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getContext(), R.color.circle)), 0, str1.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        ssb.append(str1);

        SpannableString str2 = new SpannableString(" Bonjour le monde");
        str2.setSpan(new ForegroundColorSpan(Color.BLACK), 0, str2.length(), 0);
        ssb.append(str2);

        data = new ArrayList<>();
        data.add(ssb);
        data.add(getString(R.string.section_b));
        data.add(getString(R.string.section_c));

        subdata = new ArrayList<>();
        subdata.add("Item A1");
        subdata.add("Item B1\nItem B2");
        subdata.add("Item C1\nItem C2\nItem C3");


        adapter = createAdapter();

        recyclerView.setAdapter(adapter);

        super.onActivityCreated(savedInstanceState);
    }

    RecyclerView recyclerView;
    ArrayList<Spannable> data;
    ArrayList<String> subdata;
    RecyclerView.Adapter<ViewHolder> adapter;
}

2 个答案:

答案 0 :(得分:2)

String和SpanableString都实现CharSequence。如果您不需要CharSequence无法提供的数据,则可以使用它。

data = new ArrayList<CharSequence>();

答案 1 :(得分:0)

最简单的方法是创建

ArrayList<Object> data = new ArrayList<>();

然后可以将任何对象添加到ArrayList中 希望这会有所帮助:)