Adding a Custom ImageView to main layout

非 Y 不嫁゛ 提交于 2019-12-08 07:00:55

问题


here is the deal.

i was looking over this code about extending an ImageView:

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

and i was wondering how can i add the new View to an existing xml layout file, along with some other views.

already i did this inside my main linear layout:

<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"/>

but the problem is that this way the onDraw method doesn't get called.

can anyone suggest a solution for this? maybe some examples where you combine CustomViews with xml layout.

tnx.


回答1:


Did you add the definition at res/values/attrs.xml?

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

I'm not sure if it's needed if you don't add any xml attribute...

Also, it'd help if you posted the com.marakana.Rose code. Just as an example, this is the class declaration of a component of my own:

public class CalendarCell extends ImageButton implements OnTouchListener

the onDraw:

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

and this is a snippet of my xml layout:

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

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

I did this some time ago by following a tutorial, but I don't remember where. Also, I might be missing something. Google a little bit and you'll find useful resources.

edit: I think these are the tutorials I followed, though I had to put in some work to finally make it work:

Official docs

AndDev.org




回答2:


I think I solved it. I used my code in the main.xml file and it works. the thing I had to do was to override a new class constructor accepting AttributesSet alongside with the context as a parameter and then use findViewById(CustomViewName) to reference it in the activity and use the functions defined in the CustomView.




回答3:


To allow the Android Developer Tools to interact with your view, at a minimum you must provide a constructor that takes a Context and an AttributeSet object as parameters. This constructor allows the layout editor to create and edit an instance of your view.

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

And detail Answer here



来源:https://stackoverflow.com/questions/3716157/adding-a-custom-imageview-to-main-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!