簡體   English   中英

方法findViewById(int)未定義

[英]The method findViewById(int) is undefined

我正在嘗試創建一個連接到各種社交媒體(facebook,twitter等)的應用程序,並檢索未讀的通知

我的主要活動是

public void retrieveFB(){

    FacebookReceiver fb = new FacebookReceiver();
    fb.loggedInCheck();

}

啟動一種方法來檢查用戶是否已登錄,如果這樣做,它將僅顯示一個Facebook徽標。 但是如果不這樣做,它將顯示登錄按鈕視圖,以供用戶單擊

我正在嘗試使用以下方法將fbButtonView鏈接到xml中定義的login_button:

fbButtonView = (LoginButton)findViewById(R.id.login_button);

但是有一個錯誤

對於類型FacebookReceiver,未定義方法findViewById(int)

我該如何解決? 我在這里找到的大多數答案是在片段中增加視圖,但是我不確定是否應該使用片段。

這是我的完整代碼

public class FacebookReceiver{

TextView fbCount;
LoginButton fbButtonView; //button

public FacebookReceiver()
{
    //constructor
}

public void loggedInCheck(){
    if(isLoggedIn() == null)
    {
        fbButtonView = (LoginButton)findViewById(R.id.login_button);//problem here 
        fbButtonView.setVisibility(View.VISIBLE);   
    }
    else
    {
        String FBCount = null;
        fbCount = (TextView).findViewById(R.id.facebookCount);//here too 

        FBCount = this.getFacebook();
        fbCount.setText(FBCount);
    }
}

private String getFacebook(){
    String FBCount = null;
     try
     {
        FBCount= new GraphRequest(AccessToken.getCurrentAccessToken(),
                            "/me/notifications",
                            null,
                            HttpMethod.GET,
                            new GraphRequest.Callback() {
                            public void onCompleted(GraphResponse response) {
                                /* handle the result */
                            }
                        }
                    ).executeAsync().toString();    

     }
     catch (Exception e)
     {
         e.printStackTrace();
     }
     return FBCount;
}

private AccessToken isLoggedIn(){
    AccessToken accessToken = AccessToken.getCurrentAccessToken();
    return accessToken ;
}

}

首先,在FacebookReceiver類中創建一個constructor如下所示:

private Activity activity;

public FacebookReceiver(Activity activity) 
{ 
    this.activity = activity;
}

然后從您的MainActivityMainActivity活動引用傳遞給FacebookReceiver類,如下所示:

FacebookReceiver fb = new FacebookReceiver(MainActivity.this);
    fb.loggedInCheck();

現在像這樣更新您的loggedInCheck()方法:

public void loggedInCheck(){ 
    if(isLoggedIn() == null) 
    { 
        fbButtonView = (LoginButton) activity.findViewById(R.id.login_button); 
        fbButtonView.setVisibility(View.VISIBLE);   
    } 
    else 
    { 
        String FBCount = null;
        fbCount = (TextView) activity.findViewById(R.id.facebookCount); 

        FBCount = this.getFacebook();
        fbCount.setText(FBCount);
    } 
}

因為FacebookReceiver類沒有擴展Activity類,所以findViewById方法不適用於該類。 如果您的類設計為具有用戶界面以便用戶可以與之交互,則它必須是活動或片段。 或者,如果僅將它用作后台服務來檢查用戶是否已登錄,則不必擴展活動或片段類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM