要自定義Android瀑布流樣式,可以在布局文件中使用RecyclerView和GridLayoutManager來(lái)實(shí)現(xiàn)瀑布流布局。然后在A(yíng)dapter中自定義Item的布局樣式。
下面是一個(gè)簡(jiǎn)單的示例:
<android.support.v7.widget.RecyclerView
android:id="@+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<String> mData;
public MyAdapter(List<String> data) {
mData = data;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
// 設(shè)置Item的數(shù)據(jù)
holder.textView.setText(mData.get(position));
}
@Override
public int getItemCount() {
return mData.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView textView;
public ViewHolder(View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_view);
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:textSize="16sp"/>
</LinearLayout>
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private MyAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view);
mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL));
List<String> data = new ArrayList<>();
// 添加測(cè)試數(shù)據(jù)
for (int i = 0; i < 50; i++) {
data.add("Item " + i);
}
mAdapter = new MyAdapter(data);
mRecyclerView.setAdapter(mAdapter);
}
}
通過(guò)以上步驟,就可以自定義Android瀑布流樣式了??梢愿鶕?jù)需求自定義Item的布局樣式,設(shè)置RecyclerView的LayoutManager為StaggeredGridLayoutManager來(lái)實(shí)現(xiàn)瀑布流布局。