Android GridView使项目适合各种屏幕大小

ttvkxqim  于 2022-11-20  发布在  Android
关注(0)|答案(2)|浏览(140)

我使用gridvew作为布局来填充我的项目,圆圈按钮,但是我遇到了问题,适合一个大的网格,11 x 11。当我使用更大的屏幕,它适合,但它停止了一半?这是因为我在我的roundbutton.xml中放入的szie吗?在我的手机小屏幕上,它确实适合,并延伸到屏幕的末端。我需要适合屏幕,无论大小为11 x 11?
网格视图布局

<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridView1"
    android:numColumns="11"
    android:gravity="center"
    android:stretchMode="columnWidth"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
</GridView>

item.xml

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="O"
android:id="@+id/grid_item_label"
android:layout_column="1" 
android:background = "@drawable/roundedbutton"/>

roundedbutton.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <solid android:color="#9F2200"/>
    <stroke android:width="2sp" android:color="#fff" />
        <size 
       android:width="5dp"
        android:height="5dp"/>
</shape>

activity_main.java

gridView = (GridView) findViewById(R.id.gridView1);
        customGridAdapter = new CustomGridViewAdapter(this, R.layout.button_item, gridArray);
        gridView.setAdapter(customGridAdapter);

adapter.java

@Override
public View getView(final int position, View convertView, final ViewGroup parent)
    {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rks48beu

rks48beu1#

你必须计算device width and height runtime

int width = devicewidth/11 ;
int height =deviceheight/11 ;

使用此参数时,您必须传入GridView's Adapter

android.widget.AbsListView.LayoutParams parms = new android.widget.AbsListView.LayoutParams(width , height);

用于调整其单元格大小。

ru9i0ody

ru9i0ody2#

将Gridview调整为屏幕大小
onCreate中取rowHeight:
//获取根视图

root = binding.root

//或者可以使用findviewbyid(R.id.root)

view.onGlobalLayout {
            rowHeight =
                root.measuredHeight / currentPageNumberOfRow
            fillView(appsList)
        }

在适配器中:

override fun getView(position: Int, ConvertView: View?, parent: ViewGroup?): View? {
            var mConvertView = ConvertView
            if (layoutInflater == null) {
                layoutInflater =
                    context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as 
                        layoutInflater!!.inflate(R.layout.item_app_shortcut, null)
          }

           if (mConvertView == null) {
                mConvertView =
                layoutInflater!!.inflate(R.layout.item_child_launcher_app, null)
               
        //Add this: 

         mConvertView.layoutParams = AbsListView.LayoutParams(GridView.AUTO_FIT, rowHeight)

            }

不要忘记设置行按钮:

android:layout_width="0dp"
    android:layout_height="0dp"

适合屏幕大小

相关问题