我的potrait和横向模式有两种布局。
在potrait中我有一个ListView,在Landscape中我有一个GridView。
布局/ myxml.xml
<ListView
android:id="@+id/android:list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/getdata"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:listSelector="@drawable/list_selector" />
布局脊/ myxml.xml
<com.etsy.android.grid.StaggeredGridView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/grid_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:item_margin="8dp"
app:column_count="3" />
Iam在我的课程中扩展这些布局,扩展了片段。我想根据方向对两个视图进行充气。
这就是我所做的: -
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
Configuration config;
if(config.orientation == Configuration.ORIENTATION_PORTRAIT)
{
View vi = inflater.inflate(R.layout.myxml, container, false);
newsList = (ListView)vi.findViewById(android.R.id.list); //Error Here
itemsAdapter = new LazyAdapter(myContext, getList );
newsList.setAdapter(itemsAdapter);
}
else if(config.orientation ==Configuration.ORIENTATION_LANDSCAPE)
{
View vi = inflater.inflate(R.layout.myxml, container, false);
mGridView =(StaggeredGridView)vi.findViewById(R.id.grid_view);
stagAdaper = new StaggeredAdapter(myContext, android.R.layout.simple_list_item_1, getList);
mGridView.setAdapter(stagAdaper);
}
}
但是我收到了一个错误: -
Caused by: java.lang.NullPointerException
06-09 10:44:34.369: E/AndroidRuntime(2680): at mypackage.class(HomeFragment.java:220)
答案 0 :(得分:0)
问题是Configuration config;
为空,因为你没有实例化它。
查找landscape
或portrait
模式的另一种方法是实例化StaggeredGridView
和ListView
并检查其中一个是否为空。
示例:强>
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View vi = inflater.inflate(R.layout.myxml, container, false);
newsList = (ListView) vi.findViewById(android.R.id.list); // Error Here
mGridView = (StaggeredGridView) vi.findViewById(R.id.grid_view);
if (mGridView == null) {
itemsAdapter = new LazyAdapter(myContext, getList);
newsList.setAdapter(itemsAdapter);
} else {
stagAdaper = new StaggeredAdapter(myContext,
android.R.layout.simple_list_item_1, getList);
mGridView.setAdapter(stagAdaper);
}
}
关于:强>
上述代码的作用是检查mGridView
是否为空,如果是,那么您当前处于portrait
模式,否则您处于landscape
模式
答案 1 :(得分:0)
这里没有启动Configuration变量。像这样更改代码:
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
..Your code for LANDSCAPE view ....
}else if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
..Your code for PORTRAIT view .....
}