Android databinding and animation - java

Can someone point me in the direction of how to trigger an animation when using databinding?
I've got an icon which changes according to data in my viewmodel. How do I animate icon change when the viewmodel changes (that is, when a property changes in the viewmodel)?

One possible solution is to use a binding adapter.
Here's a quick sample to show you the way to go:
First we define a custom binding adapter:
import android.databinding.BindingAdapter;
import android.support.v4.view.animation.FastOutSlowInInterpolator;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Interpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
public class ViewBusyBindings {
private static final Interpolator INTERPOLATOR = new FastOutSlowInInterpolator();
#BindingAdapter("isBusy")
public static void setIsBusy(View view, boolean isBusy) {
Animation animation = view.getAnimation();
if (isBusy && animation == null) {
view.startAnimation(createAnimation());
} else if (animation != null) {
animation.cancel();
view.setAnimation(null);
}
}
private static Animation createAnimation() {
RotateAnimation anim = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
anim.setInterpolator(INTERPOLATOR);
anim.setDuration(1400);
anim.setRepeatCount(TranslateAnimation.INFINITE);
anim.setRepeatMode(TranslateAnimation.RESTART);
return anim;
}
}
The example layout will look like this:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<data>
<variable
name="vm"
type="de.example.exampleviewmodel"/>
</data>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<ImageButton
android:id="#+id/btnPlay"
style="?attr/borderlessButtonStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|bottom"
android:src="#drawable/ic_play_circle_filled_white_36dp"
app:isBusy="#{vm.isBusy}"/>
</FrameLayout>
</layout>
As you can see, the 'isBusy' property of your viemodel is bound to the view (imagebutton).
You can use this adapter at any view not only at a imagebutton.
Of course, the 'isBusy' property must be bindable (e.g. your viewmodel extends BaseObservable or as a minimum it's a ObservableBoolean).
So whenever you change the 'isBusy' property to true it will trigger the animation to start.
Set it to false, it stops.
Hope this helps ?

Related

How do I keep animated components from "bouncing back" to their original positions after animation?

I want to make a CardView placed at the bottom of the window slide down when you switch modes, and slide back up when you go back into normal mode. The problem is that while the animation works fine, the card immediately reappears in the same spot it was in after the animation finishes. How do I get it to stay/freeze until I want to make it come back?
Here's my animation code for hiding the card (in card_hide_ani.xml):
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:shareInterpolator="#android:anim/decelerate_interpolator">
<translate
android:fromYDelta="0%"
android:toYDelta="100%"
android:duration="500" />
</set>
...and the method that hides the card in MainActivity.java (called from button tap)
void HideCard(Context context) {
CardView cardView = findViewById(R.id.cardView);
Animation cardAni = AnimationUtils.loadAnimation(context, R.anim.card_hide_ani);
cardView.startAnimation(cardAni);
}
(I'd also like to animate the card's transparency/alpha, although I'm not entirely sure if that'll work for both the card and it's embedded components. I'll deal with that later, but right now I just want to get this working.)
Like I said, the animation part works fine, but the card "bounces" right back to where it was. I can't find anything that indicates why, and so far it's been frustrating. I'm assuming that I should have done it some other way, but I can't figure out what to do or how to go about doing it. Am I missing something here? Any help would be greatly appreciated. Thanks!
Visual demonstration of problem
If you want to try custom animation ( this will give you more control over animation), you can try this. I have tried both YAxis animation & Alpha animation together. This will give you context on how we can control item.
import android.animation.AnimatorSet
import android.animation.ValueAnimator
import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
class MainActivityF : AppCompatActivity() {
lateinit var downTextView: TextView
lateinit var upTextView: TextView
lateinit var cardview: CardView
private val cardViewOriginalY: Float by lazy { cardview.y }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main_f)
downTextView = findViewById(R.id.down)
upTextView = findViewById(R.id.up)
cardview = findViewById(R.id.cardview)
downTextView.setOnClickListener { animateCardDown() }
upTextView.setOnClickListener { animateCardUp() }
}
private fun animateCardDown() {
val yAxisAnimator: ValueAnimator = ValueAnimator.ofFloat(cardViewOriginalY, cardViewOriginalY + cardview.height)
val alphaAnimator: ValueAnimator = ValueAnimator.ofFloat(1.0f, 0.5f)
with(yAxisAnimator) {
duration = 300L
addUpdateListener {
val currentY = it.animatedValue as Float
cardview.y = currentY
}
}
with(alphaAnimator) {
duration = 300L
addUpdateListener {
val currentAlpha = it.animatedValue as Float
cardview.alpha = currentAlpha
}
}
val animatorSet = AnimatorSet()
with(animatorSet) {
playTogether(yAxisAnimator, alphaAnimator)
start()
}
}
private fun animateCardUp() {
val yAxisAnimator: ValueAnimator = ValueAnimator.ofFloat(cardViewOriginalY + cardview.height, cardViewOriginalY)
val alphaAnimator: ValueAnimator = ValueAnimator.ofFloat(0.5f, 1.0f)
with(yAxisAnimator) {
duration = 300L
addUpdateListener {
val currentY = it.animatedValue as Float
cardview.y = currentY
}
}
with(alphaAnimator) {
duration = 300L
addUpdateListener {
val currentAlpha = it.animatedValue as Float
cardview.alpha = currentAlpha
}
}
val animatorSet = AnimatorSet()
with(animatorSet) {
playTogether(yAxisAnimator, alphaAnimator)
start()
}
}
}
xml file
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/down"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp"
android:text="DOWN ANIMATION"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/up"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginEnd="20dp"
android:text="UP ANIMATION"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.cardview.widget.CardView
android:id="#+id/cardview"
android:layout_width="match_parent"
android:layout_height="100dp"
android:backgroundTint="#color/black"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
It should be enough to add this line
android:fillAfter="true"
to your xml TranslateAnimation code. Since a TranslateAnimation not really animates the view itself, more like a bitmap representing the View on the screen, without that line the animation does not stay at the wanted position.
For general better and more dynamic animations check out ViewPropertyAnimator
This allows you to chain multiple animations together in one line of code, as well as it really animates the View's property itself on the screen, other than the xml TranslateAnimation, which like mentioned above, only moves the pixels on the screen, not the View itself.
This should also get you started with your other (alpha) animation plans.

