【问题标题】:Dynamic Gridview in Dynamic Tabs动态选项卡中的动态 Gridview
【发布时间】:2014-01-04 21:26:34
【问题描述】:

我试图将动态生成的 gridView 添加到动态生成的 RelativeLayout,并为多个选项卡执行此操作。代码运行正常,但图片似乎放错了位置。我做错了什么?

public View createTabContent(String tag)
{
ArrayList<Item> gridArray = new ArrayList<Item>();
CustomGridViewAdapter customGridAdapter;

RelativeLayout layout = new RelativeLayout(MainHolder);
android.widget.RelativeLayout.LayoutParams params = 
new RelativeLayout.LayoutParams(
    LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    layout.setLayoutParams(params);
    layout.setId(tab_id);
            GridView dynGrid = new GridView(ManageRooms.this);
            dynGrid.setId(someID);
            gridArray.add(new Item(homeIcon,"Home"));
                    ...

customGridAdapter = 
new CustomGridViewAdapter(ManageRooms.this, R.layout.row_grid, gridArray);

dynGrid.setAdapter(customGridAdapter);
layout.addView(dynGrid);
return layout;
}

row_grid.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp" >

<ImageView
    android:id="@+id/item_image"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_marginRight="10dp"
    android:src="@drawable/nfc" >
</ImageView>

<TextView
    android:id="@+id/item_text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dp"
    android:textSize="15sp" >
</TextView>

</LinearLayout>

应该很容易修复,但找不到任何解决方案。任何帮助将不胜感激:)

【问题讨论】:

    标签: android android-layout gridview tabs android-relativelayout


    【解决方案1】:

    尝试添加:您需要告诉 GridView 以适应列:

    dynGrid.setLayoutParams(new ViewGroup.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT));
    
    dynGrid.setNumColumns(GridView.AUTO_FIT);
    dynGrid.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
    dynGrid.setGravity(Gravity.CENTER);
    dynGrid.setColumnWidth(dpToPx(60));
    
    private int dpToPx(int dp)
    {
        float density = getResources().getDisplayMetrics().density;
        return Math.round((float) dp * density);
    }
    

    不过,在 XML 中定义 GridView 并在此处膨胀会更容易。

    【讨论】:

    • 谢谢,这正是我想要的:)
    【解决方案2】:

    你必须给网格视图column count, 在你的代码中试试这个:

    gridView.setNumColumns(GridView.AUTO_FIT);
    

    它会根据屏幕大小自动对齐项目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-09
      • 2020-12-15
      • 1970-01-01
      • 2018-07-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多