[SOLVED][Q] Dynamic items - Java for Android App Development

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.

Related

event handling in dynamically created control

Hi all,
I am using eVC++ 4.0, and i've dynamically created a CListView like this:
Code:
lv.Create(0,_T(""),WS_CHILD|WS_VISIBLE,r,this,5);
but I dont know how to handle the events of this control... any ideas??
Mohammad
To get events from a listview (win32) I normally subclass it. I use the subclassing routine to post a message back to the parent when the user is doing something like tapping on it, then the windows routine can check whats selected etc and act on it. Is subclassing possible in mfc ?( I don't use it).
Thank u
but can anybody post some code??
thnx
Ok, I am a bit lazy to look up code at the moment, but here's something:
Yes, subclassing is possible in MFC. You just derive your class from the basic class provided like this:
Code:
class MyListView : pubic CListView
Then you add message handlers in the normal matter.
EDIT: The following passage is incorrect:
But I think subclassing may not be necessary in you case. List box controls send WM_COMMAND messages with notifications of major events like selection change to the parent window. All you have to do is to create a WM_COMMAND handler in your parent class.
Sorry I was thinking of ListBox not list view when I wrote it.
To manually add message handlers you need to put macros like ON_MESAGE or ON_COMMAND in the DECLARE_MESSAGE_MAP section of the class cpp file. All the detaisl are available on MSDN.
Are you saying that a listview will send the same WM_COMMAND as a list box in mfc? Dose this also happen in win32 made listviews. I have always thought it was a bit too tedious to find out when the user taps an item in the listview.
After reading your post levenum I had a quick look and it says that a WM_NOTIFY gets sent to the parent with a LVN_ITEMCHANGED for example. I had not used the LVN_**** because when I looked at them there was none that seem to deal with selections. I would guess that LVN_ITEMACTIVATE or LVN_ODSTATECHANGED would be usefull for this but then a second tap would not be picked up still leaving me wanting subclassing in many situations to get the users tap.
Ok, I have read what u wrote guys and my problem is almost solved, I used the OnNotify() method to handle messages sent from child controls like this:
Code:
BOOL CTest2Dlg::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult)
{
// TODO: Add your specialized code here and/or call the base class
if(wParam ==5 ) //5 is control ID
{
NMHDR *ph =(NMHDR*)lParam;
if(ph->code==NM_CLICK)
MessageBox("Click");
else if(ph->code==HDN_ITEMCLICK)
MessageBox("Item Click");
else
{
CString str;
str.Format("%d",ph->code);
MessageBox(str);
}
}
return CDialog::OnNotify(wParam, lParam, pResult);
}
Now there still a very small prolem: what messages should I handle for 'Selected Item Changed' event ?? I know its easy but I couldnt find it
Regards
mohgdeisat: I am sorry, I made a mistake about WM_COMMAND.
OdeeanRDeathshead is right, I was thinking of a list box not list view.
To make up for this, here is some sample code from a win32 dialog app that uses list view control. I hope it will be of some help:
Code:
//this is from the dialog window function:
case WM_NOTIFY: //handle events:
nmhdr = (LPNMHDR)lParam;
switch (nmhdr->idFrom)
{
case IDC_LEDLIST: //list control ID.
return OnLEDListEvent(hwndDlg, (LPNMLISTVIEW)lParam);
break;
}
break;
BOOL OnLEDListEvent(HWND hwndDlg, LPNMLISTVIEW nmlv)
{
/////
// Handles list view control notification messages
switch (nmlv->hdr.code)
{
case LVN_ITEMCHANGED:
return OnLEDListItemChanged(hwndDlg, nmlv);
break;
}
return 0;
}
BOOL OnLEDListItemChanged(HWND hwndDlg, LPNMLISTVIEW nmlv)
{
if (ListView_GetSelectionMark(nmlv->hdr.hwndFrom) != nmlv->iItem) return 0;
/* do what you need here */
return 0;
}
Don't mind the fact that I used 3 different functions. This is part of a bigger program and I am trying to keep things well organized without resorting to classes.
As I understand it, LVN_ITEMCHANGE is received for different reasons so I try to handle only the one coming from selected item. LVN_ITEMACTIVATE is only sent when you double click the item so if you just want to catch selection change you need to use LVN_ITEMCHANGE.
Once again, sorry for confusing you before.
thanx pals, good job!!!
I think my problem is now solved with ur help :wink:
Mohammad
Ok guys, I said that my problem was solved, yet, another problem arises...
When the list view is in the report mode, how can I determine when a header button is clicked, and determine which one was clicked???????
thanx in advance
To identify a header column click, you need to handle the WM_NOTIFY/HDN_ITEMCLICK message. Normally this message will be received by the header's parent control (i.e. the listview) -- some frameworks may redirect the message to the header control itself. I haven't worked with MFC in 10 years so I can't really if it reflects notification messages back to the control.
If you're trying to implement column sort, do yourself a favor and check out the Windows Template Library (WTL) at sourceforge.net. It's a set of C++ template classes that provide a thin yet useful wrapper around the standard Windows UI components. One of the classes is a sortable listview control. I've been using WTL with big Windows for more than 5 years -- you couldn't pay me to go back to MFC.
hi,
I have seen the WTL library and it seems very useful and time-saver, but I have a couple of questions about it:
1. can WTL 8.0 be installed with VC++ 6.0, specifically the appwizard stuff??how?? I see only javascript files of vc7.0 and 7.1 and 8.0!!
2. is there a good documentation about those classes??
Mohammad
I don't know about WTL 8; I'm still using WTL 7.5 with VS .Net 2003 for all my Win32 development. My guess is that it wouldn't work too well, as WTL is based on ATL, which has substantially changed between VC 6 and 7.
Good references for WTL include www.codeproject.com/wtl, and the WTL group over at Yahoo groups (reflected at www.gmane.org).

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

