如何使用android RecyclerView创建自动调整网格布局

时间:2017-12-01 04:52:28

标签: android android-recyclerview recycler-adapter recyclerview-layout

how to achieve this kind of gridlayout

我想使用RecyclerView创建自动调整列,例如上面的图像网格布局。

1 个答案:

答案 0 :(得分:2)

enter image description here最后,我使用FlexboxLayout

完成了它

/// Gradle import /// 编译com.google.android:flexbox:0.3.1'

to_string()

///// rounded_corner_yellow.xml

public class MainActivity extends AppCompatActivity {

    List<String> list_text=new ArrayList<>();
    FlexboxLayout container;

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

        container=findViewById(R.id.v_container);
        list_text.add("Avik");
        list_text.add("Rocky bolboa");
        list_text.add("Master");
        list_text.add("avhihsked");
        list_text.add("Prem chopra");
        list_text.add("Rambo");
        list_text.add("Piyali");
        list_text.add("Sheha Singh");
        list_text.add("Sheha Sarker");
        list_text.add("Supriya");
        list_text.add("Manish Singh");
        list_text.add("Chacha ji");
        list_text.add("DEbarun da");
        list_text.add("Asaduk da");
        list_text.add("Sunidhi chauhan");
        list_text.add("Shreya");
        list_text.add("Sourav mitra");

        inflatelayout();

    }

    private void inflatelayout() {
        LinearLayout.LayoutParams buttonLayoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        buttonLayoutParams.setMargins(5,5,5,5);
        for(int i=0;i<list_text.size();i++){
            final TextView tv = new TextView(getApplicationContext());
            tv.setText(list_text.get(i));
            tv.setHeight(100);
            tv.setTextSize(16.0f);
            tv.setGravity(Gravity.CENTER);
            tv.setTextColor(Color.parseColor("#000000"));
            tv.setBackground(getResources().getDrawable(R.drawable.rounded_corner_yellow));
            tv.setId(i + 1);
            tv.setLayoutParams(buttonLayoutParams);
            tv.setTag(i);
            tv.setPadding(20, 10, 20, 10);
            container.addView(tv);
        }

    }
}

/////// activity_main.xml中//////

    <?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <stroke
        android:width="1dp"
        android:color="@color/colorAccent" />

    <solid android:color="@android:color/transparent" />

    <padding
        android:left="10dp"
        android:right="10dp"
        android:top="3dp" />

    <corners android:radius="20dp" />
</shape>