【问题标题】:Buttons not working in fragment按钮在片段中不起作用
【发布时间】:2015-06-03 13:53:00
【问题描述】:

我在一个片段中实现了两个按钮,单击它们将转移到两个不同的活动。但是,在单击时,没有任何反应。该应用程序不会强制关闭,调试器也不会显示任何异常。使用 Log.d 我发现 onClick 没有被调用。 我已经提到了这篇文章来实现但是它没有用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;
        }
    }
}

【问题讨论】:

    标签: android button android-activity onclick fragment


    【解决方案1】:

    你必须返回v而不是inflater.inflate(R.layout.fragment_the_other, container, false);inflater.inflate返回一个新对象,并且你还没有注册onClickListener

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-08
      • 2014-10-25
      • 1970-01-01
      相关资源
      最近更新 更多