【发布时间】:2016-07-10 18:44:44
【问题描述】:
我有 2 个片段:ls_fragment 和 pm_fragment。我试图在纵向模式下显示pm_fragment,在横向模式下显示两个片段,但我的代码不能正常工作。在纵向模式下它可以工作并显示pm_fragment,但在横向模式下它只显示一个片段(lm_fragment)。
MainActivity 代码:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
Configuration config = getResources().getConfiguration();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
LM_Fragment lm_fragment = new LM_Fragment();
PM_Fragment pm_fragment = new PM_Fragment();
/**
* Check the device orientation and act accordingly
*/
if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
/**
* Landscape mode of the device
*/
fragmentTransaction.replace(android.R.id.content, lm_fragment);
fragmentTransaction.add(android.R.id.content, pm_fragment);
//fragmentTransaction.replace(android.R.id.content, pm_fragment);
}else{
/**
* Portrait mode of the device
*/
fragmentTransaction.replace(android.R.id.content, pm_fragment);
}
fragmentTransaction.commit();
}
}
和LM_Fragment 类(看起来像PM_Fragment 类):
public class LM_Fragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
/**
* Inflate the layout for this fragment
*/
return inflater.inflate(
R.layout.lm_fragment, container, false);
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<framelayout
android:name="com.example.myfragments.LM_Fragment"
android:id="@+id/lm_fragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<framelayout
android:name="com.example.myfragments.PM_Fragment"
android:id="@+id/pm_fragment"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
lm_fragment.xml(看起来像 pm_fragment.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#7bae16">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/landscape_message"
android:textColor="#000000"
android:textSize="20px" />
<!-- More GUI components go here -->
</LinearLayout>
如何在横向中显示两个片段?
【问题讨论】:
-
使用 FrameLayout 代替 Fragment 并从 cs 文件中替换片段容器中的片段
-
可能是因为重量。尝试通过在 LinearLayout 中添加 weightsum=1 并将
android:layout_weight.3 给第一个 Fragment 和 .7 给第二个 -
由于权重问题并试图使其正确,您使用RelativeLayout并为每个FrameLayout将屏幕分成相等的两半不是更好吗?