将变量从 MainActivity 传递到 Fragment

问题描述 投票:0回答:3

这是一个 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" />

</RelativeLayout>

有什么想法吗?

java location
3个回答
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 代码,所有片段都将在此框架布局中打开


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.使用 onConnected 中的 setter 方法设置 TodayForecast 变量日志和纬度值。

@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();
   }
 }

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);
}
© www.soinside.com 2019 - 2024. All rights reserved.