在非Activity类中使用findViewbyid

文章的标题是我在stackoverflow搜索的关键字:use findViewById in other class
——————————
打算实现一个功能:按下button,增加一个EditText
所有功能调试完毕后,打算把这个方法封装成一个新的类 就在这时 问题来了。。。
在新生成的类里 使用findViewById 错误百出
不论是前面加View还是其他的 统统不行 编译没问题 一点Button程序就闪退
查了很多很多资料
最后还是感谢stackoverflow
贴一下原帖地址http://stackoverflow.com/questions/14124468/my-app-crash-if-i-use-findviewbyid-in-other-class-than-mainactivity
findviewbyid必须在activity中使用
所以必须要让他知道是哪个activity在用它
只需要加个参数就好了
OK……前后折腾了好久…学到了

public class AssociaCarta {
    public void associaCarta(Activity context, int numeroRandom, ImageView carta) {
        TextView t = (TextView) context.findViewById(R.id.user);
    }
}

猜你喜欢

转载自blog.csdn.net/kennychan291/article/details/56830196