要自定義Android瀑布流樣式,可以在布局文件中使用RecyclerView和GridLayoutManager來實現瀑布流布局。然后在Adapter中自定義Item的布局樣式。
下面是一個簡單的示例:
<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) {
// 設置Item的數據
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<>();
// 添加測試數據
for (int i = 0; i < 50; i++) {
data.add("Item " + i);
}
mAdapter = new MyAdapter(data);
mRecyclerView.setAdapter(mAdapter);
}
}
通過以上步驟,就可以自定義Android瀑布流樣式了。可以根據需求自定義Item的布局樣式,設置RecyclerView的LayoutManager為StaggeredGridLayoutManager來實現瀑布流布局。