2010-09-15 89 views
1

这里是交易。添加自定义ImageView到主布局

我一直在寻找在这个代码大约延伸出的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方法不会被调用。

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

tnx。

回答

0

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

+0

所以如果你要添加视图通过动态代码,并不能使用findViewById那么你可以怎么做呢? – ozmank 2011-11-06 21:35:07

+0

你创建一个新的视图,例如CustomView cv = new CustomView(context);然后找到对该视图的根布局的引用,例如您希望将视图作为子视图的LinearLayout。接下来做linear.addView(cv); – DArkO 2011-11-07 07:11:29

2

您是否在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布局的一个片段:

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

      android:background="@drawable/calendar_bg_selector" /> 

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

编辑:我觉得这些都是我跟着教程,但我不得不把一些工作,终于使其工作:

Official docs

AndDev.org

0

要允许Android的开发工具与您的视图交互,至少你必须提供一个构造函数,一个上下文和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

相关问题