×

demo for swapAdapter

96
Dragon_Boat
2017.08.12 17:11* 字数 0
public class MainActivity extends AppCompatActivity {
    RecyclerView recyclerView;
    BaseAdapter adapter1,adapter2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = $(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));

        adapter1 = new BaseAdapter(Source.get("left"));
        adapter2 = new BaseAdapter(Source.get("right"));

        Button button1 = $(R.id.button1);
        Button button2 = $(R.id.button2);

        recyclerView.setAdapter(adapter1);


        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recyclerView.swapAdapter(adapter1,false);
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                recyclerView.swapAdapter(adapter2,false);
            }
        });
    }

    @SuppressWarnings("unchecked")
    public <T> T $(int resId) {
        return (T) findViewById(resId);
    }

    class BaseAdapter extends RecyclerView.Adapter{
        List<String> data;

        public BaseAdapter(List<String> data) {
            super();
            this.data = data;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new BaseViewHolder(new TextView(parent.getContext()));
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            ((BaseViewHolder) holder).render(data.get(position));
        }

        @Override
        public int getItemCount() {
            return data.size();
        }

        class BaseViewHolder extends RecyclerView.ViewHolder{
            TextView textView;
            public BaseViewHolder(View itemView) {
                super(itemView);
                textView = ((TextView) itemView);
            }
            public void render(String name){
                textView.setText(name);

            }
        }
    }

    static class Source{

        public static List<String> get(String name){
            List<String> list = new ArrayList<>();

            int size = (int) (10 + Math.random() * 100);
            for (int i = 0; i < size; i++) {
                list.add(name + i);
            }
            return list;
        }
    }
}
Android学习笔记
Web note ad 1