我尝试开发第一个从网络下载图像并在网格视图中显示它们的应用程序。gridview 是主 Activity 的一个片段。下载过程是使用 onCreate 函数中的 AsyncTask 完成的。为了在更改方向时不会再次下载图像,我android:configChanges="orientation|screenSize"
在 Android Manifest 中设置了 。然后 onCreate 函数只调用一次,一切都很好......除了我必须在横向模式下对 gridview 片段的布局进行一些更改。所以我创建了 2 个布局表:fragment_library.xml
和fragment_library_land.xml
在布局/文件夹中。为了使这些更改生效,我尝试使用 onConfigurationChanged 函数手动更改库片段的布局。在运行时,程序评估函数并传入好的情况(纵向或横向),但使用的布局仍然是纵向模式的布局:fragment_library.xml
...
public class LibraryFragment extends Fragment {
public GridView gridview;
private Boolean isImageAdapterPopulated = false;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
GetLibraryTask getLibraryTask = new GetLibraryTask(this);
getLibraryTask.execute(Config.URL + "action=getLibrary");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if (container == null)
return null;
// gridview
View V = inflater.inflate(R.layout.fragment_library, container, false);
gridview = (GridView)V.findViewById(R.id.gridview);
if(this.isImageAdapterPopulated)
this.setGridAdapter();
return V;
}
@Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
inflater.inflate(R.layout.fragment_library_land, null);
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
inflater.inflate(R.layout.fragment_library, null);
}
}
public void setGridAdapter(){
this.isImageAdapterPopulated = true;
gridview.setAdapter(new ImageAdapter(getActivity()));
}
// ...
}
片段库.xml
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:cacheColorHint="@android:color/transparent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="200dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="20dp"
android:stretchMode="columnWidth"
android:gravity="bottom"
/>
fragment_library_land.xml
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:cacheColorHint="@android:color/transparent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="400dp"
android:numColumns="2"
android:verticalSpacing="50dp"
android:horizontalSpacing="50dp"
android:stretchMode="columnWidth"
android:gravity="bottom"
/>
感谢帮助 :)