我試圖根據設備的屏幕大小動態選擇視圖。對於大多數設備我想要一個列表視圖,但對於xlarge屏幕大小,我想要一個網格視圖。我如何動態地分配使用android的視圖?
我已經在兩個獨立的library_list.xml文件中創建了佈局,一個在佈局文件夾中,另一個在layout-xlarge文件夾中。
列表視圖看起來像:
ListView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/library_list" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" android:visibility="gone" android:textColor="@android:color/black" android:background="@android:color/transparent" android:cacheColorHint="#00000000"
和網格視圖的樣子:
GridView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/library_list" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" android:columnWidth="@dimen/library_column_width" android:numColumns="auto_fit" android:verticalSpacing="10dp" android:horizontalSpacing="@dimen/library_item_horizontal_spacing" android:stretchMode="columnWidth" android:textColor="@android:color/black" android:background="@android:color/transparent" android:cacheColorHint="#00000000"
我的問題是,在我的Java代碼,我需要聲明一個公共變量持有該視圖,然後動態分配它。
我想聲明的AbsListView(我不能宣佈的GridView或ListView,因爲我不知道它是哪一個,直到運行時)是這樣的:
public static AbsListView libraryList;
...
libraryList = findViewById(R.id.library_list);
其上的華碩Eee變壓器廠平板電腦,但不是三星Galaxy或HTC的願望(它只是崩潰,登錄貓不告訴我任何東西)。是宣佈一個AbsListView正確的方式來做到這一點,或者我錯過了什麼?
我已閱讀http://developer.android.com/guide/practices/screens_support.html但這似乎沒有幫助我的問題。這似乎應該是一個相當普遍的情況,但我無法在任何地方找到答案。
謝謝!
你爲什麼要聲明libraryList爲'static'?那可能是你的問題。例如,參見http://android-developers.blogspot.com/2009/01/avoiding-memory-leaks.html。 –
好的,我會研究一下,謝謝。至於在Java中使用視圖是定義一個AbsListView,當你不知道什麼類型的視圖時,你會使用正確的方式做到這一點? – odiggity
因爲GridView和ListView都是從AbsListView派生的,所以它應該沒有'static'。如果沒有,除了如何定義'libraryList'這個問題。 –