findViewById在不同类的静态方法中

时间:2012-10-03 00:59:55

标签: android static-methods findviewbyid

在我的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;   
}
}
对于MiscMethods类型,未定义

getActivity(如果我删除了findViewById)。

现在我有一个类似于上下文的Application类

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()也没有帮助。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

看起来你正在寻找一个快速而肮脏的解决方案,所以这里有两个:

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

    public static boolean landscapeChecker(Activity activity)

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

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

答案 1 :(得分:0)

你只需在oncreate之前在MainActivity静态元素上声明。    在此之后在底部创建一个metod;

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");
 }
相关问题