To give you some background on my issue I have spent a lot of time on this issue but most the questions I have asked relate to various ways I thought would work but I have never actually asked what would be the easiest way to make this happen.
To show how much work I've done, here are a few stack overflow questions I've posted while trying different me开发者_运维知识库thods to accomplish this task.
- How do I set the background to a solid color? When I use setContentView the screen is blank
- Help with Frame Animation Android
Finally here are some of the things I've tried. My initial response was that it would be extremely easy and I could just call setContentView each time I wanted to change but clearly that is not the case. Second I've tried setting different things as bacgkround, editing that object and hoping it would change. Didn't work. Next I looked into things that android provided such as
ViewFlippers: I could change everything but not the background.
State List Drawable: I wasn't very good at implementing them, it was probably my fault?
Frame by Frame animation: Notice I have a stack overflow question regarding it... need more?
Needless to say, I've realized I'm trying too hard to do as task that should only take 3-5 lines of code. So I'm asking for suggestions.
My solution would be to create a custom View object. The key here would be overriding the onDraw function, in that function simply draw to the canvas the colour you want. It should be really easy.
Please try this and let me know if you have any questions... here are some pointers...
In your View Object...
public class MyView extends View {
@Override protected void onDraw(Canvas canvas) {
canvas.drawColor(mColor);
}
private int mColor = 0xff000000; //black
public void SetColor(int aColor) {
mColor = aColor;
invalidate(); //Not sure about this line, can't remember if this is the correct call... there is a call that causes a redraw
}
}
In your Activity Layout XML...
<your.package.name.ClassName
android:id="@+id/ClassName1"
android:layout_height="fill_parent"
android:layout_width="fill_parent"/>
In your Activity code...
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourxmllayoutfile);
MyView aMyView = (MyView) findViewById(R.id.ClassName1);
aMyView.SetColor(0xff00ff00); //Green I think, this line changes the color
}
Good Luck :)
精彩评论