1. 程式人生 > >簡易上下切換專項練習(一)

簡易上下切換專項練習(一)

簡易上下切換專項練習(一)

 private GridView top;
    private GridView bottom;
    private List<Bean> tops = new ArrayList<>();
    private List<Bean> bottoms = new ArrayList<>();
    private MyTopAdapter topAdapter;
    private MyBottomAdapter bottomAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化控制元件
        top = findViewById(R.id.top_gridview);
        bottom = findViewById(R.id.bottom_gridview);
        //建立標題資料
        for (int i = 0; i < 15; i++) {
            tops.add(new Bean("上部" + i));
        }
        for (int i = 0; i < 10; i++) {
            bottoms.add(new Bean("下部" + i));
        }
        //設定介面卡
        topAdapter = new MyTopAdapter(MainActivity.this, tops);
        bottomAdapter = new MyBottomAdapter(MainActivity.this, bottoms);
        top.setAdapter(topAdapter);
        bottom.setAdapter(bottomAdapter);
        //長按監聽
        top.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                Bean bean = tops.get(position);
                tops.remove(bean);
                bottoms.add(bean);
                topAdapter.notifyDataSetChanged();
                bottomAdapter.notifyDataSetChanged();
                return false;
            }
        });
        bottom.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bean bean = bottoms.get(position);
                bottoms.remove(position);
                tops.add(bean);
                topAdapter.notifyDataSetChanged();
                bottomAdapter.notifyDataSetChanged();
            }
        });
    }
}