【问题标题】:Calling activity method from extended view class in Android从Android中的扩展视图类调用活动方法
【发布时间】:2012-03-27 12:35:15
【问题描述】:

这是我在设计应用程序结构时没有预见到的问题。

基本上我有 3 个班级。

ProfileActivity //The main activity for the application.
ProfileView     //Which extends Linear Layout so that I can tinker with my own view. Note that this is just part of the whole activity and not the main layout
ProfileData     //This is just a class for storing data.

活动包含多个 ProfileView,每个 ProfileView 包含一个 profileData。

这是我卡住的地方。我的个人资料视图分配了一个单击方法,该方法需要在活动中调用填充方法。不幸的是````

//I'm inside the activity
public void populateProfileDataForm(ProfileData pd)
            {
                //edit some text fields and other widgets from here
            }

有没有办法从 profileView 类中调用活动方法?

如果不是,那么错误出在我的设计中,任何人都可以为我指出一个更好的绑定数据、视图和活动的解决方案吗?

【问题讨论】:

    标签: android view android-activity hierarchy


    【解决方案1】:

    当你创建一个视图时,你总是需要一个上下文,并且总是传递一个活动给它。 所以尝试使用下面的代码:

    If(m_context instanceof ProfileActivity)
    {
        ProfileActivity activity = (ProfileActivity)m_context;
        // Then call the method in the activity.
    }
    

    或者写一个接口onProfileViewClickListener比如view.onclickListener。然后 ProfileActivity 实现它并将其设置为 ProfileView。

    【讨论】:

    • 我认为我理解上下文的程度不如我想的那样。只是一个简短的问题。 Profileview 扩展了线性布局。所以 context 作为 super(context, attrs);因此,当我创建 profileView(在代码中,而不是 xml)时,我如何将正确的上下文传递给它。 IE getBaseContext(), getApplicationContext(), this.something()?
    • @OVERTONE 抱歉,我刚离开了一会儿。通过活动实例很好。您在 profileActivity 中创建 profileView,因此只需传递 thisProfileActivity.this
    • 我传递上下文的方式是错误的......你的救星梦想故事。我已经坚持了一段时间了。谢谢
    【解决方案2】:

    如果您在 ProfileActivity 类中分配 OnClickListener 或 OnTouchListener 并且在此 Listener 中您不能调用 populate 方法会怎样。在 OnTouchListener 中,您可以获取 TouchEvent 的位置,以便将其分配给特定的配置文件。

    【讨论】:

    • 因此将 onclick 方法分配给主活动而不是 ProfileView 类。这会很困难,因为 ProfileView 有多个实例,而且它们也包含在滚动视图中,因此手动定位侦听器充其量是错误的
    猜你喜欢
    • 2012-10-26
    • 2013-09-30
    • 1970-01-01
    • 1970-01-01
    • 2015-03-23
    • 1970-01-01
    • 2013-04-15
    • 2015-07-04
    • 1970-01-01
    相关资源
    最近更新 更多