How can I make Floating Action Button rotate on every click

I want the fab to rotate each time i click on it. But after trying, i achieved the rotation effect. But the problem i'm having is that it only work once. i.e on app startup.
Please help, i'm a beginner in this.
Below is the complete code i used.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
tools:context=".MainActivity">
<com.google.android.material.bottomappbar.BottomAppBar
android:id="#+id/bottom_app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:gravity="bottom"
android:backgroundTint="#color/design_default_color_background"
app:fabCradleMargin="15dp"
app:menu="#menu/app_bar_layout"
app:fabCradleVerticalOffset="20dp"
app:fabCradleRoundedCornerRadius="40dp"/>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab_generate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="#1D6837"
android:src="#drawable/generate"
app:layout_anchor="#id/bottom_app_bar"
android:contentDescription="generate"
android:clickable="true"
app:fabCustomSize="80dp"
app:maxImageSize="45dp"
android:layout_marginBottom="20dp"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.OvershootInterpolator;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import static androidx.core.view.ViewCompat.animate;
public class MainActivity extends AppCompatActivity {
private FloatingActionButton generateFab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
generateFab = findViewById(R.id.fab_generate);
generateFab.setOnClickListener ( new View.OnClickListener() {
#Override
public void onClick(View v) {
final OvershootInterpolator interpolator = new OvershootInterpolator();
animate(generateFab).
setInterpolator(interpolator).
setListener(null).
rotation(360f).
withLayer().
setDuration(300).
withStartAction(null).
start();
}
});
}
}
Basically, I added onClickListener to my floating action button inside the onCreate method
Try this:
animate(generateFab).
setInterpolator(interpolator).
setListener(null).
rotation(generateFab.getRotation() + 360f).
withLayer().
setDuration(300).
withStartAction(null).
start();
Notice the line rotation(generateFab.getRotation() + 360f).
You rotate the view 360 degrees on the first click so this changes the view elements rotation attribute to 360, and because its already 360 (after the first rotation) it wont rotate again. So instead you want to keep adding 360 degrees to the current views rotation and it will work.
Update:
As per comment by #AHoneyBustard you could instead of rotation(...) use:
rotationBy(360f)

