如何在片段中使用setContentView方法?

时间:2019-07-20 21:09:44

标签: java android-studio fragment

我正在做一个小项目...该项目可用于地图,但是setContentView方法存在问题,当我扩展Fragment而不是FragmentActivity时该方法不起作用。 注意:我需要扩展Fragment而不是Fragment Activity,因为代码部分中显示的代码只是项目的一小部分。在我的原始项目中,如果我将Fragment更改为FragmentActivity,则会在另一个类中出现问题。

public class MapsActivity extends Fragment implements OnMapReadyCallback,LocationListener,GoogleMap.OnMarkerClickListener{


    private GoogleMap mMap;
    private DatabaseReference mUsers;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //Dosn't Work with Fragment Extends ?!
        setContentView(R.layout.activity_maps);
        SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        mUsers= FirebaseDatabase.getInstance().getReference("Users");

    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        googleMap.setOnMarkerClickListener(this);
        mUsers.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for (DataSnapshot s : dataSnapshot.getChildren()){
                    UserInformation user = s.getValue(UserInformation.class);
                    assert user != null;
                    LatLng location = new LatLng(user.latitude,user.longitude);
                    mMap.addMarker(new MarkerOptions().position(location).title(user.name)).setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
                }

            }
            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
            }
        });
    }



    @Override
    public void onLocationChanged(Location location) {
    }
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
    @Override
    public void onProviderEnabled(String provider) {
    }
    @Override
    public void onProviderDisabled(String provider) {
    }
    @Override
    public boolean onMarkerClick(Marker marker) {
        return false;
    }
}

我希望应用程序正常运行,并且基于firebase中的数据在地图上显示不同的标记,但是该应用程序无法正常工作。 注意:如果我将Fragment更改为FragmentActivity,它将正常工作。.

我尝试创建视图,但是应用程序无法正常工作 “应用已停止”

public class MapsActivity extends Fragment implements OnMapReadyCallback,LocationListener,GoogleMap.OnMarkerClickListener{


private GoogleMap mMap;
private DatabaseReference mUsers;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}


@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.activity_maps, container, false);
    SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    mUsers= FirebaseDatabase.getInstance().getReference("Users");
    return view;
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    googleMap.setOnMarkerClickListener(this);
    mUsers.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for (DataSnapshot s : dataSnapshot.getChildren()){
                UserInformation user = s.getValue(UserInformation.class);
                assert user != null;
                LatLng location = new LatLng(user.latitude,user.longitude);
                mMap.addMarker(new MarkerOptions().position(location).title(user.name)).setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
            }

        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
        }
    });
}



@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public boolean onMarkerClick(Marker marker) {
    return false;
}

当我将片段更改为片段活动时,出现错误,这是另一活动中的这一行

getSupportFragmentManager().beginTransaction().replace(R.id.container,new HomeFragment()).commit();

HomeFragment扩展Fragment时没有错误,但是当我将其更改为Fragment Activity时,[new HomeFragment()]中会出现错误。

2 个答案:

答案 0 :(得分:1)

使用onCreateView方法作为片段的起点。您应该将片段视为布局本身,而不是需要表示视图的容器。

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.activity_maps, container, false);
    // ...
    return view;
}

答案 1 :(得分:0)

我找到了解决此问题的方法, 我应该重写2方法,onViewCreated,onCreateView 那么应该将代码放入onCreate中,该代码必须像这样在onViewCreated中

public class HomeFragment extends Fragment implements OnMapReadyCallback,LocationListener,GoogleMap.OnMarkerClickListener  {


public GoogleMap mMap;
public DatabaseReference mUsers;

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    mUsers= FirebaseDatabase.getInstance().getReference("Users");

}


@NonNull
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_home, container, false);

}

@Override
public void onMapReady(GoogleMap googleMap) {

mMap = googleMap;
        googleMap.setOnMarkerClickListener(this);
        mUsers.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                for (DataSnapshot s : dataSnapshot.getChildren()){
                    UserInformation user = s.getValue(UserInformation.class);
                    assert user != null;
                    LatLng location = new LatLng(user.latitude,user.longitude);
                    mMap.addMarker(new MarkerOptions().position(location).title(user.name)).setIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW));
                }

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
            }
        });

}