将变量从MainActivity传递给Fragment

时间:2016-05-20 18:36:08

标签: android api variables location fragment

这是一个java问题而不是android :)。在我的MainActivity中,我获得了手机的位置(日志和纬度),如下面的代码所示。

public class MainActivity extends AppCompatActivity implements  
GoogleApiClient.OnConnectionFailedListener,

GoogleApiClient.ConnectionCallbacks{
private static final int PLAY_SERVICES_CODE = 90;
GoogleApiClient googleApiClient;
private static final String TAG = "Location";
private static final String TODAY_FRAGMENT = "today_fragment";

public static double lat,log;
TodayForecast ff;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FragmentManager fragmentManager = getSupportFragmentManager();
    ff = (TodayForecast) fragmentManager.findFragmentByTag(TODAY_FRAGMENT);

    if (savedInstanceState != null) {
        //Restore the fragment's instance
        ff = (TodayForecast) getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
    }

    if(ff == null) {
        ff = new TodayForecast();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(android.R.id.content, ff);
        fragmentTransaction.commit();
    }

    if(checkPlayServices()){
        initializeGoogleApiClient();
    }
}

private void initializeGoogleApiClient() {
    googleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addOnConnectionFailedListener(this)
            .addConnectionCallbacks(this)
            .build();

}

public boolean checkPlayServices(){
    int result = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());

    if(result!= ConnectionResult.SUCCESS){
        if(GooglePlayServicesUtil.isUserRecoverableError(result)){
            GooglePlayServicesUtil.getErrorDialog(result, this, PLAY_SERVICES_CODE).show();
        }
        return false;
    }
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    return super.onOptionsItemSelected(item);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    return super.onCreateOptionsMenu(menu);
}


@Override
public void onConnected(@Nullable Bundle bundle) {

    Location loc = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

    if(loc!=null){
        lat = loc.getLatitude();
        log = loc.getLongitude();

        Log.v(TAG,"lat: "+lat);
        Log.v(TAG,"lon: "+log);

    }else{
        Toast.makeText(getApplicationContext(),"No location obtained",Toast.LENGTH_SHORT).show();
    }
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

@Override
protected void onStart() {
    super.onStart();
    googleApiClient.connect();
}

@Override
protected void onStop() {
    super.onStop();

    if(googleApiClient.isConnected()){
        googleApiClient.disconnect();
    }
}
}

我想将onConnected方法中看到的log和lat的值传递给片段。

