[Q] Beginner: Issues with canvas bitmaps, buttons, and layouts - Java for Android App Development

[Q] Beginner: Issues with canvas bitmaps, buttons, and layouts
Hi, I'm hoping people might help me with this more open-ended question. I'm fairly new to programming with little scripting experience.
My problem is that I'm cobbling code together from various separate examples, but trying to implement them into my tests, they don't seem to work together.
Let me show you what my goals are for this experiment:
1) Create Button
2) Generate Images with Button click
3) Drag Images around
So far, I've been able to do create images with drawing bitmaps using canvas and create a working button with the easy drag and drop.
My specific problem is that I can't use the Design tool to create buttons if I use the canvas method of drawing bitmaps because setContentView() needs to be on the canvas.
Here's my onCreate():
Code:
GenerateItem ourView;
Button genButton;
LinearLayout myLinearLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ourView = new GenerateItem(this);
setContentView(ourView);
myLinearLayout = (LinearLayout)findViewById(R.id.linearLayout1);
genButton = new Button(this);
genButton.setText("Generate");
myLinearLayout.addView(genButton);
}
And related XML code from my AndroidManifest:
Code:
<LinearLayout xmlns:android="somelink"
android:id="@+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</LinearLayout>
Now I have two questions:
1) Am I going about this problem the correct way using a mix of Design layout tools and code created images (canvas bitmaps)?
2) Can I use canvas bitmaps with an onTouchListener as a button?

Whoaness said:
2) Can I use canvas bitmaps with an onTouchListener as a button?
Click to expand...
Click to collapse
You should use an ImageView instead. Canvas aren't Views, so they aren't managed by the Android System when an event occurs. Canvas are used, for example, to draw anything in a low-level-way (custom views, for example).
I didn't understand the first question..
Sent from my Vodafone 875

Andre1299 said:
You should use an ImageView instead. Canvas aren't Views, so they aren't managed by the Android System when an event occurs. Canvas are used, for example, to draw anything in a low-level-way (custom views, for example).
I didn't understand the first question..
Sent from my Vodafone 875
Click to expand...
Click to collapse
You might have answered my first question. I'm not sure.
I was asking whether I should stick with canvas methods and, from my limited scripting knowledge, draw a hitbox for the onTouch method to detect so I can redraw the object to the fingers position.
I can easily drag imageviews/imagebuttons around. I guess I have to figure out how to create Imageviews, though I think I seen a way to cast bitmaps into an imageview, but it never worked out for me.

Whoaness said:
You might have answered my first question. I'm not sure.
I was asking whether I should stick with canvas methods and, from my limited scripting knowledge, draw a hitbox for the onTouch method to detect so I can redraw the object to the fingers position.
I can easily drag imageviews/imagebuttons around. I guess I have to figure out how to create Imageviews, though I think I seen a way to cast bitmaps into an imageview, but it never worked out for me.
Click to expand...
Click to collapse
Uhm... so, let me know wheter I understood.
In your project you have a button that renders an image (a bitmap) wich is drawn with a canvas. But you want that this image is draggable.
Am I right?

Andre1299 said:
Uhm... so, let me know wheter I understood.
In your project you have a button that renders an image (a bitmap) wich is drawn with a canvas. But you want that this image is draggable.
Am I right?
Click to expand...
Click to collapse
Yes, draggable image button. Although I'm not sure if it needs to be a button, but I thought button properties would be appropriate for touch and dragging.
Sorry for the late reply. I was on a hiatus.

Related

How to change ImageView content in layout?

