CalendarView在片段中不起作用?安卓

huangapple go评论89阅读模式
英文:

CalendarView does not work in fragments? Android

问题

如果我在xml文件中为主要活动添加一个CalendarView,然后在主要活动中编写一些代码:

public class MainActivity extends AppCompatActivity {
    private CalendarView mCalendarView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mCalendarView = findViewById(R.id.calendarView);
        mCalendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
                String date =  year + "/" + month + "/" + dayOfMonth;
                Log.wtf("wtf", "onSelectedDayChange" + date);
            }
        });
    }
}

setOnDateChangeListener将按预期工作,Log.wtf将被执行。

如果我尝试在一个片段的xml文件中添加一个CalendarView,日历将出现在片段中,我可以点击日期。但由于某种原因,setOnDateChangeListener不起作用。这是我片段的代码。抱歉,这是默认代码,所以有点多。我是新手使用片段,所以我不确定什么是所有重要的。我在onCreateView方法中实现了setOnDateChangeListener。

public class ThirdFragment extends Fragment {
    private CalendarView mCalendarView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_third, container, false);
        mCalendarView = (CalendarView) view.findViewById(R.id.calendarView);
        mCalendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
                String date =  year + "/" + month + "/" + dayOfMonth;
                Log.wtf("wtf", "onSelectedDayChange" + date);
            }
        });

        return view;
    }
}

但不知何故,setOnDateChangeListener不起作用。我真的不知道为什么这不起作用,因为我在项目中有其他片段,我在其中有按钮,按钮点击事件是有效的,我是这样实现的:

public class YourFragment extends Fragment {
    private OnFragmentInteractionListener mListener;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.your_fragment_layout, container, false);
        Button button = view.findViewById(R.id.your_button_id);
        button.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               mListener.yourMethod(); // 这里调用与活动通信的方法
           }
        });
        return view;
    }
}
英文:

So if I create a new project and throw a calanderView into the xml file for the main activity. Then write some code in the main activity

public class MainActivity extends AppCompatActivity {
    private CalendarView mCalendarView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mCalendarView = findViewById(R.id.calendarView);
        mCalendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
                String date =  year + "/" + month + "/" + dayOfMonth;
                Log.wtf("wtf","onSelectedDayChange" + date);
            }
        });
    }
}

The setOnDateChangeListener will work as expected and Log.wtf will execute.

If I try to throw a calanderView into a xml file for a fragment. The calendar will appear in the fragment and I can click on dates. But for some reason the setOnDateChangeListener does not work. Here is my code for my fragment. Sorry its the default code so there is kind of a lot. I am new to using fragments so I am not sure whats all important. I implemented the setOnDateChangeListener in the onCreateView method.

public class ThirdFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public ThirdFragment() {
        // Required empty public constructor
    }

    
    // TODO: Rename and change types and number of parameters
    public static ThirdFragment newInstance(String param1, String param2) {
        ThirdFragment fragment = new ThirdFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    private CalendarView mCalendarView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_third, container, false);
        mCalendarView = (CalendarView) view.findViewById(R.id.calendarView);
        mCalendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
                String date =  year + "/" + month + "/" + dayOfMonth;
                Log.wtf("wtf","onSelectedDayChange" + date);
            }
        });

        return inflater.inflate(R.layout.fragment_third, container, false);
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

I honestly have no idea why this does not work because I have other fragments in my project where I have buttons where the button click event works and I implemented those like this:

private OnFragmentInteractionListener mListener;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_login, container, false);
        button2 = view.findViewById(R.id.btn_register);
        button2.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               // IMPORTANT this interface can send stuff back to the main activity
               mListener.register();
           }
        });
        return view;
}

If anyone could give me some insight it would be much appreciated!

答案1

得分: 0

在 Fragments 中,如果你没有使用 binding,那么在 onCreateView 方法中,你只应该填充并返回视图。然后在 onViewCreated 方法中处理你的代码,因为这会确保你获取到了填充的视图并且视图不为空

你还应该查看Fragment 生命周期方法。这样你就会理解 Fragment 是如何与 Activity 一起工作的。

英文:

In Fragments, if you're not using binding then in onCreateView method you should only inflate and return the view.. And do your code stuff in onViewCreated as it makes sure that your get the inflated view and the view is not null.

You should also look for Fragment Lifecycle Methods.
That way you'll understand how Fragments works along with Activity.

答案2

得分: 0

你需要在onCreateView方法中返回与您在其中填充的view对象相同的对象。修改您的onCreateView方法如下:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_third, container, false);
    mCalendarView = (CalendarView) view.findViewById(R.id.calendarView);
    mCalendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
        @Override
        public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
            String date =  year + "/" + month + "/" + dayOfMonth;
            Log.wtf("wtf","onSelectedDayChange" + date);
        }
    });

    return view;  // 而不是返回 inflater.inflate(R.layout.fragment_third, container, false);
}
英文:

You need to return the same view object which you have inflated in onCreateView method. Modify your onCreateView method like this:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_third, container, false);
        mCalendarView = (CalendarView) view.findViewById(R.id.calendarView);
        mCalendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
            @Override
            public void onSelectedDayChange(CalendarView view, int year, int month, int dayOfMonth) {
                String date =  year + "/" + month + "/" + dayOfMonth;
                Log.wtf("wtf","onSelectedDayChange" + date);
            }
        });

        return view;  //instead of inflater.inflate(R.layout.fragment_third, container, false);
    }

huangapple
  • 本文由 发表于 2020年10月13日 14:52:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/64330046.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定