gpt4 book ai didi

java - 我在 onAttach(Context) 中收到这个奇怪的错误

转载 作者:太空宇宙 更新时间:2023-11-03 13:50:07 24 4
gpt4 key购买 nike

onAttach 函数中,eclipse 显示错误说明

The method onAttach(Activity) in the type Fragment is not applicable for the arguments (Context)

虽然明明是传递的Context类型变量

import android.content.Context;

public class MyListFragment extends Fragment{
private OnItemSelectedListener listener;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_rsslist_overview,
container, false);
Button button = (Button) view.findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updateDetail("fake");
}
});
return view;
}

public interface OnItemSelectedListener {
public void onRssItemSelected(String link);
}

@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnItemSelectedListener) {
listener = (OnItemSelectedListener) context;
} else {
throw new ClassCastException(context.toString()
+ " must implemenet MyListFragment.OnItemSelectedListener");
}
}

@Override
public void onDetach() {
super.onDetach();
listener = null;
}

// may also be triggered from the Activity
public void updateDetail(String uri) {
// create a string just for testing
String newTime = String.valueOf(System.currentTimeMillis());

// inform the Activity about the change based
// interface defintion
listener.onRssItemSelected(newTime);
}
}

最佳答案

如果您使用的是 API < 23 那么

public void onAttach(Context context) {

应该是

public void onAttach(Activity context) {

参见 official docs

注意:

onAttach(Context context) 已添加到 api 23 中。参见 this

关于java - 我在 onAttach(Context) 中收到这个奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36058226/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com