我的第一个应用程序单独运行良好,但现在我尝试按照教程添加选项卡,但我遇到了困难。 我一直在搜索,许多用户遇到了同样的问题,我已经尝试了这些解决方案,但仍然无法正常工作。
我的应用
package es.ea1ddo.antenacubica;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
frecuencia = findViewById(R.id.frecuencia);
cal3el = (Button) findViewById(R.id.calcular3);
现在这是我试图复制以前的应用程序的地方
package es.ea1ddo.calculadoraantenascubicas;
public class TabFragment2 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View v= inflater.inflate(R.layout.tab_fragment_2, container, false);
frecuencia = EditText.findViewById(R.id.frecuencia);
cal3el = (Button) getView().findViewById(R.id.calcular3);
我一直在四处寻找,尝试了很多例子和不同的方法,但我被困住了。
你可以看到我添加了 getView()
。在每个 findViewById
之前,但我仍然遇到同样的错误:
non-static method findViewById(int) cannot be referenced from a static context where T is a type-variable: T extends View declared in method findViewById(int)
有什么建议吗? 谢谢
最佳答案
在您的 fragment 代码中,您有两个问题。
首先,正如其他人所指出的,View.findViewById()
是一个非静态方法,因此您可以像 myView.findViewById()
一样调用它> 相对于 EditText.findViewById()
。
第二个与 Fragment 的 getView()
方法如何工作有关。此方法仅在 onCreateView()
返回后有效,因为 getView()
返回 onCreateView()
返回的内容。这意味着您不能从 onCreateView()
中调用 getView()
;它将始终返回 null
。
放在一起,您的代码应如下所示:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View v= inflater.inflate(R.layout.tab_fragment_2, container, false);
frecuencia = (EditText) v.findViewById(R.id.frecuencia);
cal3el = (Button) v.findViewById(R.id.calcular3);
...
}
关于java - 无法从静态上下文中引用非静态方法 <T>findViewById(int),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53794964/