How to implement mixture of Strings and SpannableStrings in ArrayList without loads of additional code

Lover

New Member
#1
Is it possible to have a mixture of both String and SpannableString in an ArrayList without adding loads of code?
Mã:
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;
}
 

Admin

Administrator
Thành viên BQT
#2
Both String and SpanableString implement CharSequence. If you don't need data that CharSequence can't give you, you can just use that.
Mã:
data = new ArrayList<CharSequence>();
 

Từ khóa phổ biến

You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an alternative browser.

Top