@Override
public void onConnected(@Nullable Bundle bundle) {

Location loc =  
LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

if(loc!=null){
    lat = loc.getLatitude();
    log = loc.getLongitude();

    Log.v(TAG,"lat: "+lat);
    Log.v(TAG,"lon: "+log);

}else{
    Toast.makeText(getApplicationContext(),"No location   
    obtained",Toast.LENGTH_SHORT).show();
   }
 }

我尝试了这个,但两个值都是0 :(

public class TodayForecast extends Fragment {
public static String URL= "http://api.openweathermap.org/data/2.5/weather?";
public static String BASE_URL= "";


String IMG_URL = "http://api.openweathermap.org/img/w/";
double lat;
double lot;
public TodayForecast() {
    // Required empty public constructor
}



@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment

    lat = MainActivity.lat;
    lot = MainActivity.log;

    BASE_URL = URL + "lat=" + lat + "&lot=" + lot + "&appid=" + "MY KEY";


    return inflater.inflate(R.layout.fragment_today_forecast, container,   
    false);



   }

 }

我的片段的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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:id="@+id/main_content"
android:paddingBottom="@dimen/activity_vertical_margin"
android:background="#ff1ba1ee"
tools:context="testing.theo.newweatherapp.TodayForecast">

<TextView
    android:id="@+id/cityText"
    android:textColor="#fff"
    android:textSize="18sp"
    android:textStyle="bold"
    android:layout_centerHorizontal="true"
    android:text="City of Spokane, US"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<ImageView
    android:id="@+id/thumbnailIcon"
    android:layout_below="@+id/cityText"
    android:layout_marginTop="10dp"


    android:layout_width="100dp"
    android:layout_height="100dp" />

<TextView
    android:id="@+id/tempText"
    android:layout_marginTop="25dp"
    android:text="12 deg"
    android:textStyle="normal"
    android:textSize="41sp"
    android:textColor="#fff"
    android:layout_below="@+id/cityText"
    android:layout_centerHorizontal="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/rainText"
    android:textSize="16sp"
    android:textColor="#fff"
    android:text=""
    android:layout_below="@+id/thumbnailIcon"
    android:layout_marginTop="10dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
<TextView
    android:id="@+id/windText"
    android:layout_below="@+id/rainText"
    android:layout_marginTop="35dp"
    android:textColor="#fff"
    android:text="Wind"
    android:textSize="16sp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
<TextView
    android:id="@+id/cloudText"
    android:textSize="16sp"
    android:layout_marginTop="5dp"
    android:layout_below="@+id/windText"
    android:textColor="#fff"
    android:text="Cloudness"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/pressureText"
    android:textSize="16sp"
    android:layout_marginTop="5dp"
    android:textColor="#fff"
    android:text="Pressure"
    android:layout_below="@+id/cloudText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/humidText"
    android:textSize="16sp"
    android:text="Humidity"
    android:layout_marginTop="5dp"
    android:textColor="#fff"
    android:layout_below="@+id/pressureText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<TextView
    android:id="@+id/riseText"
    android:text="Sunrise"
    android:textSize="16sp"
    android:textColor="#fff"
    android:layout_marginTop="5dp"
    android:layout_below="@+id/humidText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />
<TextView
    android:id="@+id/setText"
    android:text="Sunrise"
    android:layout_marginTop="5dp"
    android:textColor="#fff"
    android:textSize="16sp"
    android:layout_below="@+id/riseText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />


<TextView
    android:id="@+id/updateText"
    android:text="Last update"
    android:layout_marginTop="5dp"
    android:layout_centerHorizontal="true"
    android:textColor="#fff"
    android:textSize="16sp"
    android:layout_below="@+id/setText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

有什么想法吗?感谢

3 个答案:

答案 0 :(得分:1)

我正在做的事情如下所示

用于调用片段

getSupportFragmentManager().beginTransaction().replace(R.id.main_container, MyMeetings.newInstance(user_type), "My Meeting").commit();

user_type 是一个字符串

在Fragment中创建了一个新实例来获取如下所示的数据

 public static MyMeetings newInstance(String user_type) {
        MyMeetings fragment = new MyMeetings();

        mUserType = user_type;
        return fragment;
    }

希望得到这个帮助。

修改

将以下代码粘贴到主要活动的XML文件

       <FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/main_container"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/view" />

然后如果你使用about代码

,那么所有片段都会在这个Frame Layout中打开

答案 1 :(得分:0)

1.在你的片段TodayForecast

中声明log和lat的两个变量

2.创建lon和lat的公共setter方法

public class TodayForecast extends Fragment {
public static String URL= "http://api.openweathermap.org/data/2.5/weather?";
public static String BASE_URL= "";


String IMG_URL = "http://api.openweathermap.org/img/w/";
double lat;
double lot;
public TodayForecast() {
    // Required empty public constructor
}

public setLat(double lat){
    this.lat = lat
}
public setLot(double lot){
    this.lot = lot
}
}

3.set使用onConnected内部的setter方法设置TodayForecast变量log和lat值。

@Override
public void onConnected(@Nullable Bundle bundle) {

Location loc =  
LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

if(loc!=null){
    ff.setLat(loc.getLatitude());
    ff.setLon(loc.getLongitude());

    Log.v(TAG,"lat: "+lat);
    Log.v(TAG,"lon: "+log);

}else{
    Toast.makeText(getApplicationContext(),"No location   
    obtained",Toast.LENGTH_SHORT).show();
   }
 }

答案 2 :(得分:0)

将您的值传递给包

@Override
public void onConnected(@Nullable Bundle bundle) {

Location loc =  
LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

if(loc!=null){
    lat = loc.getLatitude();
    log = loc.getLongitude();

    Log.v(TAG,"lat: "+lat);
    Log.v(TAG,"lon: "+log);
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentTransaction = fragmentManager.beginTransaction();

    Fragment mFrag = new TodayForecast();
    final Bundle bundle = new Bundle();
    bundle.putString("lat", lat);
    bundle.putString("log", log);

    mFrag.setArguments(bundle);
    fragmentTransaction.replace(R.id.content_place, mFrag);
    fragmentTransaction.commit();


}else{
    Toast.makeText(getApplicationContext(),"No location   
    obtained",Toast.LENGTH_SHORT).show();
   }
 }

在TodayForecast Fragment中,获取如下所示的值。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        Bundle args = getArguments();

        if (args != null && args.containsKey("lat"))
            Log.v("TAG","lat: "+args.getString("lat"));

        if (args != null && args.containsKey("log"))
            Log.v("TAG","lon: "+args.getString("log"));

        return inflater.inflate(R.layout.fragment_today_forecast, container,false);
}