0

嗨那裏我設法綁定我的XML文件到ViewPagerIndicator通過擴展它們作爲片段,但我不能使用必要的findViewById代碼引用我的按鈕代碼。這是我的代碼,因爲它是可以有人幫助「findViewById」不工作在ViewPagerIndicator片段

package com.example.sliding; 

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

public class twoey extends Fragment { 

    Button lol; 

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ 
     View v = inflater.inflate(R.layout.two, null); 
     return v; 

     lol = (Button) findViewById (R.id.button1); 

    } 
} 

但是什麼都我嘗試做我不能得到findViewById字的小紅wriggly線可有人幫忙嗎?

回答

3

你的代碼中有2個錯誤:

  1. return v;必須是一個方法的最後一行,在這之後的任何行無法運行! 無法訪問因此出現編譯器錯誤!

  2. lol = (Button) findViewById (R.id.button1);必須行lol = (Button) v.findViewById (R.id.button1);或者你將有一個NullPointerException因爲button1View v一部分,而不是活動。

正確的代碼是:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
    View v = inflater.inflate(R.layout.two, null); 

    lol = (Button) v.findViewById (R.id.button1); 
    return v; 
} 
+0

我都試過,但然後我得到一個大紅色的波浪線的整條線路不解決問題 – Mizzeeboy 2013-04-11 06:55:01

+1

廣場這條線以上的回報 – 2013-04-11 06:55:16

+0

行不正確排序,看我的編輯! – madlymad 2013-04-11 06:58:37

0

Java編譯器根本無法訪問return語句後編寫的代碼。 return意味着你已經完成了這個方法,並且你從中返回了一個值,所以在執行之後沒有任何意義。因此,您只需在return v調用之前簡單地移動lol = (Button) findViewById (R.id.button1)(實際上應該稱爲lol = (Button) v.findViewById (R.id.button1),因爲v是您的根視圖),並且代碼將正確編譯。希望這可以幫助。

0

覆蓋onViewCreated()。就像這樣:

@Override 
public void onViewCreated(View view, Bundle savedInstanceState) { 
super.onViewCreated(view, savedInstanceState); 
    lol = (Button) getView().findViewById (R.id.button1); 

    .... // ANY OTHER CASTS YOU NEED TO USE IN THE FRAGMENT 
}