错误:找不到符号方法getSupportActionBar(),findViewById(int),getApplicationContext()

时间:2017-01-03 21:56:25

标签: java android android-fragments

所以我在ScheduleFragment中有这个代码,我的目标是查看一个简单的日历查看器。但不幸的是,它在标题中提到了一个错误。即使我将“public class ScheduleFragment extends Fragment”更改为“public class ScheduleFragment extends AppCompatActivity”,它也会给@Override带来错误。

@TargetApi(Build.VERSION_CODES.N)
public class ScheduleFragment extends Fragment {

CompactCalendarView compactCalendar;
private SimpleDateFormat dateFormatMonth = new SimpleDateFormat("MMM - yyyy", Locale.getDefault());


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


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_schedule, container, false);

    final ActionBar actionBar =     getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(false);
    actionBar.setTitle(null);

    compactCalendar = (CompactCalendarView) findViewById(R.id.compactcalendar_view);
    compactCalendar.setUseThreeLetterAbbreviation(true);

    Event ev1 = new Event(Color.RED, 1477040400000L, "Teachers' Professional Day");
    compactCalendar.addEvent(ev1);

    compactCalendar.setListener(new CompactCalendarView.CompactCalendarViewListener() {
        @Override
        public void onDayClick(Date dateClicked) {
            Context context = getApplicationContext();
            if (dateClicked.toString().compareTo("Fri Oct 21 00:00:00 AST 2016") == 0) {
                Toast.makeText(context, "Teachers' Professional Day", Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(context, "No Events Planned for that day", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onMonthScroll(Date firstDayOfNewMonth) {
            actionBar.setTitle(dateFormatMonth.format(firstDayOfNewMonth));
        }
    });

}                  

}

2 个答案:

答案 0 :(得分:3)

在片段中,您无法直接致电findViewById()并且必须使用刚刚充气的视图并在其上调用findViewById()
所以你的onCreateView代码将是,

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View v = inflater.inflate(R.layout.fragment_schedule, container, false);
    compactCalendar = (CompactCalendarView) v.findViewById(R.id.compactcalendar_view); 
   //Make sure that the view inflated above has these view elements which you are trying to initialize
    .
    .
    .
    }

对于getApplicationContext()同样,您首先需要致电getContext(),然后在其上调用getApplicationContext() 所以它变成了,

Context c = getContext().getApplicationContext();

getSupportActionBar();

也是如此

答案 1 :(得分:0)

在我看来,你应该给视图充气并使用 view.findViewByID(R.id.id), 然后在方法结束时调用return。