Question

I'm using Fragments. I need the class extending FragmentActivity to implement interface that serves as listener from my fragments. When I click on an item from gridview, it fires onItemClick method, but the listener variable is null even though I set it in GamePlayActivity.

My understanding is that I'm working on 2 different things when I instantiate my fragment to set listener and when onCreateView() is called on my fragment class.

The sample from Google does the same implementation with onClick and it works. Not on mine.

MainActivity extending FragmentActivity and Fragment class for example.

Fragment 1

public class FragmentOne extends Fragment implements OnItemClickListener {

    Listener listener = null;

    interface Listener {
        public void applyGameLogic();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        View layout = inflater.inflate(R.layout.fragment_fragpane, container, false);
        GridView gridView = (GridView) layout.findViewById(R.id.grid);
        gridView.setAdapter(new ImageAdapter(layout.getContext()));

        gridView.setOnItemClickListener(this);

        return layout;
    }

    public void setListener(Listener listener) {
        this.listener = listener;
    }

    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        //listener.applyGameLogic(); this listener is null
    }
}

GamePlayActivity

public class GamePlayActivity extends FragmentActivity implements WordPane.Listener, ChainPane.Listener {

    private FragmentOne fragment1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
            setContentView(R.layout.game_container);

        fragment1 = new FragmentOne();

        fragment1.setListener(this);
    }

    ... applyGameLogic method follows but its empty for now
}
Was it helpful?

Solution

fragment1 = new FragmentOne();
fragment1.setListener(this);

You are creating a new instance of FragmentOne and then assigning the click listener to that new instance. Instead, you should find the existing fragment in your layout

FragmentManager fm = getSupportFragmentManager(); // or getFragmentManager() if you aren't using the support library
fragment1 = (FragmentOne)fm.findFragmentById(R.id.fragment_one);

and then set your listener

fragment1.setListener(this);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top