【问题标题】:fragment does not go to activity [Android]片段不去活动 [Android]
【发布时间】:2021-06-09 06:04:45
【问题描述】:

我学习 Android 还不到一周。试图创建一个项目,但有些东西不起作用。

问题:不从片段移动到活动

尝试过:在 Google 上浏览文档。而我用@Override for onclickListener in HomeFragment.java 出现了一条红线,醒醒remove,但还是不知道错误是什么。

HomeFragment.java

public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;
    private Button btn_today;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel = new ViewModelProvider(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_home, container, false);

        ViewGroup root_view = (ViewGroup)inflater.inflate(R.layout.fragment_home, container, false);

        Button btn_today = (Button)root_view.findViewById(R.id.btn_today);

        btn_today.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
            Intent intent = new Intent(getActivity(), HomeActivity.class);
            startActivity(intent);
            }
        });

        return root;
    }


}

在我第一次创建项目时使用了Navigation Drawer Activity

什么I want to do is click on the button btn_today to go to the activity page (in xml file)

我是初学者,或者我不知道问题出在哪里。感谢任何帮助 整天都在做,但我不确定。

【问题讨论】:

  • 此刻,如果你点击按钮会发生什么?你得到一个空指针异常吗?
  • 使用按钮 btn_today = (Button)root.findViewById(R.id.btn_today);当您在 onCreateView() 上返回 root 时
  • Sanjid Chowdhury // 单击按钮时对您的值没有任何操作。不过我已经解决了谢谢。

标签: android android-fragments android-activity fragment


【解决方案1】:

您应该使用根变量来查找按钮视图 ID。

Button btn_today = (Button)root.findViewById(R.id.btn_today);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-12
    • 2012-09-20
    相关资源
    最近更新 更多