2014-10-20 42 views
1

我最近開始編程Android,並且遇到問題。 我試圖讓字寫在一個EditText中,作爲一個字符串。findViewById(int)方法未定義爲R.layout類型

package com.example.generatoredifrasi; 

import android.os.Bundle; 
import android.R.layout; 
import android.os.Bundle; 

public class EditText 
{ 

@Override 
protected void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.my_layout); 
    EditText Text = (EditText) findViewById(R.id.EditText); 
    String string = Text.getText().toString(); // get the value from the EditText 
} 

} 

findViewById給了我這個錯誤:The method findViewById (int) is undefined for the type R.layout

爲什麼呢?我如何解決這個問題?

有一種更簡單的方法可以將EditText中的單詞寫成字符串嗎?

+2

發佈更多代碼。 – Blackbelt 2014-10-20 15:29:19

+1

我們需要查看代碼的上下文。把你在哪裏(片段,活動等),你是誰得到該佈局變種。 – jonyjm 2014-10-20 15:35:37

+2

除了這個問題的主要範圍之外,你不應該在標準的Java主要方法中放置任何代碼。主要方法在Android本身並不存在 - 作爲初學者,您應該在Activity的onCreate方法或Fragment的onCreateView方法中放置這樣的代碼。 – naweinberger 2014-10-20 15:42:18

回答

1

方法名findViewById()建議您提供一個視圖的ID,而不是一個佈局。因此,使用您在版面文件內添加了的編號。

應該是這樣的:findViewById(R.id.my_mega_awesome_view);

更新:

您嘗試獲取輸入的文本是正確的方式。我想你的問題是你需要找到正確的地點和時間來獲取數據。我的意思是用戶必須先輸入一些東西,然後才能得到它。嘗試閱讀關於addTextChangedListener() method

+0

這取決於情況。如果用戶填寫字段並最終按下「提交」按鈕,則不需要監聽每個更改,因此getText()可以正常工作。但是,在某些情況下,TextChangedListener也最適合。 – naweinberger 2014-10-20 15:54:25

+0

@naweinberger我同意。 – WarrenFaith 2014-10-20 15:56:06

+0

然後我需要getText(),但是給了我很多錯誤 – Fedcom99 2014-10-20 16:04:21

0

沒有必要提及layout.findViewById(R.id.EditText);您可以簡單地引用視圖的ID即EditText視圖。

EditText Text = (EditText) findViewById(R.id.EditText); 
String string = Text.getText().toString(); 
+0

完成,但它給了我這個錯誤 該方法findViewById(INT)是未定義的類型Generatore – Fedcom99 2014-10-20 15:41:26

0

如果你在一個片段中工作,你應該調用findViewById作爲一個視圖的函數。

你需要在你的onCreate方法調用

View view = inflater.inflate(R.layout.fragment_layout, container, false); 

第一膨脹的看法。

然後你就可以通過調用

view.findViewById(R.id.my_btn); 

確保return view;末在網頁上找到的看法。

2

的第一個錯誤您遇到「的方法findViewById(INT)是未定義的類型R.layout」是因爲你有你的進口import R;,所以layout實際上是R.layout,不是你的佈局視圖。如果layout是對視圖的引用,則findViewById()將是有效的方法調用。

下一個錯誤「時,方法findViewById(INT)是未定義的類型Generatore」看起來是因爲你的Generatore類不從Activity繼承,因此沒有可用的findViewById()方法。

沒有看到你的整個班級,很難確定你的問題在哪裏。這是爲了讓你的EditText的字符串值所需的最低限度:

public class TestActivity extends Activity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.my_layout); 
     EditText Text = (EditText) findViewById(R.id.EditText); 
     String string = Text.getText().toString(); // get the value from the EditText 
    } 
} 

當然,你可能想獲取用戶輸入文本後,也許點擊一個按鈕或什麼之內,所以你可以移動Text.getText().toString()其他地方,只要它在setContentView()findViewById()之後。

+0

我更新了帖子中的代碼,但總是錯誤 – Fedcom99 2014-10-20 16:13:19

0

刪除導入android.R.layout。 在正常情況下,您不應該導入任何R類。

相關問題