错误:找不到符号方法getsupportactionbar()、findviewbyid(int)、getapplicationcontext()

khbbv19g  于 2021-07-09  发布在  Java
关注(0)|答案(2)|浏览(264)

所以我在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));
        }
    });

}                  

}
lvjbypge

lvjbypge1#

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

6kkfgxo0

6kkfgxo02#

在我看来,应该膨胀视图并使用view.findviewbyid(r.id.id),然后在方法末尾调用return。

相关问题