为什么OnClickListener在Fragment中不能用作Alertdialog

时间:2018-11-21 19:36:17

标签: android fragment alertdialog

我正在使用一个片段作为警报对话框。在片段内部,我有一个onclick侦听器,但不会触发。我该怎么办?

用作警报对话框代码的片段:

        AlertDialog.Builder mBuilder = new AlertDialog.Builder(v.getContext());
            View mview = getLayoutInflater().inflate(R.layout.fragment_add_opskrift, null);
            mBuilder.setView((mview));
            AlertDialog dialog = mBuilder.create();
            dialog.show();

片段代码内的Onclicklistener:

public class AddOpskrift extends Fragment  {

            private static  final int RESULT_LOAD_IMAGES = 1;
            TextView filepath_name;

  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    View view = inflater.inflate(R.layout.fragment_add_opskrift, container, false);

    filepath_name = (TextView) view.findViewById((R.id.billede_path)) ;


    Button soeg_billede = (Button) view.findViewById(R.id.billede_button);
    soeg_billede.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(galleryIntent, RESULT_LOAD_IMAGES);


        }

    });

    return view;

Xaml:

<Button
        android:id="@+id/billede_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="70dp"
        android:layout_marginRight="70dp"
        android:background="@color/colorPrimary"
        android:drawableRight="@drawable/ic_add_photo_white"
        android:padding="10dp"
        android:text="Tilføj billede "
        android:textColor="@color/white" />

2 个答案:

答案 0 :(得分:0)

AlertDialog 中使用片段的布局与实际使用DialogFragment

有区别 自 API 28 起,不推荐使用

DialogFragment

  

该类已在API级别28中弃用。   使用支持库DialogFragment 在所有设备上实现一致的行为并访问生命周期。

答案 1 :(得分:0)

此代码:

Button soeg_billede = (Button) mview.findViewById(R.id.billede_button);
soeg_billede.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(galleryIntent, RESULT_LOAD_IMAGES);
    }
});
在显示带有dialog.show();的对话框之前,应写


对于mview

,所需的更改是view而不是findViewById()