按钮在片段中不起作用

Buttons not working in fragment

我在一个片段中实现了两个按钮,点击它们会转移到两个不同的活动。但是单击时,没有任何反应。该应用程序不会强制关闭,调试器也不会显示任何异常。使用 Log.d 我发现没有调用 onClick。 我已经将此 post 用于实施,但它没有用 Multiple Buttons In Fragment Class Issue?

这是我的代码

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;
        }
    }
}

您必须 return v 而不是 inflater.inflate(R.layout.fragment_the_other, container, false);inflater.inflate return 一个新对象,并且您还没有在其上注册 onClickListener