【问题标题】:Creating android custom view创建android自定义视图
【发布时间】:2012-07-25 21:52:24
【问题描述】:

我正在尝试创建一个如下所示的自定义视图组件: 一个组件将作为一个菜单工作 - 它有 4 个图像视图,其中对 onClick 事件作出反应。 我用它们制作了一个单独的 .xml 并为它创建了一个类。比我从.xml“class='myclass'”设置父节点类。 在我的 .xml 中,imageview 声明了一个 onClick,但是当我尝试使用 myclass 处理它时 - 应用程序崩溃。怎么了?或者我想主要问题是:为自定义视图设置事件处理程序的正确方法是什么?在这个视图类定义中的处理程序。我应该在.xml 中写一个类似的视图吗

补充:那么,我如何才能从这个自定义视图中触发事件,以获取将持有它来处理的活动?

这是我的菜单 .xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
class="com.example.mtgesturestest.MTMenuViewController"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/main_layout" >

<RelativeLayout
    android:id="@+id/relativeLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

        <ImageView
            android:id="@+id/imageChannels"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:src="@drawable/channels"
            android:layout_marginBottom="10dp"           />
        <ImageView
            android:id="@+id/imageMessages"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:src="@drawable/messages"
            android:layout_marginBottom="10dp" />
        <ImageView
            android:id="@+id/imageTimeline"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:src="@drawable/timeline"
            android:onClick="yell"
            android:layout_marginBottom="10dp" />  

</RelativeLayout>
        <ImageView
            android:id="@+id/imageMenu"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:src="@drawable/menu"
            android:layout_alignParentBottom="true"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="-15dp"
            android:onClick="maximizeMenu"/>

</RelativeLayout>

应用程序说它找不到 onClick 处理程序 (maximizeMenu),但它在我添加此视图而不是 com.mtgesturestest.MTMenuViewController 类的活动中搜索它。我希望这个菜单是独立的。它应该处理点击,播放一些动画,然后触发父活动的事件。所以可以说这里的这个onClick是供我的自定义视图内部使用的。

【问题讨论】:

  • 请显示您的 xml 代码
  • 不客气。看原帖

标签: android events custom-component


【解决方案1】:

为什么不尝试从 MTMenuViewController 类中添加 onClick 侦听器,例如

ImageView menu = (ImageView)this.findViewById(R.id.imageMenu);
menu.setOnClickListener(PUT THE LISTENER HERE);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-20
    • 1970-01-01
    • 2011-05-24
    • 2018-10-11
    相关资源
    最近更新 更多