gpt4 book ai didi

android - 如何将Onclick监听器设置为 fragment 中的按钮

转载 作者:行者123 更新时间:2023-11-29 17:33:41 25 4
gpt4 key购买 nike

我在 fragment1 中有按钮。我想单击此按钮并用 fragment 2 替换 fragment ,但是当我尝试运行它时我的应用程序仍然关闭

这是 fragment 1 中的代码

   @Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

View rootView = inflater.inflate(R.layout.layout_menu, container, false);

// gallery = (Gallery) rootView.findViewById(android.R.id.list);
//gallery.setAdapter(new ItemAdapter(generateData(), getActivity()));
Button button = (Button) rootView.findViewById(R.id.imageButtonAll);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
HomeFragment homeFragment = new HomeFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, homeFragment);
transaction.commit();

}

});

return rootView;

}

}

最佳答案

您无法从另一个 fragment 中打开一个 fragment 。因此,您必须将代码从 onClick 移动到您的 Activity 并在那里运行。

在您的 Activity 中(假设其 MainActivity):

public void openMyFragment(){
HomeFragment homeFragment = new HomeFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.frame_container, homeFragment);
transaction.commit();
}

然后,将此添加到您的 onClick fragment 中:

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
((MainActivity) getActivity()).openMyFragement();
}

});

关于android - 如何将Onclick监听器设置为 fragment 中的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31671745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com