下面的类从不调用 layout-large 文件夹中的布局。也就是下面的 maintabletlayout.xml 文件。我正在使用分辨率为 800x1280 且密度为 160 的 avd。下面的 findViewById() 始终返回 null。有任何想法吗?系统必须具备哪些规范才能访问 layout-large 文件夹?
public class MainActivity extends Activity
{
boolean mTwoPane;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ArrayList<String> subjects=new ArrayList<String>();
subjects.add("Math");
subjects.add("Science");
subjects.add("Art");
if(findViewById(R.id.top_tablet_container)!=null){
mTwoPane=true;
}else{
mTwoPane=false;
}
if(mTwoPane){
setContentView(R.layout.maintabletlayout);
SubjectListFragment top=new SubjectListFragment(subjects,mTwoPane);
getFragmentManager().beginTransaction().add(R.id.list_container, top).commit();
}else{
setContentView(R.layout.mainphonelayout);
SubjectListFragment top=new SubjectListFragment(subjects,mTwoPane);
getFragmentManager().beginTransaction().add(R.id.top_phone_container, top).commit();
}
}
}
mainphonelayout.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/top_phone_container"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
</LinearLayout>
maintabletlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/top_tablet_container"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<RelativeLayout
android:id="@+id/list_container"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="2"
android:layout_toLeftOf="@+id/content_container"
>
</RelativeLayout>
<RelativeLayout
android:id="@id/content_container"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:layout_toRightOf="@id/content_container"
>
</RelativeLayout>
</LinearLayout>
在清单中我也有这个
<supports-screens
android:xlargeScreens="true"
android:largeScreens="true"
android:normalScreens="true"
android:anyDensity="true" />
@nOiAd 有正确的答案。我必须为这两个布局赋予相同的名称,然后使用该名称设置 setContentView()。这样,您可以为适当大小的屏幕设置内容视图,然后 findViewById() 在尝试在大屏幕布局中查找 id 时能够返回非 null。
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<String> subjects=new ArrayList<String>();
subjects.add("Math");
subjects.add("Science");
subjects.add("Art");
if(findViewById(R.id.top_tablet_container)!=null){
mTwoPane=true;
}else{
mTwoPane=false;
}
if(mTwoPane){
SubjectListFragment top=new SubjectListFragment(subjects,mTwoPane);
getFragmentManager().beginTransaction().add(R.id.list_container, top).commit();
}else{
SubjectListFragment top=new SubjectListFragment(subjects,mTwoPane);
getFragmentManager().beginTransaction().add(R.id.top_phone_container, top).commit();
}
}