【问题标题】:Adding a Custom ImageView to main layout将自定义 ImageView 添加到主布局
【发布时间】:2026-01-15 21:35:01
【问题描述】:

这是交易。

我正在查看有关扩展 ImageView 的代码:

http://marakana.com/forums/android/examples/98.html

我想知道如何将新视图与其他一些视图一起添加到现有的 xml 布局文件中。

我已经在我的主要线性布局中这样做了:

<FrameLayout android:id="@+id/FrameLayout01" android:layout_width="300dp" android:layout_height="300dp">
        <com.marakana.Rose android:layout_height="wrap_content" android:layout_width="wrap_content"/>

但问题是这样不会调用 onDraw 方法。

任何人都可以为此提出解决方案吗?也许是一些将 CustomViews 与 xml 布局结合起来的例子。

tnx.

【问题讨论】:

    标签: android layout custom-view


    【解决方案1】:

    您是否在 res/values/attrs.xml 中添加了定义?

    <declare-styleable name="Rose">
    </declare-styleable>
    

    如果不添加任何 xml 属性,我不确定是否需要它...

    此外,如果您发布了 com.marakana.Rose 代码,将会有所帮助。举个例子,这是我自己的一个组件的类声明:

    public class CalendarCell extends ImageButton implements OnTouchListener
    

    onDraw:

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    

    这是我的 xml 布局的 sn-p:

    <TableRow>
            <com.view.customcomponents.CalendarCell
                style="@style/NumericImageButton"
                android:id="@+id/calendar_row1_col1"
    
                android:background="@drawable/calendar_bg_selector" />
    

    我前段时间按照教程做了这个,但我不记得在哪里。另外,我可能会遗漏一些东西。谷歌一下,你会发现有用的资源。

    编辑:我认为这些是我遵循的教程,尽管我必须投入一些工作才能最终使其发挥作用:

    Official docs

    AndDev.org

    【讨论】:

      【解决方案2】:

      我想我解决了。我在 main.xml 文件中使用了我的代码,它可以工作。我必须做的是重写一个新的类构造函数,它接受 AttributesSet 以及上下文作为参数,然后使用 findViewById(CustomViewName) 在活动中引用它并使用 CustomView 中定义的函数。

      【讨论】:

      • 所以如果你是通过代码动态添加视图并且不能使用 findViewById 那么你该怎么做呢?
      • 您创建一个新视图,例如 CustomView cv = new CustomView(context);然后找到对该视图的根布局的引用,例如要将视图作为子视图放置的 LinearLayout。接下来做linear.addView(cv);
      【解决方案3】:

      要允许 Android 开发者工具与您的视图交互,您至少必须提供一个以 Context 和 AttributeSet 对象作为参数的构造函数。这个构造函数允许layout editor to create and edit an instance of your view.

      class PieChart extends View {
          public PieChart(Context context, AttributeSet attrs) {
              super(context, attrs);
          }
      }
      

      还有详情Answer here

      【讨论】: