【问题标题】:send data from Actvity to fragment,method after Activity on Create将数据从 Activity 发送到片段,从 Activity 中创建方法
【发布时间】:2016-02-10 14:25:00
【问题描述】:

我在名为 onConnected 的方法中从 Activity 获取数据,我获取当前位置:经度、纬度。如何将这些数据放入片段?是的,我知道 Bundle 以及如何通过这种方式传递数据,但我无法创建 Bundle在 onConnected 方法和 setArguments 中,因为我在 onCreate Activity 方法中创建了片段。我创建了类变量经度和纬度,但在 onCreate 中,变量 = 0。如何将数据发送到片段?我需要在 Activity 中获取当前位置和将其发送到片段。

活动

public class ScreenForTagging extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener {
double latitude,longitude;
    Location mLastLocation;
GoogleApiClient mGoogleApiClient;
    Bundle bundlelocation;
    Tagging_screen tagging_screen;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_screen_for_tagging);
        tagging_screen = new Tagging_screen();
        bundlelocation = new Bundle();

        bundlelocation.putDouble("latitude",latitude);
        bundlelocation.putDouble("longitude", longitude);

        tagging_screen.setArguments(bundlelocation);

        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.fragmentCont, tagging_screen);
        fragmentTransaction.commit();
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
        }
mGoogleApiClient.connect();

    }

    @Override
    public void onConnected(Bundle bundle) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mLastLocation != null) {
            latitude = mLastLocation.getLatitude();
            longitude = mLastLocation.getLongitude();

            Toast.makeText(ScreenForTagging.this, "latitude:"+latitude+"longitude"+longitude, Toast.LENGTH_SHORT).show();
        }

    }


    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }
    public void onStop(){
        super.onStop();
        mGoogleApiClient.disconnect();

    }

}

片段

class Tagging_screen extends Fragment {
    Location mLastLocation;
    String URL;
    Button btndownload;
    ImageView imageView;
    EditText editText;
    Button btngallery;
    FloatingActionButton floatbtn;
    LocationManager locationManager;
    GoogleApiClient mGoogleApiClient;
    double latitude, longitude;
    private static final int RESULT_LOAD_IMAGE = 1;
Context mContext;
    // private static final int RESULT_OK = 2;
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.tagging_screen, null);
        imageView = (ImageView) v.findViewById(R.id.imageView);
        editText = (EditText) v.findViewById(R.id.editText_download);
        btndownload = (Button) v.findViewById(R.id.btn_download);
        btngallery = (Button) v.findViewById(R.id.button_gallery);
        floatbtn = (FloatingActionButton) v.findViewById(R.id.floatbutton);
        locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
mContext = getActivity();
        return v;

    }

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
//        latitude = getArguments().getDouble("latitude");
   //     longitude = getArguments().getDouble("longitude");


        floatbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


            }
        });


        btndownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                URL = editText.getText().toString();
                Picasso.with(getActivity()).load(URL).into(imageView);
            }
        });
        btngallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RESULT_LOAD_IMAGE && resultCode == getActivity().RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getActivity().getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);

            assert cursor != null;
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            Log.d("ActivityResult", "OnActivityResult");
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

        }


    }




}

【问题讨论】:

标签: android android-fragments android-activity


【解决方案1】:

您已经在 Activity 中引用了 Fragment (Tagging_screen tagging_screen;),因此在 Fragment 类 Tagging_Screen 中声明一个公共方法,如下所示,然后调用 tagging_screen.setLatAndLongt(lat, longt ) 来自您的活动。

在 Tagging_Screen.java 中添加以下方法

public void setLatAndLongt(double lat, double longt){
    latitude = lat;
    longitude = longt;
}

【讨论】:

  • 如何使用这个值?我尝试在 Fragment 中的 OnActivityCreated 中制作 Toast,但两个值都是 0。
  • onConnected 在 Activity 中的 onCreate 方法之后开始,我在其中创建了一个片段。在 onCreate 中的值为 0。在片段中它们为 0。如何解决?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多