Perfectly linear spacing between gridview items

I am using following code to show the GirdView items.
<GridView
android:id="#+id/gridView"
android:gravity="center_horizontal"
android:layout_below="#+id/searchLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:horizontalSpacing="10dp"
android:numColumns="3"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" />
Each GridItem (ImageView) is of size 92dp
What i want is to show only 3 Columns or 3 images each Row and each Top, bottom ,left right all needs to be perfectly aligned and equal.
Below is the result of above code.
It can be seen that spaces on left and right of the grid are very less as compared with the ones in between images and also between rows are very small.
Secondly, I am using 92dp. above is the result of S3, but when i use small screen the 3rd image doesn't get fit like in 320 dp screen.
Shouldn't using "dp" automatically adjust according to screen size?
I think this code will help you
try it :-
GridView
android:id="#+id/grid_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:numColumns="3"
android:gravity="center"
android:stretchMode="columnWidth"
android:background="#000000"/>
In xml of GridView
<GridView
android:id = "#+id/gridViewSms"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
android:numColumns = "3"
android:horizontalSpacing = "10dp"
android:verticalSpacing = "10dp"
android:gravity = "center"
android:stretchMode ="columnWidth">
In ImageAdapter.java
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private int widthOfScrren;
public Integer[] mThumbIds;
// Constructor
public ImageAdapter(Context c,int ScrrenSize,Integer[] mThumbIds){
mContext = c;
widthOfScrren=ScrrenSize;
this.mThumbIds = mThumbIds;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(widthOfScrren / 4,widthOfScrren / 4));
return imageView;
}
}
In Your Activity
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
public class MainActivity extends Activity{
private Integer[] mThumbIds = {
R.drawable.image1 ,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4,
R.drawable.image5,
R.drawable.image6,
R.drawable.image7,
R.drawable.image8,
R.drawable.image9
};
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//found width of Screen for Gridview
WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
Display display = windowManager.getDefaultDisplay();
int densityX = display.getWidth();
GridView grid = (GridView) findViewById(R.id.gridViewSms);
grid.setAdapter(new ImageAdapter(getApplicationContext(), densityX, mThumbIds));
grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position ,
long id) {
}
});
}
}
I tested it. It works.
In the past, I have used a GridLayout instead of GridViewso that I can keep compatibility back to api v8.
for GridLayout, I wrote a nifty little function which is placed in the activity to dynamically stretch/space the items in the grid to fill the view evenly. I wrote about it here:
https://stackoverflow.com/a/15341447/2066079
I've also copied the code below for your convenience:
public void fillview(android.support.v7.widget.GridLayout gl)
{
Button buttontemp;
//Stretch buttons
int idealChildWidth = (int) ((gl.getWidth()-20*gl.getColumnCount())/gl.getColumnCount());
for( int i=0; i< gl.getChildCount();i++)
{
buttontemp = (Button) gl.getChildAt(i);
buttontemp.setWidth(idealChildWidth);
}
}
(The 20 is for the internal and external padding and margins. This could be done more universally, but this is far cleaner)
Then it can be called like this:
android.support.v7.widget.GridLayout gl = (android.support.v7.widget.GridLayout)findViewById(R.id.buttongrid);
ViewTreeObserver vto = gl.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {#Override public void onGlobalLayout()
{
android.support.v7.widget.GridLayout gl = (android.support.v7.widget.GridLayout) findViewById(R.id.buttongrid);
fillview(gl);
ViewTreeObserver obs = gl.getViewTreeObserver();
obs.removeGlobalOnLayoutListener(this);
}});
It must be done with an observer because we need to wait for the view to be drawn before we call the views.
Please try this code :
Grid.xml :
<GridView
android:id="#+id/photo_grid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:numColumns="3" />
Your custom xml file for photo :
<ImageView
android:id="#+id/img_photo"
android:layout_width="#dimen/grid_photo"
android:layout_height="#dimen/grid_photo"
android:scaleType="fitXY"
android:layout_margin="5dp"
android:src="#drawable/ic_launcher" />
NOTE : Here i recommend to use different dimension for image size instead of fixed 92dp. So, by using dimens.xml you can get exact width and height for different resolution also with same space from all side in Gridview.
I have gone through the same problem a long time ago & get solved by
this:
You can do some change attributes as below in
Gridview:
<GridView
android:id="#+id/gridView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_below="#+id/rltop"
android:fadingEdge="none"
android:fitsSystemWindows="true"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="3"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:soundEffectsEnabled="true"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" >
</GridView>
Get your Screen Size & Width by:
Display display= ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
myapp.screen_width = display.getWidth();
myapp.screen_height = display.getHeight();
And The Most Important thing:
In your GridAdapter class -> in getView() method:
call below method to target devices with different resolution:
public void screenResolutions(int screen_width,int screen_height, RelativeLayout relativeLayout)
{
if((myapp.screen_width == 240)&&(myapp.screen_height==320))
{
// relativeLayout.getLayoutParams().height=(myapp.screen_height-(35+General.getStatusBarHeight(cntxt)))/3;
relativeLayout.getLayoutParams().width=(myapp.screen_width)/3;
}
else if((myapp.screen_width== 720)&&(myapp.screen_height==1280))
{
// relativeLayout.getLayoutParams().height=(myapp.screen_height-(107+General.getStatusBarHeight(cntxt)))/3;
relativeLayout.getLayoutParams().width=(myapp.screen_width)/3;
}
else if((myapp.screen_width== 320)&&(myapp.screen_height==480))
{
// relativeLayout.getLayoutParams().height=(myapp.screen_height-(47+General.getStatusBarHeight(cntxt)))/3;
relativeLayout.getLayoutParams().width=(myapp.screen_width)/3;
}
else if((myapp.screen_width == 480)&&(myapp.screen_height==800))
{
// relativeLayout.getLayoutParams().height=(myapp.screen_height-(71+General.getStatusBarHeight(cntxt)))/3;
relativeLayout.getLayoutParams().width=(myapp.screen_width)/3;
}
else if((myapp.screen_width == 768)||(myapp.screen_height==1280))
{
// relativeLayout.getLayoutParams().height=(myapp.screen_height-(114+General.getStatusBarHeight(cntxt)))/3;
relativeLayout.getLayoutParams().width=(myapp.screen_width)/3;
}
else if((myapp.screen_width == 540)&&(myapp.screen_height==960))
{
// relativeLayout.getLayoutParams().height=(myapp.screen_height-(80+General.getStatusBarHeight(cntxt)))/3;
relativeLayout.getLayoutParams().width=(myapp.screen_width)/3;
}
else if((myapp.screen_width == 1080)||(myapp.screen_height==1920))
{
// relativeLayout.getLayoutParams().height=(myapp.screen_height-(160+General.getStatusBarHeight(cntxt)))/3;
relativeLayout.getLayoutParams().width=(myapp.screen_width)/3;
}
}
Where relativelayout = layout which consists ImageView.
You also have to change your height & width of imageview to target
multiple resolutions as below:
put this in your imageview:
android:layout_width="#dimen/image_width"
android:layout_height="#dimen/image_height"
Put this:
In values folder values-hdpi => dimens.xml(480x800)
<dimen name="image_width">92dp</dimen>
<dimen name="image_height">92dp</dimen>
In values folder values-mdpi => dimens.xml(320x480)
<dimen name="image_width">64dp</dimen>
<dimen name="image_height">64dp</dimen>
In values folder values-sw360dp-notlong-hdpi => dimens.xml(540x960)
<dimen name="image_width">114dp</dimen>
<dimen name="image_height">114dp</dimen>
In values folder values-sw360dp-xhdpi => dimens.xml(720x1280)
<dimen name="image_width">138dp</dimen>
<dimen name="image_height">138dp</dimen>
In values folder values-sw360dp-notlong-xhdpi => dimens.xml(768x1280)
<dimen name="image_width">184dp</dimen>
<dimen name="image_height">184dp</dimen>
Have you try default demo given by Developer site?
this demo clear shows all the images with equal height and width and with equal space around it.
Please also check this Example for GridView.
Please let me know if its not helping you.
Enjoy Coding... :)