Hi,
in my simple app i have an activity with some textviews and a single imageview.
I'm trying to understand how to dynamically change the content of the imageview in my linear layout. I have a linearlayout and i only need to change the image in it (based on the logic of the underlying application) and similarly the text of the textviews. The pictures are .png files that i have put in res/drawable.
It seems to me that the only way is to use an adapter (simpleadapter) but i struggle to find an example of source code as all the ones i found so far refer to more complex adapters (e.g. simplecursoradapter). Anyway i'm very new to these concepts (adapters, helpers, etc.).
Do i really need to define and use AdapterView (or a more specific subclass?) or if if i keep the image files in res/drawable there is a more straightforward way to dynamically change the ImageView?
Thanks in advance,
x70
ImageView iv = (ImageView)findViewById(R.id.myimageview);
iv.setImageResource(resId);
where resId = R.drawable.mypng
With the textviews is similar, just call setText.
Thanks a lot janfsd. That was really easy...
I did actually try before in that way but i thought i needed also to explicitly set the view (eg via setContentView) and it didnt work; i didn't realise that there is no need for that.
still its not clear to me when do i need to use setContentView, but i made good progress!
Cheers,
x70
setContentView is normally used to set the layout(View) of the activity. I have only used it once per activity. Unless you want to change all the Layout of the activity then don't use it more than once, only on the onCreate method after the super call.
So you should only need to use setSomething method which each view should have it.

PackageManager.getApplicationIcon(pckName) returning a 9patch?

Hello Everybody,
I am currently developing a program that get all the running apps and the icon. That work pretty weel on more than 2.000 users but recently, a sprint hero user told me about a force close. After investigation, this line in causing problem:
Code:
BitmapDrawable iconDrawableBitmap=(BitmapDrawable) monPackageManager.getApplicationIcon(pckName);
with the processus com.htc.android.htcime and I get this error:
java.lang.RuntimeException: Unable to resume activity {my.package.name}: java.lang.ClassCastException: android.graphics.drawable.NinePatchDrawable
Click to expand...
Click to collapse
So I guess that the htc virtual keyboard on a Sprint Hero has a 9patch icon instead of a static bitmap or png like all the other softwares?
What sould i do to detect a 9patch and transform it into a Bitmap Ressource?
Thank a lot.
Profete162
But why do you want BitmapDrawable, not general Drawable object? You shouldn't do casting here, because this method may return any Drawable, not just BitmapDrawable or NinePatchDrawable. In the future you will have problems, because e.g. in some cases ClipDrawable will be returned.
I think you try to do something, that you shouldn't.
Hello
Thank you for the answer.
The reason why I don't want to use it as a drawable is simple: after in my code, i draw the icons of all the applications in a canvas.
And i draw with canvas.drawBitmap(...) and I cannot use a drawable there, so I need a Bitmap.
So, is there an other method to draw a Drawable in a canvas?
I am not an Android Guru, but I feel like when I have a number coded as a string and I need an integer for mathematical operations, no?
Thank a lot.
profete162 said:
So, is there an other method to draw a Drawable in a canvas?
Click to expand...
Click to collapse
I don't have much experience in developing Android apps, but I found this method:
http://developer.android.com/refere...e/Drawable.html#draw(android.graphics.Canvas)
Brut.all said:
I don't have much experience in developing Android apps, but I found this method:
Click to expand...
Click to collapse
Yes, and....?
This doesn't allow me to use a Drawable.... I need to instanciate it as a Bitmap and then draw into a canvas..
profete162 said:
This doesn't allow me to use a Drawable....
Click to expand...
Click to collapse
Errr... this is method of a Drawable
A part of my own code : I use Bitmap instead of Drawable, and create the Bitmap from the Drawable with my dTob method.
public static Bitmap dTob(Drawable drawable) {
Bitmap bmp = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_4444);
Canvas c = new Canvas(bmp);
drawable.setBounds(new Rect(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight()));
drawable.draw(c);
return bmp;
}
Click to expand...
Click to collapse

[Q] Basic Questions - Refreshing Adapters/Global Variables

