如何在 Android 中使用 TableLayout 创建书架视图?






3.40/5 (4投票s)
在本文中,我们将尝试创建一个书架视图来显示书籍或报纸等列表。
引言
在本文中,我们将尝试创建一个书架视图来显示书籍或报纸等列表。
Using the Code
- 首先,main.xml
在这个文件中,您应该使用
ScrollView
和TableLayout
来显示书架视图。<?xml version="1.0" encoding="utf-8"?> <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/sclView"> <TableLayout android:id="@+id/tblLayout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:padding="0dp"> </TableLayout> </ScrollView>
showShelfView
类:在内部的TableLayout
中添加多个HorizontalScroll
,数量等于行数。 并且在任何内部的TableRow
中添加Image
。 不要忘记为行设置书架背景图片。public class showShelfView extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); int numRow = 4; int numCol = 8; TableLayout tblLayout = (TableLayout) findViewById(R.id.tblLayout); for(int i = 0; i < numRow; i++) { HorizontalScrollView HSV = new HorizontalScrollView(this); HSV.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); TableRow tblRow = new TableRow(this); tblRow.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); tblRow.setBackgroundResource(R.drawable.bookshelf); for(int j = 0; j < numCol; j++) { ImageView imageView = new ImageView(this); imageView.setImageResource(R.drawable.book1); TextView textView = new TextView(this); textView.setText("Java Tester"); textView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); tblRow.addView(imageView,j); } HSV.addView(tblRow); tblLayout.addView(HSV, i); } } }
关注点
请注意,我们使 TableRow
和 HorizontalScrollView
的数量等于 numRow
变量。 您可以使用 Dialog
或 Editview
来输入值,然后创建与该值相等的行数。