gpt4 book ai didi

android - 不同类中静态方法中的 findViewById

转载 作者:行者123 更新时间:2023-11-29 18:07:22 34 4
gpt4 key购买 nike

在我的 android fragment 中,我进行了以下简单检查,以判断我的应用程序是否在平板电脑上运行(在平板电脑上我打开了 3 个 View ,在手机上看不到 View 2 和 3,只有第一个看到一个)

boolean mDualPane;
View detailsFrame = getActivity().findViewById(R.id.content1);
mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;

这在 fragment 本身中工作正常,但我需要在许多 fragment 中进行完全相同的检查,因此我想将它放在我用于多个类中常用方法的“MiscMethods”类中。现在我类的同一条鳕鱼看起来像这样:

public class MiscMethods{    
public static boolean landscapeChecker(){
boolean mDualPane;
View detailsFrame = getActivity().findViewById(R.id.content1);
mDualPane = detailsFrame != null && detailsFrame.getVisibility() == View.VISIBLE;
return mDualPane;
}
}

getActivity(如果我删除 findViewById)对于 MiscMethods 类型是未定义的。

现在我有一个像这里这样的上下文应用程序类

public static void ErrorToast(int errorCode) {
String errorString = null;
switch (errorCode) {
case 1:
errorString = App.getContext().getString(R.string.error_tooManyFieldsEmpty);
break;
case 2:
errorString = App.getContext().getString(R.string.error_featureComingSoon);
break;
case 3:
errorString = App.getContext().getString(R.string.error_SwitchBreak);
break;
default:
errorString="Wrong Error Code";
break;
}
Toast errormsg = Toast.makeText(App.getContext(), errorString, Toast.LENGTH_SHORT);
errormsg.setGravity(Gravity.CENTER, 0, 0);
errormsg.show();
}

但是这个 App.getContext() 也没有帮助。

我该如何解决这个问题?

最佳答案

看起来您正在寻找一种快速而简单的解决方案,所以这里有两个:

  • 更改方法签名以将 Activity 作为参数:

    public static boolean landscapeChecker( Activity Activity )

    在该方法中,使用传入的activity 代替getActivity()。从您的各种 Activity 中调用它,例如 boolean mDualPane = landscapeChecker(this)

  • 子类 Activity 并将方法放在那里。对于此解决方案,您将创建一个类 MyActivity extends Activity,然后让您的各种 Activity extend MyActivity 而不是 extend Activity。在该方法中,使用 this 代替 getActivity()

关于android - 不同类中静态方法中的 findViewById,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12700588/

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