Making imagebuttons glow on touch in android

I am making a launcher for android, where it is only usable in landscape. Half of the screen is buttons, not apps, but buttons, and half is simply some clocks and stuff. I want my buttons to glow for like for a second or something once i touch them, which is followed by an animation to show a different screen. I only need help with the glow. Please help me and thanks so much!
This is my xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/mainLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/wallpaper" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="match_parent" >
</LinearLayout>
<GridView
android:id="#+id/gridView1"
android:layout_width="284dp"
android:layout_height="wrap_content"
android:numColumns="3" >
</GridView>
I would also like to know how i can add the imagebuttons to my gridview
my java code:
package com.mysoftware.mysoftwareos.launcher;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
public class MainActivity extends Activity implements OnClickListener {
LinearLayout mainLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Import views
mainLayout = (LinearLayout)findViewById(R.id.mainLayout);
//Setup onClickListener for the buttons
}
#Override
public boolean onKeyDown(int KeyCode, KeyEvent event) {
if ((KeyCode == KeyEvent.KEYCODE_BACK)) {
//Do nothing to prevent the back button to kill the launcher
return true;
}
return super.onKeyDown(KeyCode, event);
}
public void onClick(View src) {
switch(src.getId()) {
}
}
}

using Canvas in android

I am trying to use Canvas that has been created in external class.
However, the app does not run. Here is my code for MyImge where activity starts
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
public class MyImage2 extends Activity {
DemoView draw;
private int imageSizeX = 2047;
private int imageSizeY = 2047;
private int current_drawable = R.drawable.image;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("blah", current_drawable);
ImageView img=(ImageView)findViewById(R.id.imageView);
Bitmap bmp=BitmapFactory.decodeResource(getResources() ,current_drawable);
draw = (DemoView)findViewById(R.id.demo);
imageSizeX = bmp.getWidth()/2;
imageSizeY = bmp.getHeight()/2;
Bitmap resizedbitmap=Bitmap.createScaledBitmap(bmp, imageSizeX, imageSizeY, true);
img.setImageBitmap(resizedbitmap);
}
}
and my DemoView as follows
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
public class DemoView extends View{
public DemoView(Context context){
super(context);
}
#Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
// make the entire canvas white
paint.setColor(Color.WHITE);
canvas.drawPaint(paint);
paint.setAntiAlias(false);
paint.setColor(Color.GREEN);
canvas.drawRect(100, 5, 200, 30, paint);
canvas.drawLine(0, 300 , 320, 300, paint);
}
}
the layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:id="#+id/imageView"
android:layout_width="fill_parent"
android:scaleType="matrix"
android:layout_height="525px">
</ImageView>
<view class="com.test.DemoView"
android:id="#+id/demo"
android:layout_width="fill_parent"
android:layout_height="125px"/>
</LinearLayout>
if I remove the tag com.myimage2.DemoView I can see the image, however my goal is to see the image and canvas. Could someone help please.
Error log:
!ENTRY com.android.ide.eclipse.adt 2 0 2011-04-10 02:19:27.204
!MESSAGE AndroidManifest: Ignoring unknown 'com.test.DemoView' XML element
!ENTRY com.android.ide.eclipse.adt 2 0 2011-04-10 02:19:27.891
!MESSAGE AndroidManifest: Ignoring unknown 'view' XML element
Many thanks in advance.
I think you need to provide one of the other constructors (one that can handle AttributeSet) in order for the classs to be instantiated from xml. Try adding DemoView(Context context, AttributeSet attrs).
I don't know what you want to do with your code in your onCreate-method in the class "MyImage2".
You need just 2 lines to set a canvas view:
draw=new DemoView(this);
setContentView(draw);
By setting your content view to the main layout, the canvas will never be seen. So don't use your main layout, just print everything in the canvas.
Hope this will help you.

Categories

Resources