Android中的封装流式布局FlowLayout

鸿洋的GitHub:https://github.com/hongyangAndroid/FlowLayout

第一步:加依赖

implementation 'com.hyman:flowlayout-lib:1.1.2'

第二步:创建一个Adapter继承TagAdapter

public class MyFlowAdapter extends TagAdapter {

    private Context context;

    public MyFlowAdapter(Context context,List datas) {
        super(datas);
        this.context=context;
    }

    @Override
    public View getView(FlowLayout parent, int position, String s) {
        LayoutInflater inflater = LayoutInflater.from(context);
        TextView tv = (TextView) inflater.inflate(R.layout.flow_item, parent, false);
        tv.setText(s);
        return tv;
    }

    /**
     * 选中时的回调方法
     * @param position
     * @param view
     */
    @SuppressLint("ResourceAsColor")
    @Override
    public void onSelected(int position, View view) {
        super.onSelected(position, view);
        view.setBackgroundColor(R.color.colorAccent);
    }

    /**
     * 默认的回调方法
     * @param position
     * @param view
     */
    @SuppressLint("ResourceAsColor")
    @Override
    public void unSelected(int position, View view) {
        super.unSelected(position, view);
        view.setBackgroundColor(R.color.colorPrimaryDark);
    }
}

第三步:创建一个子布局





第四步:使用页面的布局




    
    

    

第五步:在Activity中的使用方式

public class MainActivity extends AppCompatActivity {

    List list = new ArrayList<>();
    private TagFlowLayout mFlow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initData();
    }

    private void initData() {
        for (int i = 0; i < 50; i++) {
            list.add("标签"+(i+i*20));
        }
        MyFlowAdapter adapter=new MyFlowAdapter(this,list);
        mFlow.setAdapter(adapter);
        //点击时的回调方法
        mFlow.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(View view, int position, FlowLayout parent) {
                Toast.makeText(MainActivity.this, "点击", Toast.LENGTH_SHORT).show();
                return true;
            }
        });
        //点击时回调所选中的集合
        mFlow.setOnSelectListener(new TagFlowLayout.OnSelectListener() {
            @Override
            public void onSelected(Set selectPosSet) {
                
            }
        });
        //预先设置选中
        adapter.setSelectedList(1,3,5,7,8,9);
        //选中的下标集合
        Set selectedList = mFlow.getSelectedList();
    }

    private void initView() {
        mFlow = (TagFlowLayout) findViewById(R.id.flow);
    }
}

 

你可能感兴趣的:(框架)