使用按钮从片段到 activity。 Android 工作室

Going from fragment to activity with a button. Android Studio

我正在尝试在 Android Studio 中实施下一个代码,但它不起作用。 我想通过一个按钮从片段 (GalleryFragment) 传递到 Activity (postropa)。 我已将按钮与函数 (BotonPulsado) 链接起来,但我不知道哪里出了问题(在设计视图中)。

Design View

代码:

import (...)

public class GalleryFragment extends Fragment {

    private GalleryViewModel galleryViewModel;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        galleryViewModel =
                ViewModelProviders.of(this).get(GalleryViewModel.class);
        View root = inflater.inflate(R.layout.fragment_gallery, container, false);
        final TextView textView = root.findViewById(R.id.text_gallery);
        galleryViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);
            }
        });
        return root;
    }

    public void BotonPulsado(View view) {
        Intent intent = new Intent(getContext(), postropa.class);
        startActivity(intent);
    }
}

您应该创建 Button 变量作为 class 字段。

private GalleryViewModel galleryViewModel;
Button button; <<-------

之后需要在方法中定义onCreateView()

 button = (Button) findViewById(R.id.button2);

并在此按钮上设置 onClickListener() 以处理呼叫。 您必须在那里调用启动 activity.

的方法
button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            BotonPulsado();
        }
    });

您的最终代码:

import (...)

public class GalleryFragment extends Fragment {

    private GalleryViewModel galleryViewModel;
    Button button;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        galleryViewModel =
                ViewModelProviders.of(this).get(GalleryViewModel.class);
        View root = inflater.inflate(R.layout.fragment_gallery, container, false);
        final TextView textView = root.findViewById(R.id.text_gallery);
        galleryViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);
            }
        });
        button = (Button) findViewById(R.id.button2);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                BotonPulsado();
            }
        });
        return root;
    }

    public void BotonPulsado() {
        Intent intent = new Intent(getContext(), postropa.class);
        startActivity(intent);
    }
}