为什么片段不能在导航抽屉中打开?
问题描述:
我MainActivity.java包含为什么片段不能在导航抽屉中打开?
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId())
{
case R.id.calendar:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container, new Calender());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Calender");
item.setChecked(true);
break;
// drawer.closeDrawers();
}
return true;
}
});
和我Calender.java包含
public class Calender extends android.support.v4.app.Fragment{
Activity a;
CalendarView calendar;
public Calender() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
a = new Activity();
a.setContentView(R.layout.fragment_calender);
initializeCalendar();
return inflater.inflate(R.layout.fragment_calender, container, false);
}
public void initializeCalendar() {
calendar = (CalendarView) a.findViewById(R.id.calendar);
// sets whether to show the week number.
calendar.setShowWeekNumber(false);
// sets the first day of week according to Calendar.
// here we set Monday as the first day of the Calendar
calendar.setFirstDayOfWeek(2);
//The background color for the selected week.
calendar.setSelectedWeekBackgroundColor(getResources().getColor(R.color.green));
//sets the color for the dates of an unfocused month.
calendar.setUnfocusedMonthDateColor(getResources().getColor(R.color.transparent));
//sets the color for the separator line between weeks.
calendar.setWeekSeparatorLineColor(getResources().getColor(R.color.transparent));
//sets the color for the vertical bar shown at the beginning and at the end of the selected date.
calendar.setSelectedDateVerticalBar(R.color.darkgreen);
//sets the listener to be notified upon selected date change.
calendar.setOnDateChangeListener(new OnDateChangeListener() {
@Override
public void onSelectedDayChange(CalendarView view, int year, int month, int day) {
Toast.makeText(a.getApplicationContext(), day + "/" + month + "/" + year, Toast.LENGTH_LONG).show();
}
});
}
}
有我的片段的任何问题?还是主要活动?请尽快帮助。该应用程序打开,但我试图点击日历按钮,nothins显示。
答
为什么你的片段中有一个活动实例? 您onCreateView更改为:
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.content_main, parent, false);
calendar = (CalendarView) view.findViewById(R.id.calendar);
return view;
}
,然后在onViewCreated方法做到这一点:
initializeCalendar();
确保在content_main日历视图的ID是日历。
'a = new Activity();'...永远不要做一个'new Activity()' –
@Mohendra是否有效? – Heisenberg
不,http://stackoverflow.com/questions/38654653/why-is-calendar-in-navigation-drawer-not-working/38654768?noredirect=1#comment64692360_38654768继承人我已经给了整个代码的链接,请看到它 – Mohendra