无法在ViewPager的Fragment中解析方法'findViewById(int)'

时间:2017-08-31 09:34:33

标签: android android-viewpager

您好,我有一个ViewPager的片段:

package my.test.myapplication;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

public class Fragment1 extends Fragment {

    private Button btn;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // point A
        return  inflater.inflate(R.layout.frag1,container,false);
    }
}

当我在A点下添加它时,会出现一条错误消息:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // point A
    btn = (Button) findViewById(R.id.button);
    return  inflater.inflate(R.layout.frag1,container,false);
}

错误消息:

Cannot resolve method 'findViewById(int)'

我该怎么办?

6 个答案:

答案 0 :(得分:1)

如果想要绑定fragment中的控件而不是首先使用view将布局设置为LayoutInflater而不是view的帮助,请尝试此操作你可以像这样绑定你的所有控件

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.frag1,container,false);
        btn = (Button) rootView.findViewById(R.id.button);
        return rootView  ;
    }

答案 1 :(得分:1)

如果要访问任何视图,可以使用视图对象来访问它。

  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
          View view =   inflater.inflate(R.layout.frag1,container,false);
         btn = (Button)view.findViewById(R.id.button);

       return view;
   }

答案 2 :(得分:0)

OnViewCreated()方法中尝试以下代码:

btn = (Button) view.findViewById(R.id.button);

答案 3 :(得分:0)

试试

 view.findViewById(R.id.expandable);

答案 4 :(得分:0)

您可以尝试这样:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
{
  View rootView = inflater.inflate(R.layout.frag1, container, false);
  btn = (Button)rootView.findViewById(R.id.button);
  return  rootView ;
}

答案 5 :(得分:0)

Fragment不是Activity的子类。

您必须在findViewById(R.id.*id*);对象上致电Activity

请参阅API