gpt4 book ai didi

java - 通过 Java 访问 fragment 中的 CalendarView

转载 作者:行者123 更新时间:2023-12-02 01:24:26 24 4
gpt4 key购买 nike

我想在 Fragment 中使用 CalendarView,但我不知道如何通过 Java 访问它。首先,我只想在 toast 中显示选定的日期,但如果我单击日期,似乎不会调用该函数。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Fragments.SchedulerFragment">
<CalendarView
android:id="@+id/scheduler_calendar"
android:layout_width="match_parent"
android:layout_height="match_parent"></CalendarView>
</RelativeLayout>
public class SchedulerActivity extends AppCompatActivity {
private CalendarView calendarView;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
calendarView = (CalendarView) findViewById(R.id.scheduler_calendar);

calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
@Override
public void onSelectedDayChange(CalendarView calendarView, int i, int i1, int i2) {
Toast.makeText(SchedulerActivity.this, "Date changed to" + i2 + "." + i1 + "." + i, Toast.LENGTH_SHORT).show();
}
});
}
}

最佳答案

onViewCreated 方法中设置 setOnDateChangeListener 并在 Toast 中使用 getActivity()。我测试了下面的代码并且它可以工作。

public class SchedulerFragment extends Fragment {

private CalendarView calendarView;

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


@Override
public void onViewCreated(@NonNull final View view, @Nullable final Bundle savedInstanceState) {
calendarView = view.findViewById(R.id.scheduler_calendar);
calendarView.setOnDateChangeListener(new OnDateChangeListener() {
@Override
public void onSelectedDayChange(@NonNull final CalendarView view, final int year, final int month,
final int dayOfMonth) {
Toast.makeText(getActivity(), "Date changed to" + dayOfMonth + "." + month + "." + year, Toast.LENGTH_SHORT).show();
}
});
}

@Override
public View onCreateView(
@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_scheduler, container, false);
return root;
}

}

关于java - 通过 Java 访问 fragment 中的 CalendarView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57160618/

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