static95
static95

Reputation: 33

Buttons not working in fragment

I'm implementing two buttons in a fragment which on getting clicked will transfer to two different activities. However on clicking, nothing happens. The app does not force close nor the debugger shows any exception. Using Log.d I found that onClick is not getting called. I had referred this post for implementing however it didn't work Multiple Buttons In Fragment Class Issue?

Here is my code

TheOtherFragment.java

package com.tct.level4;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class TheOtherFragment extends Fragment implements View.OnClickListener {
    Context context;
    private Button sound;
    private Button vib;
    View v;

    public TheOtherFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.fragment_the_other, container, false);
        context = container.getContext();
        sound = (Button) v.findViewById(R.id.sound);
        vib = (Button) v.findViewById(R.id.vibration);
        Log.d("onactivity", "called");
        sound.setOnClickListener(this);
        vib.setOnClickListener(this);
        return inflater.inflate(R.layout.fragment_the_other, container, false);
    }

    @Override
    public void onClick(View va) {
        switch (va.getId()) {
            case R.id.vibration: 
                Log.d("vib","1");
                Intent intent = new Intent(context, Vib.class);
                startActivity(intent);
                Log.d("vib","2");
                break;

            case R.id.sound: 
                Log.d("sound","1");
                Intent inten = new Intent(context, Ring.class);
                startActivity(inten);
                Log.d("sound","2");
                break;
        }
    }
}

Upvotes: 2

Views: 754

Answers (1)

Blackbelt
Blackbelt

Reputation: 157457

you have to return v instead of inflater.inflate(R.layout.fragment_the_other, container, false);, inflater.inflate returns a new object, and on it you haven't register the onClickListener

Upvotes: 1

Related Questions