I am trying to make a thermometer. For this I have an image of a thermometer(a png file) which i have inserted into the layout using ImageView. Now I want to draw a line over this image to show the effect of temperature reading.
Here is my code.
main.xml
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
</ImageView>
<com.focusone.Android.DrawExample.CustomDrawableView
android:id="@+id/custom_drawable_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
height='100'
/>
</AbsoluteLayout>
DrawExample.java
package com.focusone.Android.DrawExample;
public class DrawExample extends Activity {
/** Called when the activity is first created. */
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
CustomDrawableView.java
public class CustomDrawableView extends View {
private ShapeDrawable mDrawable;
public CustomDrawableView(Context v,AttributeSet as){
super(v,as);
drawShape(as);
}
public void drawShape(AttributeSet ast) {
int x =45; int y=15 ; int width=5; int height=0 ;
height= Integer.parseInt(ast.getAttributeValue(null, "height"));
mDrawable = new ShapeDrawable(new RectShape());
mDrawable.getPaint().setC开发者_Go百科olor(0xff74AC23);
mDrawable.setBounds(x, y, x + width, y + height);
}
protected void onDraw(Canvas canvas) {
mDrawable.draw(canvas);
}
}
Now I can draw a line on top of the thermometer image using this program.
But how do i change the height of line during runtime. Since height=100 is written in the xml file I don't know how I can change it.
Please somebody help me.
First I think you don't need to pass attributes in drawShape(AttributeSet ast) but just height in your constructor CustomDrawableView(). Then as Chris said you should have another method in the custom view like
public void setTemperature(int tmp){
drawShape(tmp);
invalidate(); //this will call onDraw()
}
In your main activity make a reference to your custom view so you can call its public methods
CustomDrawableView temperatureView =
(CustomDrawableView) findViewById(R.id.custom_drawable_view);
temperatureView.setTemperature(50);
You can:
- Make "height" a member of your
CustomDrawableView
- Then create a method
setHeight(int height)
where you change the value of height. - Then in your activity use
(CustomDrawableView)findViewById(R.id.custom_drawable_view)
to get a reference to your viewObject. - Then change the value as you like with calling
setHeight(x)
hope that helps
精彩评论