有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

所以我的ScheduleFragment中有这段代码,我的目标是查看一个简单的日历查看器。但不幸的是,标题中提到了一个错误。即使我将“public class ScheduleFragment Extendes Fragment”更改为“public class ScheduleFragment Extendes 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) 个答案

  1. # 1 楼答案

    在我看来,你应该放大视图并使用视图。findViewByID(R.id.id), 然后在方法末尾调用return

  2. # 2 楼答案

    在片段中,您不能直接调用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();