gpt4 book ai didi

android - 方法 findViewById(int) 未定义

转载 作者:行者123 更新时间:2023-11-29 20:32:35 28 4
gpt4 key购买 nike

我正在尝试创建一个连接到各种社交媒体(facebook、twitter 等)并检索未读通知的应用程序

在我的主要 Activity 中我有

public void retrieveFB(){

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

}

启动一种方法来检查用户是否已登录,如果他们登录,则只会显示一个 facebook Logo 。但如果他们不这样做,它将显示登录按钮 View 供用户单击

我正在尝试使用

将 fbButtonView 链接到 xml 中定义的 login_button
fbButtonView = (LoginButton)findViewById(R.id.login_button);

但是它有一个错误

The method findViewById(int) is undefined for the type FacebookReceiver

我该如何解决这个问题?我在这里找到的大多数答案是在 fragment 中膨胀 View ,但我不确定是否应该使用 fragment 。

这是我的完整代码

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;
}

然后从您的 MainActivity 类将 Activity 引用传递给 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);
}
}

关于android - 方法 findViewById(int) 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31737698/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com