Skip to content

Instantly share code, notes, and snippets.

@cattaka
Last active May 4, 2016 06:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cattaka/f4232f4e0fea2f8626f3 to your computer and use it in GitHub Desktop.
Save cattaka/f4232f4e0fea2f8626f3 to your computer and use it in GitHub Desktop.
/**
* These codes are licensed under CC0.
*/
public class FlexibleListView extends LinearLayout {
public interface OnItemClickListener {
void onItemClick(FlexibleListView parent, View view, int position, long id);
}
private RecyclerView.AdapterDataObserver mAdapterDataObserver = new RecyclerView.AdapterDataObserver() {
@Override
public void onChanged() {
super.onChanged();
refleshViews();
}
};
private RecyclerView.Adapter mAdapter;
private OnItemClickListener mOnItemClickListener;
public FlexibleListView(Context context) {
super(context);
}
public FlexibleListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FlexibleListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public RecyclerView.Adapter getAdapter() {
return mAdapter;
}
public void setAdapter(RecyclerView.Adapter adapter) {
if (mAdapter != null) {
mAdapter.unregisterAdapterDataObserver(mAdapterDataObserver);
}
mAdapter = adapter;
mAdapter.registerAdapterDataObserver(mAdapterDataObserver);
refleshViews();
}
private void refleshViews() {
removeAllViews();
for (int i = 0; i < mAdapter.getItemCount(); i++) {
int itemViewType = mAdapter.getItemViewType(i);
RecyclerView.ViewHolder vh = mAdapter.createViewHolder(this, itemViewType);
mAdapter.onBindViewHolder(vh, i);
FrameLayout.LayoutParams params;
if (getOrientation() == VERTICAL) {
params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
} else {
params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
}
vh.itemView.setLayoutParams(params);
vh.itemView.setClickable(true);
final int position = i;
vh.itemView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(FlexibleListView.this, v, position, -1);
}
}
});
FrameLayout frame = new FrameLayout(getContext());
if (getOrientation() == VERTICAL) {
frame.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
} else {
frame.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
frame.addView(vh.itemView);
this.addView(frame);
}
}
public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
mOnItemClickListener = onItemClickListener;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment