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

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

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

这就是我想要的 - 当用户点击FAB时,它应该将来自restaurantDetailsActivity的latlon传递到我的地图片段并放大到该位置(基于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);
            }
        });
    }
}
java android google-maps android-fragments parameter-passing
2个回答
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
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.