【问题标题】:findViewById in static method in different classfindViewById 在不同类的静态方法中
【发布时间】:2012-10-03 00:59:55
【问题描述】:

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

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

这在片段本身中工作得很好,但我需要在许多片段中进行完全相同的检查,所以我想在我的“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() 也没有帮助。

我该如何解决这个问题?

【问题讨论】:

    标签: android static-methods findviewbyid


    【解决方案1】:

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

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

      public static boolean landscapeChecker(Activity activity).

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

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

    【讨论】:

    • 非常感谢!第一个解决方案效果很好,虽然因为它是片段,我需要 LandscapeChecker(getActivity());非常感谢:)
    【解决方案2】:

    您只需在 oncreate 之前声明 MainActivity 静态元素。 在此之后在底部创建一个方法;

    static TextView textView;
    
    @Override
        protected void onCreate(Bundle savedInstanceState) {
    .....................................................
    
    textView = (TextView) findViewById(R.id.texview);
    }
    
    public static void upTex(String up) {
    
    
            textView.setText(up);
        }
    
    
    }
    
    //other file class
    public class other{
    
       public void method(){
         upText("jaja");
     }
    

    【讨论】:

      猜你喜欢
      • 2013-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多