2011-03-01 14 views
0

我有一个显示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> 

回答

0

确定不要在此引用我,但我相信直到某些内容已被绘制时,实际上才会设置宽度,所以getWidth将始终返回0。如果是这样,你知道你想要什么宽度和高度,你可以使用setWidth()和setHeight()提前手动设置宽度和高度...

如果你想要的只是实际的宽度和高度显示屏幕,可以使用...

   Display display = windowManager.getDefaultDisplay(); 
       if (display != null) { 
        this.setHeight(display.getHeight()); 
        this.setWidth(display.getWidth()); 
       } 

与免责声明:我从来没有与画廊合作,如果有更好的,“最佳实践”的方式做你想要什么也不会感到惊讶...

0

我发现了什么问题:在最后一行,在第一次调用parent.getWidth()返回0(因版面没有完成)所以第一个项目不显示...

所以现在的问题是:我怎样才能设置一个画廊项目的宽度作为其父宽度的一小部分?难度是Gallery只接受Gallery.LayoutParams

我现在重新制定了原始问题。

+1

欢迎堆栈溢出!请仅使用* Post answer *按钮来获得实际答案。您应该修改原始问题以添加其他信息。 – Benjol 2011-03-03 14:02:14

+1

请不要在答案中提出另一个问题。只需创建一个新的。 – Will 2011-03-03 14:46:41

-1

我最近遇到了这个问题。设置适配器后,我立即通过在库适配器上调用notifyDataSetChanged()来解决此问题。看起来,更新视图之前,画廊是可见的,所以我没有看到突然改变宽度的任何毛刺。

像这样的事情在onCreate()回调:

Adapter adapter = new Adapter(); 
gallery.setAdapter(adapter); 
adapter.notifyDataSetChanged()