从片段中显示Toast - 没有合适的makeText方法

时间:2016-07-26 15:50:37

标签: android

我有这个代码: -

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;

public class Tab3 extends android.support.v4.app.Fragment {
    private static final String ARG_SECTION_NUMBER = "section_number";
    private ToggleButton toggleButton1, toggleButton2;
    private Button btnDisplay;
    public void addListenerOnButton(View v) {


        toggleButton1 = (ToggleButton) v.findViewById(R.id.toggleButton1);
        toggleButton2 = (ToggleButton) v.findViewById(R.id.toggleButton2);
        btnDisplay = (Button) v.findViewById(R.id.btnDisplay);
        btnDisplay.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                StringBuffer result = new StringBuffer();
                result.append("toggleButton1 : ").append(
                        toggleButton1.getText());
                result.append("\ntoggleButton2 : ").append(
                        toggleButton2.getText());

                Toast.makeText(Tab3.this, result.toString(),
                        Toast.LENGTH_SHORT).show();

            }

        });

    }

    public static Tab3 newInstance(int sectionNumber) {
        Tab3 fragment = new Tab3();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v =inflater.inflate(R.layout.tab3,container,false);
        addListenerOnButton(v);
        return v;
    }
}

它是切换按钮,标签页中有一些消息 我在这部分下面有红线: -

Toast.makeText(Tab3.this, result.toString(),
                        Toast.LENGTH_SHORT).show();

出现此错误: -

  

错误:(32,22)错误:找不到合适的方法   makeText(Tab3,String,int)方法   Toast.makeText(Context,CharSequence,int)不适用(参数   不匹配; Tab3无法转换为Context)方法   Toast.makeText(Context,int,int)不适用(参数不匹配;   Tab3无法转换为上下文)

任何人都可以帮助我吗?

3 个答案:

答案 0 :(得分:2)

makeText需要Context作为第一个参数

Tab3FragmentFragment不是Context。而不是Tab3.this,请使用Tab3.this.getContext()

答案 1 :(得分:1)

尝试使用而不是Tab3.this,请使用:getActivity()

答案 2 :(得分:0)

按照以下步骤操作: 1.Declare Context as global。

Context context;

2.在onCreateView上写下代码:

 context = container.getContext();

3.声明需要的上下文。

Toast.makeText(context, result.toString(),
                        Toast.LENGTH_SHORT).show();