2012-07-30 40 views
0

我有一個片段,它是一個「定時器」,我可以在任何地方添加。在片段中,我以編程方式更改textView,並且它運行得非常漂亮。我的問題是當涉及到從構造函數膨脹的佈局中使用視圖(?不知道這是否是正確的術語)在它下面的另一種方法。在片段後添加方法

public class Timer_fragment extends android.support.v4.app.Fragment { 
    int testpins; 
    String testedpin; 
    TextView text; 
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 
    View v = inflater.inflate(R.layout.timer_frag, container, false); 

    TextView text = (TextView) v.findViewById(R.id.pwd_status); 
    text.setText("Setting text in fragment not main"); 
    /* set the TextView's text, click listeners, etc. */ 
    updateStatus(); 
    return v; 
} 

所有代碼的工作,沒有錯誤,但是當我嘗試添加這個方法:

private void updateStatus() { 
      TextView text = (TextView) findViewById(R.id.pwd_status); 
      testPin(); 

      text.setText(testedpin);       
     } 

我下findViewById說The method findViewById(int) is undefined for the type Timer_fragment得到一條紅線。

我想過在我的所有方法中誇大視圖,而不是返回它們,但肯定會影響性能莫名其妙嗎?

只是在使用視圖之前試圖膨脹佈局,但我得到一個單詞inflatercontainer錯誤,說他們無法解決。

我是否正確地處理這個問題?

回答

4

您的分段範圍內已經有一個名爲text的成員變量。不要在你的方法中重新聲明它,只是分配它。

text = (TextView) v.findViewById(R.id.pwd_status); 

private void upateStatus() { 
     testPin(); 
     text.setText(testedpin);       
    } 
+0

是的,我的問題只是訪問視圖。 – EGHDK 2012-07-30 16:11:55

1

該方法'findViewById'由活動提供。雖然此類擴展了片段,但除非您將活動提供給片段,否則您將無法訪問與活動相關的方法調用。退房:http://developer.android.com/reference/android/app/Activity.html#findViewById(int

基本上,無論是通過在活動的Timer_fragment實例:

private final Activity _activity; 

Timer_fragment(Activity activity) 
{ 
    _activity = activity; 
} 
... 

private void updateStatus() 
{ 
    TextView text = (TextView) _activity.findViewById(R.id.pwd_status); 
    testPin(); 

    text.setText(testedpin);       
} 

或者從設置視圖的文本中取其正在使用的活動,而不是從內定時器類。

+0

由於我將重複使用這個片段,並且它有很多其他方法。你是否建議我只傳入所有其他方法的實例? – EGHDK 2012-07-30 13:38:00

+0

如果您將實例傳遞給構造函數,則Timer_Fragment類將通過成員變量在其所有方法中訪問它(您不必在此之後將其傳遞到任何位置)。然而,它關於你正在嘗試做什麼。你需要多久調用一次updateStatus(),例如:你可以使用@Sparky的答案,並在其他地方完成工作? – Noah 2012-07-30 13:57:29

0

getActivity().findViewById只需更換findViewById

findViewById方法是在Activity類中定義的。碎片不是活動。但片段可以獲得對使用getActivity方法將其添加到屏幕的Activity的引用。

+0

是啊!它非常有幫助的答案 – 2013-10-02 08:59:21