从已打开的子活动转到现有片段

时间:2017-12-19 15:14:06

标签: java android google-maps android-fragments parameter-passing

我的应用程序有两个带片段的标签。一个标签名为 地图 ,另一个标签名为 restaurantList 。当我点击地图标记或列表中的卡片时,会打开 restaurantDetailsActivity ,其中包含有关餐馆的信息 - latlang,姓名,我有一个浮动动作按钮,用户应该单击它,它应该关闭当前活动并转到地图选项卡片段,到我从活动传递的位置。我尝试过很多东西而没有取得任何成功:1 2 3 4 5 6 7 {{3} } 8 ...

这就是我想要的 - 当用户点击FAB时,它应该将latlon从restaurantDetailsActivity, 传递到我的地图片段 < / strong>并放大到该位置(基于lat和lon),无论是从列表片段还是地图片段打开。

我的餐厅详细活动:

final String lat = restaurant.getLat();
final String lon = restaurant.getLon();

 FloatingActionButton fabGoToMap = findViewById(R.id.fabGoToMap);
    fabGoToMap.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
//                MapsFragment fragment = new MapsFragment();
//                Bundle bundle = new Bundle();
//                bundle.putString("lat", lat);
//                bundle.putString("lon", lon);
//                MapsFragment mapsFragment = new MapsFragment();
//                mapsFragment.setArguments(bundle);
//                Intent restaurantDescriptionIntent = new Intent(this, MapsFragment.class);
                  Bundle bundle = new Bundle();
                  bundle.putString("lat", lat);
                  bundle.putString("lon", lon);
                  MapsFragment fragInfo = new MapsFragment();
                  fragInfo.setArguments(bundle);
                  android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

//                transaction.add(R.id.map, mapsFragment, "tag").commit();
            finish();
        }
    });

更新代码: 从列表片段调用活动:

public void fetchRestaurant(String restaurantId) {
    ApiInterface apiService =
            ApiClient.getClient().create(ApiInterface.class);

    Call<RestaurantResponse> call = apiService.getRestaurantById(restaurantId);
    call.enqueue(new Callback<RestaurantResponse>() {
        @Override
        public void onResponse(Call<RestaurantResponse> call, retrofit2.Response<RestaurantResponse> response) {
            final Restaurant restaurant= response.body().getResults();

            Intent intent = new Intent(getActivity().getApplicationContext(), AvailableRestaurantActivity.class);
            intent.putExtra("estaurant", estaurant);

            startActivity(intent);
        }

        @Override
        public void onFailure(Call<RestaurantResponse> call, Throwable t) {
            // Log error here since request failed
            Log.e(TAG, t.toString());
            Toast.makeText(getActivity().getApplicationContext(), R.string.failed_connectivity, Toast.LENGTH_LONG).show();
        }
    });
}

我的主要活动:

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

    tutorialUsed = false;
    tutorialPage = 1;


    db = new SQLiteHandler(getApplicationContext());
    // session manager
    session = new SessionManager(getApplicationContext());

    if (!session.isLoggedIn()) {
        Intent intent = new Intent(this, LoginActivity.class);
        startActivity(intent);
    } else {

        List<restaurant> restaurants = new ArrayList<>();

        TabLayout tabLayout = findViewById(R.id.sliding_tabs);
        tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_one)));
        tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_two)));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        tabLayout.setTabMode(TabLayout.MODE_FIXED);

        final ViewPager viewPager = findViewById(R.id.viewpager);
        PagerAdapter adapter = new PagerAdapter
                (getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        viewPager.setOffscreenPageLimit(3);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }
        });
 ....
        myUserName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent accountIntent = new Intent(MainActivity.this, MyProfileActivity.class);
                startActivity(accountIntent);
            }
        });
    }
}

2 个答案:

答案 0 :(得分:2)

使用类似这样的startActivityForResult从MainActivity启动restaurantDetailactivity

startActivityForResult(intent, SHOW_DETAILS_REQUEST);

点击FAB应该是这样的

final String lat = restaurant.getLat();
final String lon = restaurant.getLon();

 FloatingActionButton fabGoToMap = findViewById(R.id.fabGoToMap);
    fabGoToMap.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putString("lat", lat);
            bundle.putString("lon", lon);
            intent.putExtras(bundle);
            setResult(Activity.RESULT_OK,intent);
        }
    });
在您的MainActivity处理活动结果中

,如下所示

@Override
protected void onActivityResult(final int requestCode,
                                final int resultCode,
                                final Intent data) {
    if (resultCode == RESULT_OK) {
        switch (requestCode) {
            case SHOW_DETAILS_REQUEST: {
                //select mapfragment as current, assuming it is at index 0
                viewpager.setCurrentItem(0);
                //add your zoom logic here in zoomToCenter method
                mapfragment.zoomToCenter(data.getStringExtra("lat"),data.getStringExtra("lon"));
            }
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
}

答案 1 :(得分:1)

Kemo,您有一个事件发生在一个片段中,并且由于该事件您希望活动将一个片段交换为第二个片段。所以你的问题是如何从片段到活动进行通信。附加的片段将为您提供活动的上下文。活动应该有一个方法来交换碎片进出,并使用你在附加中获得的上下文,你可以在碎片oncreateview中使用并运行活动的方法。here祝你好运教授