我有一个显示TextViews的图库。显示时,第一项不显示。这是因为parent.getWidth()在第一次调用时返回0。Android Gallery第一项不显示:parent.getWidth返回0
那么如何将项目的宽度设置为其父库的宽度的一小部分呢?
下面是代码:
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;
}
}
}
布局/ 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>
欢迎堆栈溢出!请仅使用* Post answer *按钮来获得实际答案。您应该修改原始问题以添加其他信息。 – Benjol 2011-03-03 14:02:14
请不要在答案中提出另一个问题。只需创建一个新的。 – Will 2011-03-03 14:46:41