java– 在CustomView类中获取MainActivity上下文

java– 在CustomView类中获取MainActivity上下文,第1张

概述我知道这是一个简单的问题,但我错过了一些东西.我有2个类:MainActivity和CustomView.我有这个CustomView的XML布局.我想从我的CustomView类访问所有MainActivity变量,并修改它们,我试图获取上下文,但它没有用.MainActivity类:MyCustomViewcustomV;intmyVar;@Overridepr

我知道这是一个简单的问题,但我错过了一些东西.
我有2个类:MainActivity和CustomVIEw.
我有这个CustomVIEw的XML布局.

我想从我的CustomVIEw类访问所有MainActivity变量,并修改它们,
我试图获取上下文,但它没有用.

MainActivity类:

 MyCustomVIEw customV; int myVar;@OverrIDeprotected voID onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentVIEw(R.layout.start_page);    customV = (MyCustomVIEw) findVIEwByID(R.ID.vIEw2);    myVar = 5;    }

MyCustomVIEw类:

public class MyCustomVIEw extends TextVIEw {public MyCustomVIEw(Context context) {    super(context);    init();}public MyCustomVIEw(Context context, AttributeSet attrs) {    super(context, attrs);    init();}public MyCustomVIEw(Context context, AttributeSet attrs, int defStyleAttr) {    super(context, attrs, defStyleAttr);    init();}context.myVar = 7  //this is what I'm trying to do... 

我也试过getContext,但是没用.
你能帮我么?

解决方法:

通过尝试直接在TextVIEw子类中访问Activity中的变量,可以在Actity的子类和自定义TextVIEw之间引入紧密耦合,这实际上阻碍了自定义TextVIEw的可重用性,因为它只能用于那种类型的Activity,在另一个布局中使用它会破坏一切.基本上,我会说这是糟糕的设计,不会推荐这种方法.

您只需向自定义TextVIEw添加一个方法,并在那里使用该变量:

public class MyCustomVIEw extends TextVIEw {    // your code    public voID setvariable(int myInt){        //use the int here, either set a member variable         //or use directly in the method    }}

并在您的活动中

customV = (MyCustomVIEw) findVIEwByID(R.ID.vIEw2);customV.setvariable(5);
总结

以上是内存溢出为你收集整理的java – 在CustomView类中获取MainActivity上下文全部内容,希望文章能够帮你解决java – 在CustomView类中获取MainActivity上下文所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1115069.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-29
下一篇2022-05-29

发表评论

登录后才能评论

评论列表(0条)

    保存