简体   繁体   English

从活动获取变量的值并将其传递给片段活动

[英]Get value of variable from activity and pass it to fragment activity

I want to get the value of mLocal in my Activity and pass it to LatLng on Fragment class. 我想在我的Activity中获取mLocal的值,并将其传递给Fragment类的LatLng。

Main Activity 主要活动

    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);

            initLocationFetching(MainActivity.this);

        mapFragment = new MapFragment(MainActivity.this, this);
        manager = getSupportFragmentManager();
        manager.beginTransaction().replace(R.id.mainLayout, mapFragment).commit();
}
            @Override
        public void locationFetched(Location mLocal, Location oldLocation, String time, String locationProvider) {
        super.locationFetched(mLocal, oldLocation, time, locationProvider);
    > here mLocal
    }

Map Fragment Class 地图片段类

 class MapFragment extends Fragment implements OnMapReadyCallback,
            GoogleApiClient.OnConnectionFailedListener {

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        LatLng origin = new LatLng(14.507328, 121.000905);

        mMap.addMarker(new MarkerOptions()
                .position(new LatLng(14.507577, 121.004456))
                .anchor(0.5f, 0.5f)
                .title("title")
                .snippet("snippet")
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));

        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(value1, value2), 9.0f));

    }

Above, I want it not hardcoded. 以上,我希望它不被硬编码。 I want to get the value of mLocal in MainActivity and pass it on LatLng() MapFragment. 我想在MainActivity中获取mLocal的值,并将其传递给LatLng()MapFragment。

you can take a public global vaiable of Location in activity and create it's getter-setter 您可以在活动中获取全球公开的Location信息,并进行设置

 

 MainActivity extends Activity

    public Location mLocal;
    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);

            @Override
        public void locationFetched(Location mLocal, Location oldLocation, String time, String locationProvider) {
        super.locationFetched(mLocal, oldLocation, time, locationProvider);
    setMLocal(mLocal);
    } 
     public String getMLocal() {
            return mLocal;
        }

        public void setMLocal(String mLocal) {
            this.mLocal= mLocal;
        }

And then you can use getter method in your fragment 然后可以在片段中使用getter方法

public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
    Location mLocal = ((MainActivity)getActivity).getMLocal(); //you can get your Location object and you can use it further
        //LatLng origin = new LatLng(14.507328, 121.000905);

        mMap.addMarker(new MarkerOptions()
                .position(new LatLng(14.507577, 121.004456))
                .anchor(0.5f, 0.5f)
                .title("title")
                .snippet("snippet")
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));

You can add a method to MapFragment called setLocation and call it in MainActivity. 您可以向MapFragment添加一个名为setLocation的方法,然后在MainActivity中调用它。

Like this: 像这样:

MapFragment MapFragment

// Location mCurrentLoc = null;

public void setLocation(Location loc) {
    mCurrentLoc = loc;
    if (mMap != null) {
        //do fragment location stuff
    }
}

@Override
public void onMapReady(GoogleMap googleMap) {
    // all your above code

    if (mCurrentLocation != null) {
        // do fragment location stuff
    }
}

MainActivity 主要活动

mapFragment.setLocation(mLocal);

为了从活动数据传递到片段,您可以使用Bundle把你的变量,并设置片段的说法与此Bundle或者您可以使用另一种方法(我没有看到你的整个项目得到确保其更好的办法) EventBus

You have the instance of MapFragment as mapFragment right? 您将MapFragment的实例作为mapFragment对吗?

So create a public method in MapFragment.class as getCoordinates 因此,在MapFragment.class创建一个公共方法作为getCoordinates

    public void getCoordinates(double latitude, double longitude){
         this.latitude = latitude;
         this.longitude = longitude;
}

Send coordinates from Activity to fragment as below 从活动发送坐标到片段如下

if(mapFragment instanceOf MapFragment){
 ((MapFragment)mapFragment).getCoordinates(latitude, longitude);
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        initLocationFetching(MainActivity.this);

    mapFragment = new MapFragment(MainActivity.this, this);
    manager = getSupportFragmentManager();
}
 @Override
    public void locationFetched(Location mLocal, Location oldLocation, String time, String locationProvider) {
    super.locationFetched(mLocal, oldLocation, time, locationProvider);
 //After initLocationFetching.
 Bundle bundle = new Bundle();
 bundle.putDouble("Lat",mLocal.getLatitude());
 bundle.putDouble("Long"mLocal.getLongitude());
 mapFragment.setArguments(bundle);
 manager.beginTransaction().replace(R.id.mainLayout, mapFragment).commit();
}



//In MapFragment
class MapFragment extends Fragment implements OnMapReadyCallback,
        GoogleApiClient.OnConnectionFailedListener {
double lati=0.0;
double longi=0.0;

@Override
public void onCreate(Bundle bundle){
lati=getArguments().getDouble("Lat");
longi=getArguments().getDouble("Long");
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    LatLng origin = new LatLng(lati,longi);

    mMap.addMarker(new MarkerOptions()
            .position(new LatLng(lati,longi))
            .anchor(0.5f, 0.5f)
            .title("title")
            .snippet("snippet")
            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_CYAN)));

    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(value1, value2), 9.0f));

}

You must create an instance of your activity and thus pass the data of it to your fragment 您必须创建活动的实例,然后将其数据传递给片段

In your fragment, Declare a variable of your MainActivity to obtain the context of it and thus be able to work with it on the fragment and declares the variable to which you want to assign the value that it contains in the MainActivity and pass the value on the onAttach method. 在片段中,声明MainActivity的变量以获取其上下文,从而能够在片段上使用它,并声明要为其分配MainActivity中包含的值的变量,并将该值传递给onAttach方法。 onAttch is called when a fragment is first attached to its context. 当片段首次附加到其上下文时,将调用onAttch。

private MainActivity mActivity;
private String mData;

Now in the onAttach method that is when the fragment adheres to its container which is the main activity. 现在,在onAttach方法中,片段将粘附到其容器上,这是主要活动。

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    //Verify if mActivity is null and it is MainActivity context
    if (mActivity == null && context instanceof MainActivity) {
        mActivity = (MainActivity) getActivity();
        //Checking for a NPE       
        if(mActivity != null){
         mData = mActivity.MyMainActivityVariable;
       }
     }
   }

And in the onDetach method Called when the fragment is no longer attached to its activity. 并且在onDetach方法中当片段不再附加到其活动时调用。

@Override
public void onDetach() {
    super.onDetach();
    mActivity = null;
    }

Now we can work with the variable we want to use from the MainActivity. 现在,我们可以使用MainActivity中要使用的变量。 This is using Support Library Fragment For more info about Fragments go to Fragment Android Developers 这正在使用支持库片段有关片段的更多信息,请转到片段Android开发人员

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM