我试图将动态生成的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>
应该很容易修复,但无法找到任何解决方案。任何帮助将受到高度赞赏:)
答案 0 :(得分:0)
尝试添加:您需要告诉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并在此处充气。
答案 1 :(得分:-1)
你必须提供网格视图column count
,
在你的代码中尝试这个:
gridView.setNumColumns(GridView.AUTO_FIT);
它会根据屏幕尺寸自动对齐项目。