How to Create a shelfview in Android with TableLayout?






3.40/5 (4 votes)
In this article, we try to make a shelf view show a list of books or newspapers, etc.
Introduction
In this article, we try to make a shelf view show a list of books or newspapers, etc.
Using the Code
- First, main.xml:
In this file, you should use
ScrollView
andTableLayout
for showing a shelf view.<?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
class: InnerTableLayout
add severalHorizontalScroll
equals the number of rows. Also inner anyTableRow
addImage
. Don't forget to set a shelf image for Row's background: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); } } }
Points of Interest
Notice, we make TableRow
and HorizontalScrollView
equal the number of numRow
variable. You can use a Dialog
or Editview
for input value, then create rows equal to that value.