My newbie thread.

Some background: 10 years ago I had classes in basic, pascal, and c++( I missed something simple some where with functions or classes which messed me up in this I believe.)
So far I've watched a tutorial and set up my emulator and eclipse..
http://www.youtube.com/watch?v=z7bvrikkG7c
I then did a tutorial that ran my first program helloworld
http://www.youtube.com/watch?v=2gdhvwYUNJQ
I then did a tutorial and made a simple program that changes between two screens on a button click ( Why it is an hour long is beyond my understanding)
http://www.youtube.com/watch?v=m-C-QPGR2pM
I've proceeded to learning how to create menus and simply retrieved example code from the Google android site
Source: http://developer.android.com/guide/topics/ui/menus.html
Here's an example of this procedure, inside an Activity, wherein we create an Options Menu and handle item selections:
/* Creates the menu items */
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_NEW_GAME, 0, "New Game");
menu.add(0, MENU_QUIT, 0, "Quit");
return true;
}
/* Handles item selections */
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_NEW_GAME:
newGame();
return true;
case MENU_QUIT:
quit();
return true;
}
return false;
}
Click to expand...
Click to collapse
As I copy and pasted it into ecplise within an Activity, I realize there is some assumed information that I am missing when i received a bunch of errors
So.. I found A video tutorial
http://www.youtube.com/watch?v=6UYNnQOxCS8
and it instructs me to make sure I put these two lines of codes in first
Private static final int MENU1 = MENU.FIRST;
private static final int MENU2 = MENU.FIRST + 1;
I under line the menu's because it gives me errors on them as well... there seems to be some assumed knowledge I'm missing as well....
What specific piece of information am I missing to not have known that i would need those two lines as well as what I need to do to know the appropriate fix out of the suggestions they give me...
Are there any online tutorials or videos that'll bring me up to speed specifically with programming android apps... all the stuff I find just keeps leading me down a path to where I realize I've gotten ahead of myself because people are teaching things while assuming certain knowledge is known.
The tutorial I am following and getting errors on is for an 8th grade class of students...
Me: I'm pissed at that java toturial...
http://forum.xda-developers.com/showpost.php?p=6521891&postcount=6
Bastards.
Following the suggestion from this post
http://forum.xda-developers.com/showpost.php?p=6522089&postcount=7
I obtained a copy of Hello android.
Following the example to create a menu I used the code
I place this into my strings.xml
<string name="settings_label">Settings...</string>
name="settings_title">Sudoku settings</string>
<string
<string name="settings_shortcut">s</string>
<string name="music_title">Music</string>
<string name="music_summary">Play background music</string>
<string name="hints_title">Hints</string>
<string name="hints_summary">Show hints during play</string>
Click to expand...
Click to collapse
I place this into my main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/settings"
android:title="@string/settings_label"
android:alphabeticShortcut="@string/settings_shortcut" />
</menu>
Click to expand...
Click to collapse
I import this files into my src app.java
right uner the other imports
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
Click to expand...
Click to collapse
I place this inside my activity ( where I think it would belong since it doesn't say where to put it. ) and ERROR
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
Click to expand...
Click to collapse
Quick fix says that menu needs to be either a field or constast so i give it a go and click field and it modifies a file called R.java.
I go back to app.java and not only is the menu highlighted but now R.menu.menu is entirely highlighted and says cannot be resolved or is not a field..
I try to modify the R.java file to remove what its done...
It won't let me..
Epic fail. on the third tutorial to create a menu.
I guess ill redo everything in a new project and then do the quick fix making menu a constant....
[edit] never mind ill look else where for help
http://www.youtube.com/watch?v=X3QO0ffg2Tc&feature=related
ok the toturial looks like it will work but when he types in this line in his app.java
public boolean onCreateOptionsMenu(Menu menu) {
Click to expand...
Click to collapse
it is under lined with an error on his screen as well as mine and then he says he is importing the missing classes and the error just disappeas with no demonstrations of what missing classing or what key combination he used to import them...
http://www.google.com/#hl=en&q=impo...=f&aqi=&aql=&oq=&gs_rfai=&fp=d059ab474882bfe2
WOO HOO found what he left out...
Compiled and installed...
Boo hoo menu key does nothing!! time to go back through the other menu tutorials and see if i cant get it working now that i know of this hot key..
Went back to this toturial with the elusive import missing classes hotkey..
http://www.youtube.com/watch?v=6UYNnQOxCS8
It worked like a charm
just had to remove
newGame();
and
quit();
and i have buttons that do nothing so far
More missing pieces.
I created a new activity as shown to me in previous tutorials giving it its own seperate XML file in the res/layouts as well as a jave file and I made sure it is calling for the right layout.
I also added the activity in the androidmanifest as shown to me as well..
off this site
http://developer.android.com/guide/topics/ui/menus.html
I've taken the code to create menus.. ( i got it working )
I then followed this and made the changes
Set an intent for a single menu item
If you want to offer a specific menu item that launches a new Activity, then you can specifically define an Intent for the menu item with the setIntent() method.
For example, inside the onCreateOptionsMenu() method, you can define a new menu item with an Intent like this:
MenuItem menuItem = menu.add(0, PHOTO_PICKER_ID, 0, "Select Photo");
menuItem.setIntent(new Intent(this, PhotoPicker.class));
Android will automatically launch the Activity when the item is selected.
Note: This will not return a result to your Activity. If you wish to be returned a result, then do not use setIntent(). Instead, handle the selection as usual in the onOptionsMenuItemSelected() or onContextMenuItemSelected() callback and call startActivityForResult().
Click to expand...
Click to collapse
It doesn't work... I don't understand why the intent would be in the onCreateOptionsMenu... it doesn't seem to work so I tried the alternative and replaced setIntent with with startActivityForResult.. and then I noticed it says "As usual" in the onOptionsMenuItemSelected()... which is where I would think the code would belong in the first place... but when I originally failed and tried to move the code there it errors...
Is ever step of the way really going to be half assed instructions.. i was beginning to think I had the hang of this.
Are the instructions bad or am i missing something???
Guess ill go dig in my hello android book.
EDIT: Wow that helped
startActivity(new Intent(this, register.class));
Click to expand...
Click to collapse
guess that book is worth something after all...
guess im just intending to start an activity with a particular intent and setting an intent alone isn't going to start the activity.... i suppose there must be some purpose behind setting an intent as they had describe on the google page.. just not seeing it yet...
Got to what i wanted tho.

Guys!! Please help me!!

Guys. Help me. I'm learning to ''Respond to the Send Button'' but I don't know what to do. I follow this step but I still can't understand.
http://developer.android.com/training/basics/firstapp/starting-activity.html
If you guys can help me, I'm really grateful.
Merivex95 said:
Guys. Help me. I'm learning to ''Respond to the Send Button'' but I don't know what to do. I follow this step but I still can't understand.
http://developer.android.com/trainin...-activity.html
If you guys can help me, I'm really grateful.
Click to expand...
Click to collapse
That link didn't work, but if you Google 'android java button onclick listener' that will get you started with plenty of helpful links.
When the button is clicked, you then need to check the content of the Edit Text field - Something like this:
Code:
public void onClick(final View v) {
final String commandText = inputText.getText().toString();
if (commandText != null && commandText.length() > 0) {
Where inputText is the Edit Text field you've assigned in your OnCreate method.
Getting started involves a lot of head scratching, but don't give up! There's so much Open Source code out there, that the penny will drop soon.
brandall said:
That link didn't work, but if you Google 'android java button onclick listener' that will get you started with plenty of helpful links.
When the button is clicked, you then need to check the content of the Edit Text field - Something like this:
Code:
public void onClick(final View v) {
final String commandText = inputText.getText().toString();
if (commandText != null && commandText.length() > 0) {
Where inputText is the Edit Text field you've assigned in your OnCreate method.
Getting started involves a lot of head scratching, but don't give up! There's so much Open Source code out there, that the penny will drop soon.
Click to expand...
Click to collapse
OMG !! this is the link : http://developer.android.com/training/basics/firstapp/starting-activity.html
I don't know how to compile the code properly. hummmm ... maybe you can help me by correcting my code ?
Paste code (variables, functions, etc) inside your MainActivity class and don't write 3 dots, it's just a replacement for skipped parts
Mikanoshi said:
Paste code (variables, functions, etc) inside your MainActivity class and don't write 3 dots, it's just a replacement for skipped parts
Click to expand...
Click to collapse
Ohhh yeahhh :cyclops: .. how can I be so stupid
btw ,, where should I put this code ?
code:
Code:
@override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
Code:
Merivex95 said:
btw ,, where should I put this code ?
Click to expand...
Click to collapse
Replace existing onCreate function with it.
Mikanoshi said:
Replace existing onCreate function with it.
Click to expand...
Click to collapse
But I get an error after doing that ..
Merivex95 said:
But I get an error after doing that ..
Click to expand...
Click to collapse
You need to import TextView and Intent first. Just hover over the names and select import from the menu you will see.
Seriously, my advice would be to learn and understand Java first. It doesn't make sense to learn Android if you don't know Java (and it won't work).
nikwen said:
You need to import TextView and Intent first. Just hover over the names and select import from the menu you will see.
Seriously, my advice would be to learn and understand Java first. It doesn't make sense to learn Android if you don't know Java (and it won't work).
Click to expand...
Click to collapse
Thanks for the advice
nikwen said:
It doesn't make sense to learn Android if you don't know Java (and it won't work).
Click to expand...
Click to collapse
Unless you know any other similar languages. Java was the easiest lang to learn for me, after years of writing on Object Pascal/Object C/C++/JavaScript/PHP. The most troublesome part of coding for Android is creating an UI, especially cross-version compatible :laugh:

[Q] Beginner: Issues with canvas bitmaps, buttons, and layouts

[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.

Categories

Resources