如何在片段内加载新活动而不丢失底部导航栏

时间:2019-05-14 11:55:48

标签: java android

正如标题中所述,当我单击图像图块时,在“主页片段”上时,我希望加载新活动,但我希望保持导航栏可见。当前,活动下方的代码开始,但导航栏消失。我想要帮助编写代码,以便活动开始但导航栏保持不变。

public class HomeFragment extends Fragment {

private ImageView imageCbt;
private ImageView imageDistorted;

@Nullable
@Override
public android.view.View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_home, container, false);

}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);

    // get the button view
    imageCbt = getView().findViewById(R.id.whatIsCbt);
    imageDistorted = getView().findViewById(R.id.distortedThinking);

    // set a onclick listener for when the button gets clicked
    imageCbt.setOnClickListener(new View.OnClickListener() {
        // Start new list activity
        public void onClick(View v) {
            Intent mainIntent = new Intent(getActivity(),
                    IntroActivity2.class);
            startActivity(mainIntent);
        }
    });

    imageDistorted.setOnClickListener(new View.OnClickListener() {
        // Start new list activity
        public void onClick(View v) {
            Intent mainIntent = new Intent(getActivity(),
                    TwelveTypesDistortedThinkingActivity.class);
            startActivity(mainIntent);



        }
    });

}

2 个答案:

答案 0 :(得分:0)

要更改当前片段,您可以将点击侦听器中的代码替换为该片段(Replacing a fragment with another fragment inside activity group):

Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack if needed
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

然后,您需要将您的活动转换为Fragment(可能需要一些重构),并在onClickListener方法中更改当前的片段。

PS:使用导航栏时,片段是应用程序体系结构中的最佳实践。

答案 1 :(得分:0)

像这样FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.frame_container, yourFragment); transaction.addToBackStack(null); transaction.commit();

替换OnNavigationItemSelectedListener上的片段

有关完整的教程Android Working with Bottom Navigation