I have a Horizontalscrollview inside which is horizontal LinearLayout. I tried to add Fragments dynamically into the Linear Layout. Although I set my fragment width as "match_parent", the fragment is not filling in the screen width.
Here's my xml layouts for MainActivity
<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>
Here's my code for 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();
}
Here's fragment1.xml. fragment2 is similar to 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>