[英]Error: Non-static method 'findViewById(int)' cannot be referenced from a static context
[英]non-static method <T>findViewById(int) cannot be referenced from a static context
我的第一個應用程序單獨運行正常,但是現在我試圖在教程之后添加選項卡,但遇到了麻煩。 我一直在搜索,許多用戶遇到了同樣的問題,我嘗試了這些解決方案,但仍然無法正常工作。
我的應用程式
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
之前,但是我仍然遇到相同的錯誤:
無法從T是類型變量的靜態上下文中引用非靜態方法findViewById(int):T擴展了在方法findViewById(int)中聲明的View
請任何建議? 謝謝
更換
frecuencia = EditText.findViewById(R.id.frecuencia);
cal3el = (Button) getView().findViewById(R.id.calcular3);
同
recuencia = (EditText) v.findViewById(R.id.frecuencia);
cal3el = (Button) v.findViewById(R.id.calcular3);
如果不起作用,請在您的問題中添加完整的xml代碼
在您的片段代碼中,您有兩個問題。
正如其他人所指出的,第一個是View.findViewById()
是一個非靜態方法,因此您將像myView.findViewById()
而不是EditText.findViewById()
一樣調用它。
第二個問題涉及Fragment的getView()
方法的工作方式。 此方法僅在 onCreateView()
返回后才起作用,因為getView()
返回返回的所有onCreateView()
。 這意味着您不能從onCreateView()
內部調用getView()
onCreateView()
; 它將始終返回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);
...
}
更換
EditText.findViewById
同
(ExitText) getView().findViewById
但是,這將導致NullPointerException。
您需要將所有使用getView()
代碼移至onViewCreated()
或引用v
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.