44

我有一个当前正在扩展 Activity 的类,并且我有 findViewById、ArrayAdapter 等方法。我想将它变成一个独立的类,但上述所有方法都未定义。问题是什么?导入类还不够吗?例如,我为 findViewById 导入 android.view.View 但它仍然没有区别。请指教。

4

4 回答 4

84

您应该将 Activity 的实例传递给构造函数上的 Second Class,如下所示:

在你的Activity实例化你的类中是这样的:

MyClass instance = new MyClass(this);

在您的第二个 Class 中,构造函数将是这样的:

public class MyClass {

public Activity activity; 
//.... other attributes 

public MyClass( Activity _activity){

   this.activity = _activity;
//other initializations...

}
}

然后当你想使用该findViewById()方法时,你可以这样做:

EditText txt = (EditText)this.activity.findViewById(R.id.txt);
于 2011-11-30T09:52:38.040 回答
11

如果您想调用属于的任何函数,Activity那么您只需要拥有Activity.

例如。

class A extends Activity {
    Context ctx;

    void onCreate(Bundle b)
        ctx = this;
        B bob = new B(ctx);
    }
}

这里是B类。

class B {

    B (Activity a) {
        a.anyFunctionOfActivity();
    }
}
于 2011-11-30T09:59:49.790 回答
6

findViewById是类的非静态公共方法Activity,所以它只能用于Activity 对象。因此,导入android.view.Viewandroid.app.Activity不会使其可用。为了使它可用,你可以绕过一个Actvity对象——通常是this 你活动中的一个点。但是,请注意您应该始终在 UI 线程中更新您的视图。

于 2011-11-30T09:50:55.430 回答
0

请尝试以下方法:

public static View getLayoutByRes(@LayoutRes int layoutRes,@Nullable ViewGroup viewGroup)
{
    final LayoutInflater factory = getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    return factory.inflate(layoutRes, viewGroup);
}

TextView tv = (TextView) getLayoutByRes(R.layout.xxx ,Null).findViewById(R.id.editd);
于 2017-03-25T15:33:15.533 回答