我创建了一个像图库之类的android应用,它使用片段标签提供了一些图像
功能正常,但是当我在代码中添加setOnItemClickListener时显示错误
错误:无法解析方法'getApplicationContext()
您还可以检查错误的屏幕截图:http://prntscr.com/kc6zay
请查看我的代码并指导我如何解决此问题。
public class CallFragment extends Fragment {
@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
setHasOptionsMenu(true);
View view = inflater.inflate(R.layout.fragment_call,container,false);
GridView gridView = (GridView) view.findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(view.getContext())); // uses the view to get the context instead of getActivity().
// Listening to GridView item click
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Launch ImageViewPager.java on selecting GridView Item
Intent i = new Intent(getApplicationContext(), ImageViewPager.class);
// Show a simple toast message for the item position
//Toast.makeText(CallFragment.this, "" + position, Toast.LENGTH_SHORT).show();
// Send the click position to ImageViewPager.java using intent
i.putExtra("id", position);
// Start ImageViewPager
startActivity(i);
}
});
}
// public View onCreateView(LayoutInflater inflater, ViewGroup container,
// Bundle savedInstanceState) {
// Inflate the layout for this fragment
// setHasOptionsMenu(true);
// return inflater.inflate(R.layout.fragment_call, container, false);
// }
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_calls, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_call) {
Toast.makeText(getActivity(), "Clicked on " + item.getTitle(), Toast.LENGTH_SHORT)
.show();
}
return true;
}
}
答案 0 :(得分:0)
尝试一下:
在CallFragment
private Context context;
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
在您的onItemClick
Intent i = new Intent(context, ImageViewPager.class);
答案 1 :(得分:0)
您不以getApplicationContext
开始活动。
使用getActivity()
:
Intent i = new Intent(getActivity(), ImageViewPager.class);