getApplicationContext()无法解析片段类中的方法 -

时间:2017-02-19 06:50:40

标签: android android-fragments

这是我的代码

package com.road.apoorv.road;

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.content.Context; 
import android.view.View;
import android.content.Intent;
import android.app.Activity;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;

public class SecondFragment extends Fragment {
View myView;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    myView = inflater.inflate(R.layout.second_layout, container, false);

    GridView gridView = (GridView) myView.findViewById(R.id.gridView);
    gridView.setAdapter(new ImageAdapter(getActivity()));

    return myView;

    gridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
    {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent i = new     Intent(getApplicationContext(),FullImageActivity.class);
            i.putExtra("id", position);
            startActivity(i);
        }
    });

}
}

我尝试过getActivity()。getApplicationContext(),但它显示语句无法访问。

这是我的第一个应用,所以我遇到了几个问题。 提前谢谢

2 个答案:

答案 0 :(得分:0)

您应该使用parent.getContext()

答案 1 :(得分:0)

尝试:

在设置setOnItemClickListener

后再添加此代码
 gridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent i = new  Intent(getActivity().getBaseContext(),FullImageActivity.class);
       i.putExtra("id", position);
       startActivity(i);
    }
});


return myView;   //add it here