【问题标题】:using findviewbyid in a class that does NOT extend Activity in android在不扩展 Activity 的类中使用 findviewbyid
【发布时间】:2012-01-09 13:27:51
【问题描述】:

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

【问题讨论】:

    标签: android class android-activity findviewbyid


    【解决方案1】:

    你应该像这样在构造函数上将你的 Activity 实例传递给你的 Second Class:

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

    MyClass instance = new MyClass(this);
    

    在你的第二个 Class 中,constructor 将是这样的:

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

    【讨论】:

    • 这不起作用。 findViewById 只能在 Activity 上调用,不能在 Context 上调用。我尝试了你的方法,但它仍然给了我错误。
    • 所以看看我的编辑,只需传递 Activity 的实例而不是 Context :)
    • 好的,我做到了 :) 当我在 Activity 对象上调用 findViewById 时,我试图查找的 Listiew 为 NULL。那是因为我之前没有对包含 ListView 的 XML 文件使用 setContentView 吗?
    • 是的 setContentView 丢失了,这就是问题所在。可以在 Activity 对象上调用 setContentView。
    • 是的,就是这样,当您覆盖 onCreate 方法时,您应该始终在调用 findViewById() 方法之前设置 contentView :)
    【解决方案2】:

    如果您想调用属于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();
        }
    }
    

    【讨论】:

    • @IgorGanapolsky 在这里也一样。应该怎么做才能在 AsyncTask 中进行这项工作?
    【解决方案3】:

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

    【讨论】:

    • 好的,我明白为什么它不可用但 findViewById 不是 View 类的方法?你能解释一下为什么我们应该总是在 UI 线程中更新我们的视图(你指的是主 Activity 吗?)?
    【解决方案4】:

    请尝试以下方法:

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

    【讨论】:

    • getSystemService 来自哪里?
    猜你喜欢
    • 2014-01-09
    • 2014-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多