Java 使用FrameLayout和TextView创建自定义ImageButton类

Java 使用FrameLayout和TextView创建自定义ImageButton类,java,android,Java,Android,我是一个新手,所以,任何帮助都是感激的。我在StackOverflow上读了很多帖子,也在Google上搜索了我的疑问,但很难找到好的答案 以下是我试图做的: <FrameLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1"> <ImageButton and

我是一个新手,所以,任何帮助都是感激的。我在StackOverflow上读了很多帖子,也在Google上搜索了我的疑问,但很难找到好的答案

以下是我试图做的:

    <FrameLayout 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="1">    
    <ImageButton 
        android:background="@layout/roundcorners" 
        android:id="@+id/hug" 
        android:scaleType="centerInside"
        android:cropToPadding="false"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:paddingBottom="10dip"
        android:layout_height="fill_parent" 
        android:layout_width="fill_parent"
        android:src="@drawable/hug">
    </ImageButton>
    <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_gravity="bottom|center"
        android:textColor="#000000"
        android:textSize="15dip"
        android:textStyle="bold"
        android:paddingBottom="5dip"
        android:clickable="true" 
        android:text="Hug">
    </TextView>
</FrameLayout>
然而,这是行不通的。在错误日志中,我收到以下消息:

“未处理的事件循环异常”

你知道我做错了什么吗


谢谢

如果您只是尝试从xml创建视图并将其添加到布局中。只需使用平放器

在活动内部,使用类似

FrameLayout frame = (FrameLayout)getLayoutInfalter.inflate(
        R.id.YOUR_VIEW_XML,null);
layout.addView(frame);
如果尝试创建类,请扩展框架布局或视图。创建一个构造函数,它接受您的参数并为其指定所需的值

编辑: 访问内部元素 如果已经为这些元素设置了id,则可以通过

TextView text = (TextView)frame.findViewById(R.id.yourtextview);
或者可以使用子索引,如

TextView text = (TextView)frame.getChildAt(0);

听起来您正在寻找一种方法来创建一个视图类,它将是一个ImageButton和一个用FrameLayout包装的TextView

在本例中,您可以考虑创建自己的视图类。可能是一个扩展FrameLayout的视图类。有关如何创建自定义视图的更多信息,请参阅本开发人员文章


特别是“复合控制”部分:

你好,Blessenm,是的,你的建议奏效了,谢谢。但是,如何引用膨胀XML中的每个元素?我的意思是,我需要有一个对ImageButton和TextView的引用,这样我就可以用数据库中的值来设置它们。你有什么建议吗?
TextView text = (TextView)frame.findViewById(R.id.yourtextview);
TextView text = (TextView)frame.getChildAt(0);