Hi,
I have been trying to get to grips with Android.
First off I guess, any good books you can recommend? I have Hello, Android which has some good examples, but some of the things leave me a little cold in that it seems overly simplistic and then seems to fail to pick up on some latter crucial points, not least about creating custom adapters.
Anyhow, back to the questions.
Firstly, various devices, like the Samsung Galaxy S uses a "blue" summary line in its settings menus. Looks good. But if you want to mimic that style outside of a summary menu, is it possible to get details of system colours?
Secondly, in terms of icon design, tab icons in as defined in the Android SDK seem to suggest using a Grey icon for off and a white icon for on. This seems to bit a bit foolish when the tabs are white.... and most of the other programs I've seen that use tabs have Grey icons for on and white icons for off! Thoughts?
Third, back to this book, one of the examples it gives, is a way to load data from a SQL database using Cursors and SimpleAdapters. Im guessing if I want anything more than a relatively simple list and data pulled from the database, that Im going to need to use a CustomAdapter.
In terms of these cursors though, some of the code does this in the onCreate:
Code:
Cursor cursor
CustomDatabaseHelper test = new CustomDatabaseHelper(this);
try {
cursor = getData();
showData(cursor);
} finally {
test.close();
}
I think I found a couple of problems with that... The CustomDatabaseHelper and Cursor are both local to the onClick method and therefore if I need to access these via a Buttons onClick Im stuffed unless I make them private/public to the class. I don't know the best way around this TBH, what would you suggest? I guess I could define another CustomDatabaseHelper in the onClick method, but Im not sure whether it is a good idea to keep opening all these references.
Plus as well in onClick, you can't give a context of "this" because it's it's not a context there its an OnClickListener?
Code:
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
}
}
And there must be a better way of refreshing the data set? I've tried cursor.notify, test.notify and globalising the adapter and doing adapter.notifyDataSetChanged(); things still don't refresh.
Im going to guess this is a pretty basic and common issue for newcomers trying to understand this that super context intent.
I think Im getting there, Im just trying to get a bit of background to a few of the basic issues Im having a bit of trouble with and find out what the best way to handle the issues are.
Oh, the showData function (which I call after any data change at the moment), does this:
Code:
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.test_item, cursor, Columns, TO);
I think that'll do for now, as my next issues are about SQL, Dates and Formatting.
Thanks
Simon
I think my problem stems around this book of mine... I can do a "notifyDataSetChanged()" on the adapter provided I don't do the "test.close" as above.
This suggests to me the DB Helper should be open across the activity lifetime.
Is that right?

[SOLVED][Q] Dynamic items

Hi,
The problem is: I want to add items to listview row, but in this row I dont know how many item it can have, so I can not pin down the items(textViews) in the layout xml, I have to add them programmatically. How can I do that?
Thanks
avlisF said:
Hi,
The problem is: I want to add items to listview row, but in this row I dont know how many item it can have, so I can not pin down the items(textViews) in the layout xml, I have to add them programmatically. How can I do that?
Thanks
Click to expand...
Click to collapse
You will need to write your own Adapter extending BaseAdapter. Override this method:
Code:
public View getView(int position, View convertView, ViewGroup parent)
In most of the tutorials you will find on the internet, they will inflate a xml file there. So read about creating Views in your Java code. You will find many tutorials on that topic. That lets you decide how many Views you add to a row. Just do it in the Java code.
nikwen said:
You will need to write your own Adapter extending BaseAdapter. Override this method:
Code:
public View getView(int position, View convertView, ViewGroup parent)
In most of the tutorials you will find on the internet, they will inflate a xml file there. So read about creating Views in your Java code. You will find many tutorials on that topic. That lets you decide how many Views you add to a row. Just do it in the Java code.
Click to expand...
Click to collapse
Thanks, it solve my problem
avlisF said:
Thanks, it solve my problem
Click to expand...
Click to collapse
Great.

Loading Framgents up at App Start..

