我的菜单选项按钮与获取 HTTP 数据的类在不同的类中。它给我“PhotoGalleryFragment is not an enclosing class”错误
new PhotoGalleryFragment.FetchItemsTask("top-rated").execute();
PhotoGalleryActivity.java - 在这里,我试图做到这一点,当按下“评分最高的电影”按钮时,它会传递“评分最高”的参数供 FetchItemsTask 运行并更改 API url 并更改返回从“流行”到“顶级”的 JSON
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.topRatedMovies) {
Toast.makeText(getApplicationContext(), "Top Rated Movie selected", Toast.LENGTH_LONG).show();
new PhotoGalleryFragment.FetchItemsTask("top-rated").execute();
return true;
}
return super.onOptionsItemSelected(item);
}
PhotoGalleryFragment.java - 在这里,我试图获取数据。
public class FetchItemsTask extends AsyncTask<Void,Void,List<MovieItem>> {
private String mQuery;
public FetchItemsTask(String query) {
mQuery = query;
}
@Override
protected List<MovieItem> doInBackground(Void... params) {
return new MovieFetchr().fetchItems(mQuery);
}
@Override
protected void onPostExecute(List<MovieItem> items) {
mItems = items;
for (int i = 0; i < mItems.size(); i++) {
}
setupAdapter();
}
}
我该如何解决这样的问题?谢谢。
最佳答案
要创建内部类,您需要从外部类的实例中创建内部类或将内部类设置为static
:
因此,在 PhotoGalleryFragment
中创建实例:
public class PhotoGalleryFragment {
void createTask(String query) {
new FetchItemsTask(query); //return it if you like, or just call execute here, doesn't matter
}
}
或者:
public static class FetchItemsTask
但我认为您需要执行第一个选项,因为 setupAdapter
可能是 PhotoGalleryFragment
上的一个方法。
通过在 PhotoGalleryFragment
中创建,这为内部类提供了对 PhotoGalleryFragment
的引用,这是它能够调用方法的方式。
把它想象成一个静默的构造函数参数和字段,它的作用很像这段代码,只是你不费吹灰之力:
public class FetchItemsTask extends AsyncTask<Void,Void,List<MovieItem>> {
private final PhotoGalleryFragment outer;
public FetchItemsTask(PhotoGalleryFragment outer, //a reference to the outer is passed in automatically
String query) {
this.outer = outer; //and stored in this FetchItemsTask instance
}
@Override
protected void onPostExecute(List<MovieItem> items) {
outer.setupAdapter(); //then used when outer methods are invoked
}
}
关于java - 不是封闭类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35210910/