我有一个目前正在扩展活动的类,并且有诸如FindViewById,ArrayAdapter等的方法。我想将其变成一个独立的类,但是上述所有方法都不确定。问题是什么?导入课程不够吗?例如,我导入android.view.view for findViewByid,但这仍然没有区别。请指教。

有帮助吗?

解决方案

您应该将活动实例传递给构造函数上的第二类:

在你的 Activity 这样实现您的班级:

MyClass instance = new MyClass(this);

在您的第二堂课中, 构造函数 会这样:

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

其他提示

如果要调用任何属于的功能 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();
    }
}

FindViewById 是非静态公共方法的 Activity 上课,所以只能用于 Activity 目的. 。因此,导入 android.view.Viewandroid.app.Activity 不会提供它。为了使其可用,您可以通过 Actvity 对象 - 通常是 this 您的活动的指向。但是,请注意,您应始终在UI线程中更新视图。

请尝试以下操作:

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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top