【发布时间】:2017-06-25 13:12:59
【问题描述】:
我有一个 Horizontalscrollview,里面是水平 LinearLayout。 我试图将片段动态添加到线性布局中。虽然我将片段宽度设置为“match_parent”,但片段并未填充屏幕宽度。
这是我的 MainActivity xml 布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="400dp"
android:fillViewport="true"
android:id="@+id/baseScrollView">
<LinearLayout
android:id="@+id/scrollViewLayout"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
</HorizontalScrollView>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnNext"
android:text="Next Page"/>
</LinearLayout>
这是我的 MainActivity 代码
Button btnNext;
CustomHorizontalScrollView baseScrollView;
LinearLayout scrollViewLayout;
boolean isFragment1Added = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnNext = (Button) findViewById(R.id.btnNext);
scrollViewLayout = (LinearLayout) findViewById(R.id.scrollViewLayout);
btnNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(isFragment1Added){
isFragment1Added = false;
addCustomFragment(new Fragment2(), "fragment_2");
}else{
isFragment1Added = true;
addCustomFragment(new Fragment1(), "fragment_1");
}
}
});
}
public void addCustomFragment(Fragment fragmentView, String tag) {
FragmentTransaction viewTransaction = getFragmentManager().beginTransaction();
viewTransaction.add(R.id.scrollViewLayout, fragmentView, tag);
viewTransaction.commit();
}
这里是fragment1.xml。 fragment2 与 fragment1 类似。
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/holo_red_dark"
tools:context="com.uobtravelplanners.horizontalscrollviewtest.Fragment1">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="FRAGMENT 1"
android:textSize="50sp"
android:gravity="center"/>
</FrameLayout>
【问题讨论】:
标签: android