Nicholas Muir Nicholas Muir - 3 months ago 16
Android Question

Appcompat activity required as argument for function used in fragment

I am using an external library in my app. The first argument used in the example is "this". Which refers to an appcompat activity. However I am using this in a fragment shich obviously doesn't extend appcompat activity.

This is the library:

https://github.com/TouchBoarder/weekdays-buttons-bar

I am not sure whether there is anything I can do. Can I extend the fragment to something compatible (right now it just extends fragment).

Below is a screenshot of the issue:

enter image description here

EDIT:

This is what I extend in my MainActivity:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {


The Fragment that is called innside Main activity is extended like this:

public class AddAlarmFragment extends Fragment {


And I am trying to create the data source in the oncreate method of the fragment like this:

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


WeekdaysDataSource wds = new WeekdaysDataSource(, R.id.weekdays_stub)
.start(this);



new WeekdaysDataSource.Callback() {
@Override
public void onWeekdaysItemClicked(int attachId,WeekdaysDataItem item) {
// Do something if today is selected?
Calendar calendar = Calendar.getInstance();
if(item.getCalendarDayId()==calendar.get(Calendar.DAY_OF_WEEK)&&item.isSelected())
Toast.makeText(getActivity(),"Carpe diem",Toast.LENGTH_SHORT).show();
}

@Override
public void onWeekdaysSelected(int attachId,ArrayList<WeekdaysDataItem> items) {
//Filter on the attached id if there is multiple weekdays data sources
if(attachId==R.id.weekdays_stub){
// Do something on week 4?
}
}

};


Thanks in advance for your help.

Answer

Have you tried casting getActivity()?

((AppCompatActivity) getActivity(), R.id.weekdays_stub) 

Read the Android API, you can see AppCompatActivity does extend FragmentActivity and getActivity() does return a FragmentActivity, not an AppCompatActivity, as expected by your library.

I do find it odd that a AppCompatActivity is even the defined parameter rather than a Context