Hey Guys -
This is probably answered somewhere, but for some reason search isn't working at the moment.
So, first, keep in mind that I'm NOT an experienced developer - I have ONE app on the Play Store, and I learned both Java and Android through trial and error and more Google/DuckDuckGo searches than *they* are probably even aware of. When I first released my app, v2.3 or some such was the latest out. :laugh:
So now I'm working on bringing it into the new generation, and playing with fragments.
I've seen two main approaches with them - the first seems to be creating the fragments on the fly in code, as needed. The second seems to be adding them to your main layout (which creates them at app startup).
I decided to go with option #2 - for a couple reasons. (First, it was easier for me to get started by putting them in the XML layout, and because I had some problems trying to get the code to work. Second, one of the fragments uses the Google Maps Fragment, which apparently causes some issues adding/removing the fragments programmatically.(which was causing the errors just mentioned. Third, using the Location service, one of my fragments can read the GPS status from the other, without having to start the service up, wait for a location, and then shut it down.)
And so far, loading the fragments this way seems to work well. Only have one 'glitch' I'm wondering if I'm stuck with, or can work around -
When the app loads, I get the main activity layout, and the screen jumbles all around as the three or four fragments are loaded. Is it possible to somehow hide the messy UI display as fragments are loaded? If I create a splash activity, the fragments don't get loaded until the main activity layout is shown anyways, so that doesn't seem to help the problem any.
Any thoughts are welcome!
-Mike.,
coyttl said:
Hey Guys -
This is probably answered somewhere, but for some reason search isn't working at the moment.
So, first, keep in mind that I'm NOT an experienced developer - I have ONE app on the Play Store, and I learned both Java and Android through trial and error and more Google/DuckDuckGo searches than *they* are probably even aware of. When I first released my app, v2.3 or some such was the latest out. :laugh:
So now I'm working on bringing it into the new generation, and playing with fragments.
I've seen two main approaches with them - the first seems to be creating the fragments on the fly in code, as needed. The second seems to be adding them to your main layout (which creates them at app startup).
I decided to go with option #2 - for a couple reasons. (First, it was easier for me to get started by putting them in the XML layout, and because I had some problems trying to get the code to work. Second, one of the fragments uses the Google Maps Fragment, which apparently causes some issues adding/removing the fragments programmatically.(which was causing the errors just mentioned. Third, using the Location service, one of my fragments can read the GPS status from the other, without having to start the service up, wait for a location, and then shut it down.)
And so far, loading the fragments this way seems to work well. Only have one 'glitch' I'm wondering if I'm stuck with, or can work around -
When the app loads, I get the main activity layout, and the screen jumbles all around as the three or four fragments are loaded. Is it possible to somehow hide the messy UI display as fragments are loaded? If I create a splash activity, the fragments don't get loaded until the main activity layout is shown anyways, so that doesn't seem to help the problem any.
Any thoughts are welcome!
-Mike.,
Click to expand...
Click to collapse
what do you mean with "jumbles "? Loadinganimation? If not, use LoaderManager.LoaderCallbacks
Could you please post your layout file? The one you put the <fragment> tags into.
mynote said:
what do you mean with "jumbles "? Loadinganimation? If not, use LoaderManager.LoaderCallbacks
Click to expand...
Click to collapse
More like you can see each of the fragments load, in order, overlaying each other (especially in cases where I don't specifically set the background, leaving it transaprent, I guess..) In code, then as the first 'fragment' is selected, my code hides the unused one, 'cleaning up' the display. I can't grab a screenshot, since it happens in under half a second.
nikwen said:
Could you please post your layout file? The one you put the <fragment> tags into.
Click to expand...
Click to collapse
Oh, sure -
Code:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="MergeRootFrame">
<fragment
android:id="@+id/fragment_map"
android:name="com.tsqmadness.bmmaps.views.MapPageFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="top" >
<!-- Preview: [email protected]/fragment_mapscreen -->
</fragment>
<fragment
android:id="@+id/fragment_stations"
android:name="com.tsqmadness.bmmaps.views.StationsPageFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="top" >
<!-- Preview: [email protected]/fragment_stations -->
</fragment>
<fragment
android:id="@+id/fragment_sheet"
android:name="com.tsqmadness.bmmaps.views.DatasheetPageFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="top" >
<!-- Preview: [email protected]/fragment_mapscreen -->
</fragment>
</FrameLayout>
I could go back to creating them all in code, but.. before I do that was wondering if there was anything I overlooked.
Thanks!
-Mike.
coyttl said:
More like you can see each of the fragments load, in order, overlaying each other (especially in cases where I don't specifically set the background, leaving it transaprent, I guess..) In code, then as the first 'fragment' is selected, my code hides the unused one, 'cleaning up' the display. I can't grab a screenshot, since it happens in under half a second.
Oh, sure -
Code:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="MergeRootFrame">
<fragment
android:id="@+id/fragment_map"
android:name="com.tsqmadness.bmmaps.views.MapPageFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="top" >
<!-- Preview: [email protected]/fragment_mapscreen -->
</fragment>
<fragment
android:id="@+id/fragment_stations"
android:name="com.tsqmadness.bmmaps.views.StationsPageFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="top" >
<!-- Preview: [email protected]/fragment_stations -->
</fragment>
<fragment
android:id="@+id/fragment_sheet"
android:name="com.tsqmadness.bmmaps.views.DatasheetPageFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="top" >
<!-- Preview: [email protected]/fragment_mapscreen -->
</fragment>
</FrameLayout>
I could go back to creating them all in code, but.. before I do that was wondering if there was anything I overlooked.
Thanks!
-Mike.
Click to expand...
Click to collapse
Ah, thanks.
So you want one Fragment being at the front and all others behind it?
Then to hide them all during loading, you could put another View to the top (with android:width and height = "fill_parent"). As soon as all fragments have loaded, you can remove it.
Does that do what you want?
nikwen said:
Ah, thanks.
So you want one Fragment being at the front and all others behind it?
Then to hide them all during loading, you could put another View to the top (with android:width and height = "fill_parent"). As soon as all fragments have loaded, you can remove it.
Does that do what you want?
Click to expand...
Click to collapse
i prefer (this is what i do) replacing it after everything has been loaded. Means, use a framelayout or whatever and just replace it with the fragments, ist not that hard.
i can Show you an example if you want to
nikwen said:
Ah, thanks.
So you want one Fragment being at the front and all others behind it?
Then to hide them all during loading, you could put another View to the top (with android:width and height = "fill_parent"). As soon as all fragments have loaded, you can remove it.
Does that do what you want?
Click to expand...
Click to collapse
I'll give that a try! Essentially, I just want to hide all the apparent 'loading' of widgets until everything IS loaded, to clean up the launch process. (Obviously, this action does NOT happen if the app is in the background and brought forward - only on fresh launches - i.e. After being killed, or phone reboot.)
I hadn't thought of creating a fourth view in front of everything to hide them - I will try that. I don't see why it wouldn't work. I'll let you know tomorrow!
mynote said:
i prefer (this is what i do) replacing it after everything has been loaded. Means, use a framelayout or whatever and just replace it with the fragments, ist not that hard.
i can Show you an example if you want to
Click to expand...
Click to collapse
I wouldn't mind seeing some code, either. (Since I 'taught myself', I really do enjoy seeing other ways - usually better and quicker - at doing things. :laugh
Thanks guys -
Mike.
http://www.vogella.com/articles/AndroidFragments/article.html
scroll down, there is an example how to replace placeholder with fragments. you can receive broadcasts when the Fragment is done and replace it then this way
---------- Post added at 09:44 PM ---------- Previous post was at 09:43 PM ----------
http://www.vogella.com/articles/AndroidFragments/article.html
scroll down, there is an example how to replace placeholder with fragments. you can receive broadcasts when the Fragment is done and replace it then this way
mynote said:
http://www.vogella.com/articles/AndroidFragments/article.html
scroll down, there is an example how to replace placeholder with fragments. you can receive broadcasts when the Fragment is done and replace it then this way
---------- Post added at 09:44 PM ---------- Previous post was at 09:43 PM ----------
http://www.vogella.com/articles/AndroidFragments/article.html
scroll down, there is an example how to replace placeholder with fragments. you can receive broadcasts when the Fragment is done and replace it then this way
Click to expand...
Click to collapse
I just saw these exercises: http://www.vogella.com/articles/AndroidFragments/article.html#tutorial_dyanmicfragments
Did I miss anything?
nikwen said:
I just saw these exercises: http://www.vogella.com/articles/AndroidFragments/article.html#tutorial_dyanmicfragments
Did I miss anything?
Click to expand...
Click to collapse
No. That's true. You just have to use some way to get informed when the cursorloader is finished.
This should be that hard. Use a "Harcoded" Loading layout instead of Fragment and as soon as you get a notify (broadcastreceiver, fragmentmanager, whatever) then you "visible" replace the Fragment
mynote said:
No. That's true. You just have to use some way to get informed when the cursorloader is finished.
This should be that hard. Use a "Harcoded" Loading layout instead of Fragment and as soon as you get a notify (broadcastreceiver, fragmentmanager, whatever) then you "visible" replace the Fragment
Click to expand...
Click to collapse
If I ever need this, I'll be able to do that. Just wondering where the code was. :laugh:
Okay, so you guys lost me going back and forth in the last few messages there. (Not your fault, again, remember, I taught myself and am slow. )
However, an update on some things I tried:
Adding a view to overlay the other fragments does NOT work, unfortunately:
If added in the layout before the fragments, the view is created first, but then is underneath the fragments, defeating the purpose, because of Z-Order.
If the layout view is AFTER the fragments, it's now on top of the other fragments, BUT, because the other fragments are loaded first, you still see the stacked and loading views of the fragments before the final overlay view pops into the window.
My next thought was to mark the containing views IN each fragment's layout set to android:visibility="None". This didn't work either, as I had to set them Visible before using the FragmentManager.beginTransation() to enable/disable the fragments. Setting them all to 'visible' cause the loading animations to not appear, but all three fragments end up visible for a split second before the Transaction hid/showed the right fragments.
I looked at - am still looking at - that link with the code, but I think because one of my fragments HAS a fragment IN it (sub Fragment?) it will cause the same problems I ran into at the start of the project when I tried to create the fragments programatically.
I have one more little trick to try with the visibility of the views in the fragments, before I jump back to getting it all done up in code to avoid the ugliness.
Thanks guys -
Mike
Hi everyone! I'm new in this forum but I have to admit that I have read it a couple of times to see great stuff!
I read this thread because I had the same question. The answers here are the first thing in mind when I had the problem. As I searched the web, I found a library called Progress Fragment by Evgeny Shishkin.
https:/ /github.com/johnkil/Android-ProgressFragment (I'm new so I can't post links for now, so you can copy/paste it )
One of the main features is that is compatible with devices using Android 1.6 and up!
It's really easy to use!
I hope this helps someone.
Guys -
Thanks for your help.
After working around, here's what I ended up with -
I can't create and attach (.replace) the fragments programatically, since one of the fragments has a MapFragment inside of it. (NOT a MapSupportFragment). This causes the .replace to need some overriding to handle a 'sub-fragment'.
Seeing as I found a good way to handle it - I decided not to override the .replace or the fragment manager. Instead, my main activity (posted earlier in the thread), I made all three fragments visibility:gone. This allows the main activity to launch to a blank (or set background) screen briefly before loading up the first fragment and hiding the others.
When I call my fragmentmanager() to show/hide the fragments, I simply set the visibility to 'view' at the same time. Seems kinda clunky, but it works well.
Thanks!
-Mike.

Categories

Resources