I have added a full-screen map fragment to one of my three tabbed fragments. Everything works great apart from an issue I'm experiencing with switching between the tabs.
Each time I switch from the fragment with the map, to one of the other fragments, I get a black screen for like 0.2 seconds. It seems to be a similar issue to the problems with scrolling in an activity with a map fragment.
I've tried adding a transparent view other the top of the map as others have suggested, but it didn't help.
This is my xml:
<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"
tools:context=".ParkMapFragment">
<fragment
android:id="#+id/fullParkMap"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
And this is my code:
public class ParkMapFragment extends Fragment {
public ParkMapFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_map, container, false);
}
#Override
public void onStart(){
super.onStart();
getActivity().setTitle("Map");
}
#Override
public void onDestroyView() {
super.onDestroyView();
SupportMapFragment mapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.fullParkMap);
if (mapFragment != null) {
getFragmentManager().beginTransaction().remove(mapFragment).commit();
}
}
}
Anyone have any suggestions?
Check if the view is null, and if not, remove it from its parent view. That way, you won't see the black screen.
Try the code below.
Fragment:
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class ExhibhitionMap2 extends Fragment implements OnMapClickListener,OnMarkerClickListener{
View v;
private GoogleMap mMap;
FragmentManager fragmentManager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// android = inflater.inflate(R.layout.activity_exhibhition_map, container, false);
if (v != null) {
ViewGroup parent = (ViewGroup) v.getParent();
if (parent != null)
parent.removeView(v);
}
try {
v = inflater.inflate(R.layout.activity_exhibhition_map, container, false);
} catch (InflateException e) {
/* map is already there, just return view as it is */
}
setUpMapIfNeeded();
return v;
}
/***** Sets up the map if it is possible to do so *****/
public void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
mMap = ((SupportMapFragment) this.getChildFragmentManager().findFragmentById(R.id.map2)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null)
{
mMap.setOnMapClickListener(this);
mMap.setOnMarkerClickListener((OnMarkerClickListener) this);
MarkerOptions marker = new MarkerOptions().position(new LatLng(36.011513,-115.174853))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
.title("P-1");
MarkerOptions marker01 = new MarkerOptions().position(new LatLng(36.111513,-115.204853))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
.title("P-2");
MarkerOptions marker02 = new MarkerOptions().position(new LatLng(36.051513,-115.154853))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
.title("P-3");
MarkerOptions marker03 = new MarkerOptions().position(new LatLng(36.057513,-115.344853))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
.title("P-4");
MarkerOptions marker1 = new MarkerOptions().position(new LatLng(36.081513,-115.224853))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN))
.title("F-1");
MarkerOptions marker2 = new MarkerOptions().position(new LatLng(36.051513,-115.334853))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN))
.title("F-2");
MarkerOptions marker3 = new MarkerOptions().position(new LatLng(36.101513,-115.124853))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN))
.title("F-1");
MarkerOptions marker4 = new MarkerOptions().position(new LatLng(36.031513,-115.154853))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN))
.title("F-2");
MarkerOptions marker5 = new MarkerOptions().position(new LatLng(36.081513,-115.194853))
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN))
.title("F-2");
mMap.addMarker(marker);
mMap.addMarker(marker01);
mMap.addMarker(marker02);
mMap.addMarker(marker03);
mMap.addMarker(marker1);
mMap.addMarker(marker2);
mMap.addMarker(marker3);
mMap.addMarker(marker4);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(36.051513,-115.174853), 10.0f));
}
}
}
#Override
public boolean onMarkerClick(Marker marker) {
/*Toast.makeText(getActivity(),
"" + marker.getTitle(), Toast.LENGTH_LONG)
.show();*/
marker.showInfoWindow();
return false;
}
#Override
public void onMapClick(LatLng arg0) {
// TODO Auto-generated method stub
}
public void onDestroy() {
super.onDestroy();
}
}
XML:
<RelativeLayout 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"
tools:context="com.istride.mmps.ContactActivity" >
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tableLayout1"
android:visibility="gone"
android:layout_margin="10dp" >
<TextView
android:id="#+id/tv_Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="Bharati Vidyapeeth University's"
android:textColor="#color/black_text_color"
android:textSize="#dimen/Large_Size" />
<TextView
android:id="#+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_below="#+id/tv_Title"
android:text="Department of Information Technology and Management "
android:textColor="#color/black_text_color"
android:textSize="#dimen/small_size" />
<View
android:id="#+id/view2"
android:layout_width="fill_parent"
android:layout_height="2dp"
android:layout_below="#+id/tv"
android:layout_marginTop="10dp"
android:background="#color/blue_background" />
<RelativeLayout
android:id="#+id/relative"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/view2"
android:layout_marginTop="10dp"
android:background="#color/gray_home">
<TextView
android:id="#+id/textVi1"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/tv_add"
android:layout_alignParentTop="true"
android:background="#color/blue_background"
android:paddingBottom="2dp"
android:paddingLeft="8dp"
android:paddingRight="13dp"
android:paddingTop="2dp"
android:gravity="center_vertical"
android:text="ADDRESS "
android:textColor="#color/white_text_color"
android:textSize="#dimen/Medium_size"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/textVi1"
android:paddingBottom="2dp"
android:paddingTop="2dp"
android:text="2nd Floor, Architecture Building, Bharati Vidyapeeth Campus, Dhankawadi, Pune-411043"
android:textColor="#color/black_text_color"
android:textSize="#dimen/Medium_size" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/relativeLayout_call"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/relative"
android:layout_marginTop="10dp"
android:background="#color/gray_home">
<TextView
android:id="#+id/textView1"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/tv_school_office_num"
android:layout_alignParentTop="true"
android:background="#color/blue_background"
android:paddingBottom="2dp"
android:paddingLeft="8dp"
android:paddingRight="13dp"
android:paddingTop="2dp"
android:text="PHONE "
android:gravity="center_vertical"
android:textColor="#color/white_text_color"
android:textSize="#dimen/Medium_size"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_school_office_num"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="5dp"
android:layout_toRightOf="#+id/textView1"
android:layout_toLeftOf="#+id/imageView2"
android:textColor="#color/black_text_color"
android:paddingTop="2dp"
android:textSize="#dimen/Medium_size"
android:paddingBottom="2dp"
android:text="+91 989898989 asasa asas asasas ass sdsd asas asas ass assas asas ass " />
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="3dp"
android:src="#drawable/ic_call" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/relativeLayout_Email"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/relativeLayout_call"
android:layout_marginTop="10dp"
android:background="#color/gray_home">
<TextView
android:id="#+id/tex1"
android:layout_width="90dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView1"
android:layout_alignParentTop="true"
android:background="#color/blue_background"
android:gravity="center_vertical"
android:paddingBottom="2dp"
android:paddingLeft="8dp"
android:paddingRight="13dp"
android:paddingTop="2dp"
android:text="EMAIL "
android:textColor="#color/white_text_color"
android:textSize="#dimen/Medium_size"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_school_office_email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/imageView1"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp"
android:gravity="center_vertical"
android:layout_toRightOf="#+id/tex1"
android:textColor="#color/black_text_color"
android:paddingTop="2dp"
android:paddingBottom="2dp"
android:textSize="#dimen/Medium_size"
android:text="principal.mmei#eternalmewar.in" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="3dp"
android:src="#drawable/ic_email" />
</RelativeLayout>
</RelativeLayout>
<fragment
android:id="#+id/map2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentRight="true"
android:layout_marginTop="10dp"
class="com.google.android.gms.maps.SupportMapFragment"
android:background="#color/gray_color"
android:paddingBottom="5dp"
android:layout_above="#+id/footer"
android:textSize="#dimen/small_size" />
<RelativeLayout
android:id="#+id/footer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="10dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" >
<TextView
android:id="#+id/blue"
android:layout_width="20dp"
android:layout_height="20dp"
android:background="#0000FF"
android:gravity="center"
android:layout_margin="10dp"
android:textColor="#color/black_text_color"
android:textSize="#dimen/small_size"
android:textStyle="bold" />
<TextView
android:id="#+id/parking"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/blue"
android:layout_alignTop="#+id/blue"
android:layout_alignBottom="#+id/blue"
android:gravity="center_vertical"
android:text="Parking"
android:textColor="#color/black_text_color"
android:textSize="#dimen/Medium_size"
android:textStyle="bold" />
<TextView
android:id="#+id/cyc"
android:layout_width="20dp"
android:layout_height="20dp"
android:background="#00FFFF"
android:gravity="center"
android:layout_margin="10dp"
android:layout_toRightOf="#+id/parking"
android:textColor="#color/black_text_color"
android:textSize="#dimen/small_size"
android:textStyle="bold" />
<TextView
android:id="#+id/footer2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/cyc"
android:layout_alignTop="#+id/cyc"
android:layout_alignBottom="#+id/cyc"
android:gravity="center_vertical"
android:text="Food"
android:textColor="#color/black_text_color"
android:textSize="#dimen/Medium_size"
android:textStyle="bold" />
</RelativeLayout>
</RelativeLayout>
#Override
public void onDestroyView() {
super.onDestroyView();
SupportMapFragment mapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.fullParkMap);
if (mapFragment != null) {
getFragmentManager().beginTransaction().remove(mapFragment).commit();
}
}
right here you are removing the fragment without replacing it. I would use .replace instead with a new fragment.
Something like this:
getFragmentManager().beginTransaction().replace(R.id.your_placeholder, new CustomFragment(), "cstmFragID").commit();
i would recommend you to use MapView instead of SupportFragment to avoid nested fragment For details answer look at the following post
Should I use MapView or MapFragment
Now your ParkFragment be look like
MapFragment.java
public class MapFragment extends Fragment implements OnMapReadyCallback {
private MapView mMapView;
private GoogleMap mGoogleMap;
public MapFragment() {
// Required empty public constructor
}
public static MapFragment newInstance() {
MapFragment fragment = new MapFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_map, container, false);
mMapView = (MapView) rootView.findViewById(R.id.map);
mMapView.onCreate(savedInstanceState);
mMapView.getMapAsync(this);
return rootView;
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onPause() {
mMapView.onPause();
super.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
#Override
public void onMapReady(GoogleMap googleMap) {
googleMap.getUiSettings().setZoomControlsEnabled(true);
}
}
fragment_map.xml
<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">
<com.google.android.gms.maps.MapView
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
The problem is possibly because it is recreating Fragment which causes the Black screen. If you are using ViewPager then you can use
// Note that you must set adapter before this line otherwise it can cause NullPointerException
// Or add null check on getAdapter if required
mViewPager.setOffscreenPageLimit(mViewPager.getAdapter().getCount());
It will force ViewPager not to create Fragments second time. For sure, it takes more memory but I believe it is more efficient when using less tabs so I normally do this to avoid recreation of fragments.
Secondly I would suggest to remove these lines from onDestroy:
SupportMapFragment mapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.fullParkMap);
if (mapFragment != null) {
getFragmentManager().beginTransaction().remove(mapFragment).commit();
}
And overcome this issue by updating onCreateView as this:
private View mView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (mView == null) {
mView = inflater.inflate(R.layout.fragment_map, container, false);
}
return mView;
}
It will not inflate layout every time so you will not face Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment issue.
But make sure you pass false in attachToRoot (last argument of inflater.inflate) otherwise you may get exceptions like The specified child already has a parent
Last thing, when using MapFragment inside Fragment, or in other words, when using Nested Fragments, I would recommend use getChildFragmentManager() instead of getFragmentManager() to avoid unexpected issues.
Because as the documentation says:
getFragmentManager: Return the FragmentManager for interacting with fragments associated with this fragment's activity. Note that this will be non-null slightly before getActivity(), during the time from when the fragment is placed in a FragmentTransaction until it is committed and attached to its activity. If this Fragment is a child of another Fragment, the FragmentManager returned here will be the parent's getChildFragmentManager().
getChildFragmentManager: Return a private FragmentManager for placing and managing Fragments inside of this Fragment.
This is a known issue. For the meantime, you may use work around by placing another view on top of the map that uses a background color that is the same as its container is. This makes the map smoothly come in once its ready.
SupportMapFragment mapFragment = SupportMapFragment.newInstance(new GoogleMapOptions().zOrderOnTop(true));
As you always replace fragment then map gets always created then workaround for this would be load your map fragment only once, rest of the time just show/hide your fragment (as if you are showing tabbed fragments).
Have you tried to hide and show fragment (instead of remove/adding it) ?
private FragmentA fragmentA;
private FragmentB fragmentB;
private FragmentC fragmentC;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
fragmentA = FragmentA.newInstance("foo");
fragmentB = FragmentB.newInstance("bar");
fragmentC = FragmentC.newInstance("baz");
}
}
In your case you might change it to ParkMapFragment etc.
protected void displayFragmentA() {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (fragmentA.isAdded()) { // if the fragment is already in container
ft.show(fragmentA);
} else { // fragment needs to be added to frame container
ft.add(R.id.flContainer, fragmentA, "A");
}
// Hide fragment B
if (fragmentB.isAdded()) { ft.hide(fragmentB); }
// Hide fragment C
if (fragmentC.isAdded()) { ft.hide(fragmentC); }
// Commit changes
ft.commit();
}
source: https://github.com/codepath/android_guides/wiki/Creating-and-Using-Fragments
Try this inside createView:
if (v != null) {
ViewGroup parent = (ViewGroup) v.getParent();
if (parent != null)
parent.removeView(v);
}
You should make the transition of fragments by this way:
Fragment fragment = new YourFragmentToShow();
getFragmentManager().beginTransaction().replace(R.id.content_frame, fragment, TAG).setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE).commit();
With TRANSIT_FRAGMENT_FADE Fragment should simply fade in or out; that is, no strong navigation associated with it except that it is appearing or disappearing for some reason.
Use it when you replace the fragment with map by another fragment, in other case I recomend the common use, without (.setTransition...):
Fragment fragment = new YourFragmentToShow();
getFragmentManager().beginTransaction().replace(R.id.content_frame, fragment, TAG).commit();
Related
I have created three swiping splash screen layout fragments over an splash screen activity, and I want to change the color of the status bar for each fragment which matches the color of the fragment body.
My Code is
Fragment_a.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FragmentA">
<ImageView
android:id="#+id/circle1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/circle_filled"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginTop="16dp"
android:layout_marginStart="16dp"/>
<ImageView
android:id="#+id/circle2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/circle_blank"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toEndOf="#id/circle1"
android:layout_marginTop="16dp"
android:layout_marginStart="8dp"/>
<ImageView
android:id="#+id/circle3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/circle_blank"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toEndOf="#id/circle2"
android:layout_marginTop="16dp"
android:layout_marginStart="8dp"/>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginEnd="32dp"
android:text="Skip"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_marginTop="120dp"
android:src="#drawable/ic_browsing"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.496"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="68dp"
android:text="Move"
android:textSize="20dp"
app:layout_constraintStart_toStartOf="#+id/imageView2"
app:layout_constraintTop_toBottomOf="#+id/imageView2" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Step by Step"
app:layout_constraintTop_toBottomOf="#id/textView2"
app:layout_constraintStart_toStartOf="#id/textView2"
android:layout_marginTop="6dp"
android:textSize="35sp"
android:textStyle="bold"
android:textColor="#color/black"/>
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a dummy text.\nMade for testing purpose!"
android:textSize="20sp"
android:layout_marginTop="10dp"
app:layout_constraintStart_toStartOf="#+id/textView3"
app:layout_constraintTop_toBottomOf="#+id/textView3" />
</androidx.constraintlayout.widget.ConstraintLayout>
FragmentA.java
package in.pratikchakraborty.liquidswipe;
import android.os.Build;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
public class FragmentA extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public FragmentA() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment FragmentA.
*/
// TODO: Rename and change types and number of parameters
public static FragmentA newInstance(String param1, String param2) {
FragmentA fragment = new FragmentA();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_a, container, false);
if (Build.VERSION.SDK_INT >= 21) {
Window window = this.getActivity().getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(this.getResources().getColor(R.color.white));
}
}
}
I am getting this error while building the project.
AndroidStudioProjects\LiquidSwipe\app\src\main\java\in\pratikchakraborty\liquidswipe\FragmentA.java:65: error: unreachable statement
if (Build.VERSION.SDK_INT >= 21) {
^
You are writing the code for change status color after the return statement so it is not reachable please try below
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_a, container, false);
if (Build.VERSION.SDK_INT >= 21) {
Window window = this.getActivity().getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(this.getResources().getColor(R.color.white));
}
return view;
}
I have set up a RecyclerView adapter with ViewPager in an activity namely TvShowEpisodeDetails , it works well but there is one issue, the Layout of RecyclerView is fixed while scrolling up and down in the Fragment(TvShowEpisodeDetailsFragment). But I want it to scroll with them.
The RecyclerView and ViewPager are both set inside viewpager_with_toolbar_overlay.xml Layout , and both has been settup in The Activity.
TvShowEpisodeDetailsFragment is the fragment class which belongs to activity class TvShowEpisodeDetails , the fragment creates as many episodes as a TV Show season can offer.
And off course this issue will be gone if I set RecyclerView adapter inside fragment, but I will get non-fixable highlighting and scrolling issues , that is why I set it inside the activity because it does not give those issues.
I need to make it work somehow inside the activity.
My goal is that RecyclerView and ViewPager has to be in the same layout XML file and they both must either be in the activity or fragment class
Is it possible to make the RecyclerView scroll with rest of the fragment layouts?
or
Is it possible to do it programmatically?
Here is the activity
public class TvShowEpisodeDetails extends MizActivity{
#Override
protected int getLayoutResource() {
return R.layout.viewpager_with_toolbar_overlay;
}
#Override
public void onCreate(Bundle savedInstanceState) {
mBus = MizuuApplication.getBus();
super.onCreate(savedInstanceState);
// Set theme
setTheme(R.style.Mizuu_Theme_NoBackground);
// setting episodeslist
final ArrayList<PlanetModel> episodeslist = new ArrayList<>();
for(TvShowEpisode e : mEpisodes){
episodeslist.add(new PlanetModel(e.mEpisode));
}
// setting RecyclerView
mEpisodesList = (RecyclerView) findViewById(R.id.episodesLIST);
// Setting LinearLayoutManager
LinearLayoutManager layoutManager
= new LinearLayoutManager(this.getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
//mEpisodesList.setLayoutManager(new LinearLayoutManager(mContext));
mEpisodesList.setLayoutManager(layoutManager);
// Setting RecyclerView Adapter
PlanetAdapter.OnItemClickListener indicatorCallback = new PlanetAdapter.OnItemClickListener() {
#Override
public void onItemClick(String item) {
SharedPreferences getPref = getContext().getSharedPreferences("PlanetAdapter", Context.MODE_PRIVATE);
int pos = getPref.getInt("newPosition", 0);
mViewPager.setCurrentItem(pos,false);
}
};
final PlanetAdapter planetAdapter = new PlanetAdapter(episodeslist,indicatorCallback);
mEpisodesList.setAdapter(planetAdapter);
// Setting ViewPager
mViewPager = (ViewPager) findViewById(R.id.awesomepager);
mViewPager.setAdapter(new TvShowEpisodeDetailsAdapter(getSupportFragmentManager()));
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
planetAdapter.setSelectedIndex(position);
planetAdapter.notifyDataSetChanged();
mEpisodesList.smoothScrollToPosition(position);
//mEpisodesList.scrollToPosition(position);
for (int i=0; i<episodeslist.size(); i++)
{
episodeslist.get(i).setPlanetSelected(false);
}
episodeslist.get(position).setPlanetSelected(true);
ViewUtils.updateToolbarBackground(TvShowEpisodeDetails.this, mToolbar, 0, mEpisodes.get(position).getTitle(), Color.TRANSPARENT);
}
});
if (savedInstanceState != null) {
mViewPager.setCurrentItem(savedInstanceState.getInt("tab", 0));
} else {
for (int i = 0; i < mEpisodes.size(); i++) {
if (mEpisodes.get(i).getSeason().equals(MizLib.addIndexZero(mSeason)) && mEpisodes.get(i).getEpisode().equals(MizLib.addIndexZero(mEpisode))) {
mViewPager.setCurrentItem(i);
break;
}
}
}
}
}
viewpager_with_toolbar_overlay
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v4.view.ViewPager
android:id="#+id/awesomepager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="#+id/progressbar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#068006"
android:layout_marginTop="450dp"
>
<android.support.v7.widget.RecyclerView
android:id="#+id/episodesLIST"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:scrollbars="horizontal" />
</LinearLayout>
<include layout="#layout/toolbar_layout" />
</FrameLayout>
Here is the XML layout of the fragment which is inflated in onCreateView of the fragment class
episode_details.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/abc_input_method_navigation_guard">
<com.miz.views.ObservableScrollView
android:id="#+id/observableScrollView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/episodePhoto"
android:layout_width="match_parent"
android:layout_height="#dimen/backdrop_portrait_height"
android:scaleType="centerCrop"
android:src="#drawable/bg" />
<com.melnykov.fab.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/episodePhoto"
android:layout_alignParentEnd="false"
android:layout_alignParentRight="true"
android:layout_marginTop="#dimen/content_details_fab_negative_margin"
android:layout_marginRight="#dimen/content_details_baseline_margin"
android:src="#drawable/ic_play_arrow_white_36dp"
app:fab_colorNormal="#666"
app:fab_type="mini" />
<LinearLayout
android:id="#+id/linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/fab"
android:layout_marginLeft="#dimen/content_details_baseline_margin"
android:layout_marginTop="#dimen/content_details_title_margin_top"
android:layout_marginRight="#dimen/content_details_baseline_margin"
android:layout_toLeftOf="#+id/fab"
android:orientation="vertical">
<TextView
android:id="#+id/movieTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="3"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_title" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/content_details_very_small_margin"
android:layout_marginBottom="#dimen/content_details_baseline_margin"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_subheader"
android:textStyle="bold|italic" />
</LinearLayout>
</RelativeLayout>
<LinearLayout
android:id="#+id/details_area"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#666"
android:baselineAligned="false"
android:elevation="1dp"
android:minHeight="#dimen/content_details_large_margin"
android:orientation="horizontal"
android:paddingLeft="#dimen/content_details_baseline_margin"
android:paddingTop="#dimen/content_details_small_margin"
android:paddingRight="#dimen/content_details_baseline_margin"
android:paddingBottom="#dimen/content_details_small_margin">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/TextView03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="center_horizontal"
android:lines="1"
android:maxLines="1"
android:text="#string/detailsAirDate"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="#dimen/content_details_area_subheader" />
<TextView
android:id="#+id/textReleaseDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_area_header"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/textView61"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:gravity="center_horizontal"
android:lines="1"
android:maxLines="1"
android:text="#string/detailsRating"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textSize="#dimen/content_details_area_subheader" />
<TextView
android:id="#+id/textView12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_area_header"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="#dimen/content_details_baseline_margin">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/content_details_baseline_margin"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/director"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_movie_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/writer"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_edit_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/guest_stars"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:drawableLeft="#drawable/ic_people_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:focusable="false"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#f0f0f0"
android:textSize="#dimen/content_details_body_text" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="#drawable/ic_folder_open_white_24dp"
android:drawablePadding="#dimen/movie_details_padding"
android:gravity="center_vertical"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#FFFFFF"
android:textSize="#dimen/content_details_body_text" />
</LinearLayout>
</LinearLayout>
</com.miz.views.ObservableScrollView>
<FrameLayout
android:id="#+id/progress_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg"
android:visibility="gone">
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</FrameLayout>
</FrameLayout>
Update
Fragment
#SuppressLint("InflateParams") public class TvShowEpisodeDetailsFragment extends Fragment {
public TvShowEpisodeDetailsFragment() {}
public static TvShowEpisodeDetailsFragment newInstance(String showId, int season, int episode) {
TvShowEpisodeDetailsFragment pageFragment = new TvShowEpisodeDetailsFragment();
Bundle bundle = new Bundle();
bundle.putString("showId", showId);
bundle.putInt("season", season);
bundle.putInt("episode", episode);
pageFragment.setArguments(bundle);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
mContext = getActivity();
mBus = MizuuApplication.getBus();
mShowFileLocation = PreferenceManager.getDefaultSharedPreferences(getActivity()).getBoolean(SHOW_FILE_LOCATION, true);
mPicasso = MizuuApplication.getPicassoDetailsView(getActivity());
mMediumItalic = TypefaceUtils.getRobotoMediumItalic(mContext);
mMedium = TypefaceUtils.getRobotoMedium(mContext);
mCondensedRegular = TypefaceUtils.getRobotoCondensedRegular(mContext);
mDatabaseHelper = MizuuApplication.getTvEpisodeDbAdapter();
LocalBroadcastManager.getInstance(mContext).registerReceiver(mBroadcastReceiver,
new IntentFilter(LocalBroadcastUtils.UPDATE_TV_SHOW_EPISODE_DETAILS_OVERVIEW));
loadEpisode();
}
#Override
public void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(mContext).unregisterReceiver(mBroadcastReceiver);
}
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
loadEpisode();
loadData();
}
};
private void loadEpisode() {
if (!getArguments().getString("showId").isEmpty() && getArguments().getInt("season") >= 0 && getArguments().getInt("episode") >= 0) {
Cursor cursor = mDatabaseHelper.getEpisode(getArguments().getString("showId"), getArguments().getInt("season"), getArguments().getInt("episode"));
if (cursor.moveToFirst()) {
mEpisode = new TvShowEpisode(getActivity(),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SHOW_ID)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_TITLE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_PLOT)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_AIRDATE)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_DIRECTOR)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_WRITER)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_GUESTSTARS)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE_RATING)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_HAS_WATCHED)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_FAVOURITE))
);
mEpisode.setFilepaths(MizuuApplication.getTvShowEpisodeMappingsDbAdapter().getFilepathsForEpisode(
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SHOW_ID)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_SEASON)),
cursor.getString(cursor.getColumnIndex(DbAdapterTvShowEpisodes.KEY_EPISODE))
));
}
cursor.close();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.episode_details, container, false);
}
#Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mBackdrop = (ImageView) view.findViewById(R.id.imageBackground);
mEpisodePhoto = (ImageView) view.findViewById(R.id.episodePhoto);
mDetailsArea = view.findViewById(R.id.details_area);
mTitle = (TextView) view.findViewById(R.id.movieTitle);
mSeasonEpisodeNumber = (TextView) view.findViewById(R.id.textView7);
mDescription = (TextView) view.findViewById(R.id.textView2);
mFileSource = (TextView) view.findViewById(R.id.textView3);
mAirDate = (TextView) view.findViewById(R.id.textReleaseDate);
mRating = (TextView) view.findViewById(R.id.textView12);
mDirector = (TextView) view.findViewById(R.id.director);
mWriter = (TextView) view.findViewById(R.id.writer);
mGuestStars = (TextView) view.findViewById(R.id.guest_stars);
mScrollView = (ObservableScrollView) view.findViewById(R.id.observableScrollView);
mFab = (FloatingActionButton) view.findViewById(R.id.fab);
mFab.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ViewUtils.animateFabJump(v, new SimpleAnimatorListener() {
#Override
public void onAnimationEnd(Animator animation) {
play();
}
});
}
});
...
}
...
}
I have set up a RecyclerView adapter with ViewPager in an activity namely TvShowEpisodeDetails , it works well but there is one issue, the Layout of RecyclerView is fixed while scrolling up and down in the Fragment(TvShowEpisodeDetailsFragment). But I want it to scroll with them.
It's hard to use the RecyclerView outside of the ViewPager page fragment; because you can't synchronize and link the touch/motion events when you scroll the page up/down (or when you swipe to next/previous page) between both the page fragment and a standalone (i.e. activity) RecyclerView. Even that won't be smooth.
So, the RecyclerView should be a part of the ViewPager page.
And off course this issue will be gone if I set RecyclerView adapter inside fragment, but I will get unfixable highlighting and scrolling issues
So, now the issue of adding the RecyclerView in the ViewPager fragment is the highlighting issue of the RecyclerView item when you click on any item or when you swipe the ViewPager to right/left page.
But, the main issue is that there is a RecyclerView instance per page, i.e. if you have 5 pages, then you have 5 RecyclerViews.
So, it's a cumbersome to track highlighting only within the RecyclerView adapter class. And hence manipulating that with OnClickListeners solely will have issues of linking these RecyclerView and adapter instances together to update their highlighting item.
So, a simpler approach is to pass a parameter to the RecyclerView adapter with the selected item (which is definitely equals to the current ViewPager page position).
And then do a check in the onBindViewHolder() if the position equals to the passed-in value, then highlight the item; otherwise keep items with the original color.
So, wrapping this up into actions:
Change the adapter constructor to accept a highlighted_position parameter
public PlanetAdapter(ArrayList<PlanetModel> episodeslist,
int highlightedPosition, OnItemClickListener listener)
Whenever you create the ViewPager fragment using newInstance() pass-in the current position of the page fragment:
So, in the TvShowEpisodeDetails activity:
for (int i = 0; i < mEpisodes.size(); i++)
fragments.add(TvShowEpisodeDetailsFragment
.newInstance(mShowId,
Integer.parseInt(mEpisodes.get(i).getSeason()),
Integer.parseInt(mEpisodes.get(i).getEpisode()),
i)); // The position
And in the TvShowEpisodeDetailsFragment fragment, register this into a field in the fragment argument:
public static TvShowEpisodeDetailsFragment newInstance(String showId, int season, int episode, int position) { // adding position
TvShowEpisodeDetailsFragment pageFragment = new TvShowEpisodeDetailsFragment();
Bundle bundle = new Bundle();
// trimmed code.
bundle.putInt("position", position); // <<<< into the bundle
pageFragment.setArguments(bundle);
return pageFragment;
}
And set that in the adapter creation:
int currentPosition = getArguments().getInt("position");
planetAdapter = new PlanetAdapter(episodeslist, currentPosition, new PlanetAdapter.OnItemClickListener() {
#Override
public void onItemClick(final int pos) {
mCallback.sendText(pos);
}
});
And reflect that in the adapter to highlight the item:
public class PlanetAdapter extends RecyclerView.Adapter<PlanetAdapter.PlanetViewHolder> {
private final int highlightedPos;
public PlanetAdapter(ArrayList<PlanetModel> episodeslist, int highlightedPosition, OnItemClickListener listener) {
this.episodeslist = episodeslist;
this.listener = listener;
this.highlightedPos = highlightedPosition; // <<< set the position
}
#Override
public void onBindViewHolder(PlanetAdapter.PlanetViewHolder vh, final int position) {
TextView tv = (TextView) vh.itemView;
PlanetModel planetModel = episodeslist.get(position);
tv.setText(planetModel.getPlanetName());
tv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.bg, 0, 0, 0);
if (highlightedPos == position) { //<<<<< Highlight the item
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryLight));
Log.d("LOG_TAG", "onClick: Highlight item: " + highlightedPos);
} else {
vh.itemView.setBackgroundColor(getContext().getResources().getColor(R.color.colorPrimaryDark));
Log.d("LOG_TAG", "onClick: No highlight: " + highlightedPos);
}
}
}
Intro:
To put things into perspective, I am attempting to use fragments to create a Sudoku game.
The Sudoku board consists of 9 sub-grids, each containing 9 cells, so 9 cells in one grid, and 9 of these grids form the Sudoku board, arranged in a 3x3 fashion.
Method:
Home screen containing some information, of which a GridLayout contains 9 Framelayouts where each Sudoku Fragment will be placed into
The 9 Sudoku Fragments will make up the Sudoku board.
sudoku_cell extends a LinearLayout with an onClickListener, since extending a TextView, I was unable to inflate the sudoku_cell layout (Is it possible to do so?)
In my main activity, I have a GridLayout containing 9 FrameLayouts. These layouts have column and row locations set to form a 3x3 matrix, this is where each of the fragments will be added into.
These FrameLayouts are named on a 0-based index: frame00, frame01, frame02, frame10, etc
Documentation says:
As mentioned here on developer.android.com, I am required to have an:
Inflator method for the fragment, i.e. onCreateView() which inflates the fragment
A Layout container of sorts to root/place the fragment in, in the main activity (in my case)
A FragmentManager and FragmentTransactionManager to handle the fragments, adding and commiting them.
Problem:
TL;DR: Simply, my fragments are not showing.
After calling the commit(), I expect to see a 3x3 board of sudoku_grid fragments, each containing 9 sudoku_cells. However, this does not get shown
I have searched SO, reread the documentation, and searched more but cannot understand why it is not showing.
I have tried:
When inflating my fragment, I inflate a sudoku_cell layout instead, this does infact show a 9 cell grid.
However each cell should be a grid containing 9 cells, this leads me to believe that there may be an issue on the Sudoku_Grid - Sudoku_Cell side, possibly the sudoku_cell layout is not being inflated correctly or being rooted correctly.
Usually an LayoutInflator, and ViewGroup is passed allowing one to inflate a layout, but in the case of the sudoku_cell, I cannot find such a method to override, is this the cause?
The code:
sudoku_cell.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">
<TextView
android:id="#+id/cellText"
android:layout_width="35dp"
android:layout_margin="1px"
android:textSize="18dp"
android:layout_height="35dp"
android:textAlignment="center"
android:textColor="#color/clBlack">
</TextView>
</LinearLayout>
SudokuCell.java
public class SudokuCell extends LinearLayout{
private LinearLayout layout;
private TextView textView;
private Context mContext;
private Point location;
private int index;
public SudokuCell(Context context) {
super(context);
}
public SudokuCell(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout = (LinearLayout) inflater.inflate(R.layout.sudoku_cell, this, true);
textView = layout.findViewById(R.id.cellText);
setText("");
}
public void setStaticText(String s){
if (textView != null) {
textView.setText(s);
textView.setTypeface(textView.getTypeface(), Typeface.BOLD);
}
}
public void setText(String s){
if (textView != null)
textView.setText(s);
}
public Point getLocation() {
return location;
}
public void setLocation(Point location) {
this.location = location;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
9 of these sudoku_cell's get added to a sudoku_grid as shown below in the onCreateView() and populateGrid() methods:
sudoku_grid.xml
<?xml version="1.0" encoding="utf-8"?>
<GridLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="2px"
android:id="#+id/grid_layout"
android:columnCount="3"
android:rowCount="3">
</GridLayout>
SudokuGrid.java
public class SudokuGrid extends Fragment{
private GridLayout gridLayout;
private List<GridFragmentListener> listeners = new ArrayList<>();
private Context mActitityContext;
private boolean FRAGMENT_LOCATION_CENTRE;
private float SCREEN_DP;
private int GRID_MARGINS_DP = 1;
private int colorOdd, colorEven;
private List<Integer> presetGrid;
private View previousView;
private Drawable previousViewDrawable;
public void addGridListener(GridFragmentListener gridFragmentListener) {
listeners.add(gridFragmentListener);
}
public void removeGridListener(GridFragmentListener gridFragmentListener) {
listeners.remove(gridFragmentListener);
}
protected void notifyValueChanged(View value) {
for (GridFragmentListener listener : listeners) listener.onValueChange(value);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mActitityContext = getActivity();
View v = inflater.inflate(R.layout.sudoku_grid, container, false);
//set grid view
gridLayout = v.findViewById(R.id.grid_layout);
populateGrid();
return v;
}
private void populateGrid() {
for (int i = 0; i < 9; i++) {
SudokuCell sudokuCell = new SudokuCell(mActitityContext);
sudokuCell.setBackgroundColor(((i % 2) == 0) ? R.color.clOdd : R.color.clEven);
System.out.printf("Sudoku Cell ID [ index = " + String.valueOf(i) + " ] - getId() = " + sudokuCell.getId());
sudokuCell.setLocation(getPoint(i));
sudokuCell.setIndex(i);
sudokuCell.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
notifyValueChanged(view);
}
});
sudokuCell.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean b) {
SudokuCell cell = (SudokuCell) view;
if (b)
view.setBackgroundColor(ContextCompat.getColor(mActitityContext, R.color.clSelected));
else
view.setBackgroundColor(ContextCompat.getColor(mActitityContext, (cell.getIndex() % 2 == 0) ? R.color.clOdd : R.color.clEven));
}
});
sudokuCell.setStaticText(String.valueOf(i));
gridLayout.addView(sudokuCell, i);
}
}
private Point getPoint(int i) {
int y = 0;
while (i > 2){
y++;
i -= 3;
}
return new Point(i, y);
}
#Override
public void onStart() {
super.onStart();
try {
addGridListener((GridFragmentListener) getActivity());
} catch (ClassCastException e) {
throw new ClassCastException(
getActivity().getClass().toString()
+ " does not implement the DetailsFragment.DetailsFragmentListener interface.");
}
}
#Override
public void onStop() {
super.onStop();
removeGridListener((GridFragmentListener) getActivity());
}
}
In my main activity, I handle the creation of 9 sudoku_grid fragments which are placed into each respective FrameLayout, to form a 3x3 matrix of Sudoku_Grids, which will form the Sudoku board
activity_main_sudoku.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="wrap302.nmu.task1.MainActivitySudoku"
android:background="#color/clDarkGrey">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:id="#+id/linearLayout2">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:text="#string/app_title"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:textColor="#color/clWhite"
android:textAppearance="#style/TextAppearance.AppCompat.Display1"
android:textAlignment="center"
android:textStyle="bold"
android:fontFamily="sans-serif"/>
<TextView
android:text="#string/lblScore"
android:textColor="#color/clWhite"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:id="#+id/lblScore"
android:textAppearance="#style/TextAppearance.AppCompat.Button" android:textAlignment="center"
android:layout_marginBottom="5dp"/>
</LinearLayout>
<GridLayout
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnCount="3"
android:rowCount="3"
android:id="#+id/main_sudokugrid_container">
<FrameLayout
android:layout_column="0"
android:layout_row="0"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame00"/>
<FrameLayout
android:layout_column="1"
android:layout_row="0"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame01"/>
<FrameLayout
android:layout_column="2"
android:layout_row="0"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame02"/>
<FrameLayout
android:layout_column="0"
android:layout_row="1"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame10"/>
<FrameLayout
android:layout_column="1"
android:layout_row="1"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame11"/>
<FrameLayout
android:layout_column="2"
android:layout_row="1"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame12"/>
<FrameLayout
android:layout_column="0"
android:layout_row="2"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame20"/>
<FrameLayout
android:layout_column="1"
android:layout_row="2"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame21"/>
<FrameLayout
android:layout_column="2"
android:layout_row="2"
android:layout_width="wrap_content"
android:background="#color/clWhite"
android:layout_height="wrap_content" android:id="#+id/frame22"/>
</GridLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center" android:id="#+id/linearLayout">
<GridLayout
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:paddingTop="0dp">
<Button
android:layout_row="0"
android:layout_column="0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn1"
android:text="1"/>
<Button
android:layout_row="0"
android:layout_column="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn2"
android:text="2"/>
<Button
android:layout_row="0"
android:layout_column="2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn3"
android:text="3"/>
<Button
android:layout_row="1"
android:layout_column="0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn4"
android:text="4"/>
<Button
android:layout_row="1"
android:layout_column="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn5"
android:text="5"/>
<Button
android:layout_row="1"
android:layout_column="2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn6"
android:text="6"/>
<Button
android:layout_row="2"
android:layout_column="0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn7"
android:text="7"/>
<Button
android:layout_row="2"
android:layout_column="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn8"
android:text="8"/>
<Button
android:layout_row="2"
android:layout_column="2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn9"
android:text="9"/>
<Button
android:layout_row="0"
android:layout_column="3"
android:layout_rowSpan="3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="fill_vertical"
android:id="#+id/btnClear"
android:text="Clear"/>
</GridLayout>
</LinearLayout>
</RelativeLayout>
MainActivitySudoku.java
public class MainActivitySudoku extends AppCompatActivity implements GridFragmentListener {
private FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_sudoku);
createSudokuGrid();
}
private void createSudokuGrid() {
fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransactionManager = fragmentManager.beginTransaction();
fragmentTransactionManager.add(R.id.frame00, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame01, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame02, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame10, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame11, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame12, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame20, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame21, new SudokuGrid());
fragmentTransactionManager.add(R.id.frame22, new SudokuGrid());
fragmentTransactionManager.commit();
}
#Override
protected void onStart() {
super.onStart();
Toast.makeText(this, "Activity Started & Viewable", Toast.LENGTH_SHORT).show();
}
// GridFragmentListener
#Override
public void onValueChange(View view) {
//todo something here with received view
}
}
Well, the solution proved simpler than expected.
In short, the solution was to move the SudokuCell constructor code from the
SudokuCell(Context context, AttributeSet attrs)
to the
SudokuCell(Context context)
since that was the constructor I was calling.
A few other changes can be made for improvement, this solves the fragments not being displayed.
Quite a simple error
Ok - I have given you a sample of how to add your fragments so they will display. If you go through this and emulate the process this will assist you. I've used basic examples in the layout so we can have ids to use in the classes.
You'll also need to manage the app lifecycle and the back press button on how you want to manage your stack with your fragments and maintaining any data.
Activity
public class MyActivity extends Activity {
Fragment fragment;
FrameLayout frameLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_myactivity);
View view = this.findViewById(android.R.id.content);
frameLayout = (FrameLayout) findViewById(R.id.frag);
fragment = new MyFragment();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.frag, fragment);
fragmentTransaction.commit();
}
}
Layout for Activity
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
.../...>
.../...
<FrameLayout
android:id="#+id/frag"
// sort out your layout here with the frameLayouts
android:layout_below="#+id/your_id"
/>
.../...
</RelativeLayout>
Fragment
public class MyFragmentextends Fragment {
FragmentManager fragmentManager;
Fragment fragment;
public static MyFragmentnewInstance(String item {
fragment =
new MyFragment();
// pass data from activity
Bundle args = new Bundle();
args.putString(ITEM, item);
fragment.setArguments(args);
return fragment;
}
public DeliveryDisplayFromDispenserFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
item = getArguments().getString(ITEM);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view =
inflater.inflate(R.layout.myfragment, container, false);
}
}
Layout for Fragment
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
.../...>
// fragment layout
</RelativeLayout>
I use this code to create map and marker but when I run it it shows blank map and errors
My code is from - https://developers.google.com/maps/documentation/android-api/
ContactFragment.java
public class ContactFragment extends Fragment implements OnMapReadyCallback {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.mapView);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap map) {
LatLng sydney = new LatLng(-33.867, 151.206);
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));
map.addMarker(new MarkerOptions()
.title("Sydney")
.snippet("The most populous city in Australia.")
.position(sydney));
}
}
fragment_contact.xml
<RelativeLayout 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"
tools:context="layout.ContactFragment"
android:background="#color/colorWhite"
android:id="#+id/contact_wrapper">
<!-- TODO: Update blank fragment layout -->
<com.google.android.gms.maps.MapView
android:layout_width="match_parent"
android:id="#+id/mapView"
android:layout_height="200dp" />
<TextView
android:text="Address - 1526 Petchaburi Rd. Makkasan Rajdhevee Bangkok 10400 Thailand"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView6"
android:layout_below="#+id/mapView"
android:layout_alignParentStart="true"
android:layout_marginTop="18dp"
android:padding="10dp"
android:textSize="18sp"
android:textStyle="normal|bold" />
<TextView
android:text="Tel - +66-2652-7477-80, Fax +66-2652-7777"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView7"
android:padding="10dp"
android:layout_below="#+id/textView3"
android:layout_alignParentStart="true"
android:textSize="18sp"
android:textStyle="normal|bold"
android:fontFamily="sans-serif" />
<TextView
android:text=" EMail - sdschool#sd.ac.th"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView3"
android:padding="10dp"
android:textSize="18sp"
android:layout_below="#+id/textView6"
android:layout_alignParentStart="true"
android:textStyle="normal|bold" />
</RelativeLayout>
This is error I got
Use below code .
public class ContactFragment extends Fragment implements OnMapReadyCallback {
View rootView
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
rootView =inflater.inflate(R.layout.content_main, container, false);
MapFragment mapFragment = (MapFragment) getFragmentManager()
rootView.findFragmentById(R.id.mapView);
mapFragment.getMapAsync(this);
return rootView;
}
}
when creating a Fragment is that you must use the onCreateView() callback to define the layout.
I have a fragment that contains a PercentRelativeLayout that I want to replace with another fragment on a button click. Here is the outer fragment xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.percent.PercentRelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<android.support.percent.PercentRelativeLayout
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
app:layout_widthPercent="92%"
app:layout_heightPercent="80%"
app:layout_marginTopPercent="15%">
<android.support.percent.PercentRelativeLayout
android:layout_height="wrap_content"
android:layout_width="match_parent">
<TextView
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:text="Vecka 49"
android:id="#+id/weekOneTextView"/>
<android.support.percent.PercentRelativeLayout
app:layout_widthPercent="100%"
app:layout_heightPercent="0%"
android:layout_below="#+id/weekOneTextView"
android:id="#+id/displayWeekOne">
</android.support.percent.PercentRelativeLayout>
<TextView
android:layout_alignParentLeft="true"
app:layout_widthPercent="45%"
app:layout_heightPercent="5%"
app:layout_marginTopPercent="2%"
android:layout_below="#+id/displayWeekOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Vecka 50"
android:id="#+id/weekTwoTextView"
android:clickable="true"/>
<android.support.percent.PercentRelativeLayout
app:layout_widthPercent="100%"
app:layout_heightPercent="0%"
android:layout_below="#+id/weekTwoTextView"
android:id="#+id/displayWeekTwo">
</android.support.percent.PercentRelativeLayout>
<TextView
android:layout_alignParentLeft="true"
app:layout_widthPercent="45%"
app:layout_heightPercent="5%"
app:layout_marginTopPercent="2%"
android:layout_below="#+id/displayWeekTwo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Vecka 51"
android:id="#+id/weekThreeTextView"
android:clickable="true"/>
<android.support.percent.PercentRelativeLayout
app:layout_widthPercent="100%"
app:layout_heightPercent="0%"
android:layout_below="#+id/weekThreeTextView"
android:id="#+id/displayWeekThree">
</android.support.percent.PercentRelativeLayout>
<TextView
android:layout_alignParentLeft="true"
android:layout_below="#+id/displayWeekThree"
app:layout_widthPercent="45%"
app:layout_heightPercent="5%"
app:layout_marginTopPercent="2%"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Vecka 52"
android:id="#+id/weekFourTextView"
android:clickable="true"/>
<android.support.percent.PercentRelativeLayout
app:layout_widthPercent="100%"
app:layout_heightPercent="0%"
android:layout_below="#+id/weekFourTextView"
android:id="#+id/displayWeekFour">
</android.support.percent.PercentRelativeLayout>
</android.support.percent.PercentRelativeLayout>
</android.support.percent.PercentRelativeLayout>
</android.support.percent.PercentRelativeLayout>
Here is the onClick method in the fragments Java file
private void setOnClickListeners(){
mWeekOneTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DropDownWeekFragment dropDownWeekFragment = new DropDownWeekFragment();
FragmentManager manager = getFragmentManager();
manager.beginTransaction().add(R.id.displayWeekOne, dropDownWeekFragment).commit();
}
});
I want to replace the PercentRelativeLayout with ID displayWeekOne with a fragment, here is the for the fragment I wish to replace with
<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context="layout.DropDownWeekFragment">
<android.support.percent.PercentRelativeLayout
app:layout_widthPercent="80%"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Måndag"
android:id="#+id/monday"
app:layout_marginTopPercent="2%"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tisdag"
android:id="#+id/tuesday"
android:layout_below="#id/monday"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/wednessday"
android:layout_below="#id/tuesday"
android:text="Onsdag"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/thursday"
android:layout_below="#id/wednessday"
android:text="Torsdag"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/friday"
android:layout_below="#id/thursday"
android:text="Fredag"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/saturday"
android:layout_below="#id/friday"
android:text="Lördag"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/sunday"
android:layout_below="#id/saturday"
android:text="Söndag"/>
</android.support.percent.PercentRelativeLayout>
</android.support.percent.PercentRelativeLayout>
And here is the Java for that fragment
package layout;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.studentconsulting.mypages.R;
import static android.content.ContentValues.TAG;
public class DropDownWeekFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public DropDownWeekFragment() {
// Required empty public constructor
}
public static DropDownWeekFragment newInstance(String param1, String param2) {
DropDownWeekFragment fragment = new DropDownWeekFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
Log.d("hej", "oncreate");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_drop_down_week, container, false);
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
I read in the documentation that I can use replace() to replace another fragment, but I want to replace the PercentRelativeLayout if that is possible, or add the fragment to the outer fragments xml
FragmentManager manager = getFragmentManager();
manager.beginTransaction().replace(R.id.displayWeekOne, dropDownWeekFragment).commit();
You can use replace() to replace one Fragment with another Fragment, as well as a Layout with a Fragment.
Not tested. Hope it works.