I have a Gallery displaying TextViews. When it’s shown, the 1st item is not displayed. This is because parent.getWidth() returns 0 at the first call.
So how can I set the item’s width to be a fraction of its parent gallery’s width?
Here is the code:
public class GalleryActivity extends Activity {
private Gallery gallery;
public void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.gallery);
gallery = (Gallery) findViewById (R.id.gallery);
gallery.setAdapter (new Adapter ());
}
private class Adapter extends BaseAdapter {
private String[] items = {"A", "B", "C", "D", "E", "F"};
public int getCount () {
return items.length;
}
public Object getItem (int position) {
return items[position];
}
public long getItemId (int position) {
return position;
}
public View getView (int position, View convertView, ViewGroup parent) {
TextView view = new TextView (GalleryActivity.this);
view.setText (getItem (position).toString ());
view.setBackgroundColor (Color.GRAY);
view.setGravity (Gravity.CENTER);
view.setLayoutParams (new Gallery.LayoutParams (parent.getWidth () / 3,
LayoutParams.FILL_PARENT));
return view;
}
}
}
layout/gallery.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Gallery android:id="@+id/gallery" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_weight="1"
android:scrollbars="horizontal" android:spacing="1dp"></Gallery>
<TextView android:layout_width="fill_parent" android:layout_height="wrap_content"
android:layout_weight="3"></TextView>
</LinearLayout>
OK don’t quote me on this but I believe the width won’t actually get set until some contents have been drawn, so getWidth will always return 0 before that. If so, and you know what width and height you want anyway you can manually set width and height ahead of time with setWidth() and setHeight()…
If all you want is the width and height of the actually display screen, you can use…
And disclaimer: I’ve never worked with Galleries before and wouldn’t be surprised if there’s a better, “best practice” way to do what you’re trying…