Android Button Different Events - Java for Android App Development

Hi,
I have a easy question about devoloping android app.
Question is diffrent type of button.
for example, when my finger on the button, music is play but when my finger up to button music is stopped. How can i do this. İt's probably diffrent type of button event's but I don't know.
I google ıt but I find anything.
PS: i can starting, stopping process on normal button. But i can't do like this.

I'm not sure if I understood what you asked, but I think you can use the isPresed() method for this:
Code:
public void onClick(View v) {
if(v.isPressed()){
//do sth.
}
else{
//do sth. else
}
}
}

You could try using MotionEvents?

Working
I tried if else structure but it doesnt work.
------
Jonny i google it now. I dont know motionevents.
Finaly ı found my answer. I ask on stackoverflow and ı wrote my answer
If somebody want learning to answer follok link
http :// stackoverflow. com/questions/28376374/android-button-keydown-keyup-different-button-events?noredirect=1#comment45093077_28376374

Related

A way to browse huge amount of items ( like contacts)

Hi there.
Sorry for my poor english, i a french user, but i really need this forum and your help.
I am developping an app where the user will have to choose an item in a list of huge numbers items ( let's consider that we are talking about all the cities in a little country)
My first try was to create an autocompletetextview. This solution work perfectly, but i think that is not the easiest way for the user...
My second attempt was to create a popup like this:
Code:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Pick a color");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
But that's really not easy to scroll in such a huge list and i didn't find a way to create an fastscroll on this list!
So i am still looking to present my list in a better way with a fastscroll
Do you think there is an easy way to create something like that ( with a scroll by letter ) or i ll have to programm all the stuff by myself?
Thank a lot for all your ideas.

[Q] New developer question

Hey all,
I'm a new Droid developer (but long time Java programmer) and have been playing around with writing some apps. I've managed to get my first app working really well but have hit a snag. The program, which lets me view recent PVP comics, works like this:
1. Download the RSS from PVP
2. Parse the RSS to pull out comic links
3. Show the most recent comic (download it if needed) and allow user to view previous comics
Everything works fine. However, there is one thing that I just can't seem to figure out how to stop. The download of the RSS and image files take place in threads. In order to get the RSS immediately on load I put my method call in the onCreate() method. This works great. However, every time I rotate the phone, it seems like everything resets itself and reloads the RSS again.
I tried using a global boolean variable "first" which gets set to false when I first load the RSS, but when the phone is rotated it goes back to true. I'm obviously missing something in terms of how applications work on the android, but have been unable to find any work-arounds.
Any suggestions for me? I'm at a loss.
Thanks for any help.
Matthew
PS. Here's the basic structure of the code:
Code:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// set up all the appropriate listeners and layout stuff
loadRSS(); // this is the method that I only want to call the first time
}
I tried the following with no luck:
Code:
private boolean first = true;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// set up all the appropriate listeners and layout stuff
if (first)
{
first = false;
loadRSS(); // this is the method that I only want to call the first time
}
}
onCreate() is fired everytime the activity is loaded. If you rotate the phone you are basically reloading the activity. Put a breakpoint on the onCreate() method and you should see it get called when you rotate.
Thanks, I had seen that with a breakpoint. Is there any solution or best practice to get around it? Downloading and parsing the RSS file is a fairly expensive process (a few seconds) and I'd rather not do it except when needed (I can't cache the RSS file like I do the images as it will change over time). However, I don't want to have to click a "get it now" button on starting the app but would rather the program know to do this the first time it loads and then not again. Is there anything that allows you to either store some value in a variable that isn't reset on the "onCreate()" method or some other method that the first call should be put in (e.g. "onStartup()"...completely made that name up).
Thanks,
Matthew
I'm new to this as well, but this seems like something that you should use this Class for:
http://developer.android.com/reference/android/os/AsyncTask.html
I think you are not considering the Activity lifecycle. I don't see a problem to call LoadRSS() each time onCreate is called (probably onResume() is a better place), because LoadRSS() should spawn a thread to retrieve the RSS. If the Activity is destroyed by Android you want to keep the Thread handle to continue running the loading, you can do that saving it with onRetainNonConfigurationInstance() and restore the thread handle calling getLastNonConfigurationInstance() when the Activity is resumed, remember it could be another instance of the activity.
Code:
private Thread _rssThread;
public void OnCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// set up all the appropriate listeners and layout stuff
LoadRSS();
}
private void LoadRSS() {
_rssThread = (Thread)getLastNonConfigurationInstance();
if (_rssThread == null) {
_rssThread = new Thread(... )
}
}
public Object onRetainNonConfigurationInstance() {
return _rssThread ;
}
Probably you want to do something similar with the actual RSS already loaded, and put some logic in the Thread to update the RSS instead to reload all.
I like the suggestion of basically caching the RSS and loading from there. the Activity should basically check if it has already downloaded the RSS and just 'reload' it locally instead of downloading it again.
Failing that, why don't you just force landscape mode only since this is a comic anyway?
Unconn
What you need to do is handle configuration changes within your activity.
First, update your activity tag in the AndroidManifest.xml like so:
Code:
<activity android:name=".MyActivity"
android:configChanges="keyboardHidden|orientation">
...
</activity>
That's all you need to do to prevent your activity from being recreated with each configuration change.
If you need to update something, such as reloading the layout for an orientation change, just override the onConfigurationChanged method like so:
Code:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.myactivity);
...
}
Randroid. said:
What you need to do is handle configuration changes within your activity.
First, update your activity tag in the AndroidManifest.xml like so:
Code:
...
That's all you need to do to prevent your activity from being recreated with each configuration change.
If you need to update something, such as reloading the layout for an orientation change, just override the onConfigurationChanged method like so:
Code:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.myactivity);
...
}
Click to expand...
Click to collapse
this is correct
That worked perfectly! Thanks a lot for the help.

Restart Activity

Hello,
I have some kind of a special question...
I am new in Android programming and I wonder if it's posible to restart an application after the home-button stopped it. Since I know, the application is not destroyed, only stopped.
So, I thought doing something like this:
Code:
protected override void OnStop()
{
base.OnStop();
StartActivity(new Intent(this, typeof(MyActivity)));
}
Obviously that does not work. How can I "refocus" my Activity after the home-button closed it?
Thanks a lot!
Kuehner
Hello,
I have news. Restart works when I do this:
protected override void OnStop()
{
base.OnStop();
if (!guiHandler.TestStopped)
{
Intent intent = new Intent(this, this.Class);
StartActivity(intent);
}
//Finish();
}
My problem now:
I have to finish my old activity to start a new one. But I only want to restart a stopped activity without destroying it. Is this possible?
start the intent and finish the intent at the same time.
How do I do that?
Intent intent = new Intent(first.class, second.class);
startActivity(intent);
finish();
replace first.class and second.class with the classname.
Ok, thanks for your help. Now I understand.
The problem is that I do not want my activity to finish. When the user presses the home-button, the activity runs in background (for a couple of minutes) and there I want my activity to refocus again (without restarting, it's more "refocusing", so that the old state appears again).
I do not want my activity to finish!
i already tried it too.. but found nothing.. i solved my problem so.. :/

[Q] DatePickerDialog cancelclick

Hi there!
I have been trying to catch the Cancel click of a DatePickerDialog, because I want to do some additional stuff, when the user clicks on the Cancel Button.
I tried it like described in the second answer from esilver from this Question:
http://stackoverflow.com/questions/...erner-of-datepicker-dialog?tab=active#tab-top
But I can't get it to work like that. When do I have to call this onClick method?
Would be great if someone could help me with that!
Thanks!
cTrox said:
Hi there!
I have been trying to catch the Cancel click of a DatePickerDialog, because I want to do some additional stuff, when the user clicks on the Cancel Button.
I tried it like described in the second answer from esilver from this Question:
http://stackoverflow.com/questions/...erner-of-datepicker-dialog?tab=active#tab-top
But I can't get it to work like that. When do I have to call this onClick method?
Would be great if someone could help me with that!
Thanks!
Click to expand...
Click to collapse
the "checked" solution in that example seems wrong to me. but the second one people voted up seems correct.
You can also set the onDissmissListener which will catch if the user backs out with the back key ( recommended for user friendliness )
have a look here:
http://developer.android.com/refere...id.content.DialogInterface.OnDismissListener)
Also, since DatePickerDialog is a subclass of AlertDialog, you can set the buttons the same way:
http://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog
That should get you started but feel free to post back if you get stuck again. And post the code you are using.
Also, one other thing, it might be useful to keep a private reference to your dialog in your activity class.
All those examples (in the API docs and tutorials) always show a new dialog created when "onCreateDialog(int ID)" is called by the OS on your activity and they never save any sort of reference to it. They give you just enough code to hang yourself
Anyways, while this is a perfectly normal way to do things, it doesnt give you a chance to follow what is actually happening with the dialog. It also makes it harder to reference your dialog from elsewhere in the activity.
Keeping a reference, and exploring the onPrepareDialog(int ID) method are good for learning what the OS is doing with your dialog. (IMHO)
hth
Thanks a lot for your answers. But I still can't figure out how to do it.
Here's my current Code:
Code:
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker datePicker, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
// do some more stuff...
}
};
Code:
protected Dialog onCreateDialog(int id) {
Calendar cDate = Calendar.getInstance();
int cyear = cDate.get(Calendar.YEAR);
int cmonth = cDate.get(Calendar.MONTH);
int cday = cDate.get(Calendar.DAY_OF_MONTH);
switch(id){
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, cyear, cmonth, cday);
}
return null;
}
With that I can just call showDialog(DATE_DIALOG_ID); and I get the dialog. Now, where do I have to implement this OnDismissListener and how?
Thanks!
there are lots of ways to do this but I broke it out into several parts so hopefully it seems more obvious what is happening.
Code:
//here's our field reference we could use later or reuse or whatever
private DatePickerDialog dateDialog = null;
protected Dialog onCreateDialog(int id)
{
//your calendar code here... just removed to save space
switch(id)
{
case DATE_DIALOG_ID:
dateDialog = new DatePickerDialog(this, mDateSetListener, cyear, cmonth, cday);
dateDialog.setButton ( DialogInterface.BUTTON_NEGATIVE, android.R.string.cancel, cancelBtnListener );
dateDialog.setOnDismissListener ( listener );
break;
}
return dateDialog;
}
//our dismiss listener
protected DialogInterface.OnDismissListener dismissListener = new OnDismissListener( )
{
@Override
public void onDismiss ( DialogInterface dialog )
{
// do your thang here
}
};
//our click listener
protected DialogInterface.OnClickListener cancelBtnListener = new OnClickListener( )
{
@Override
public void onClick ( DialogInterface dialog, int which )
{
dialog.dismiss ( );
// since we dismiss here, the next listener to get called
// is the dismiss listener. now we'll have consistent behavoir
}
};
Ah thank you very much! I was always confused, where to set the Button and the OnDismissListener.
It works perfectly like that!

[Q]how to invoke search dialoge by button help needed

I have created a free dictionary app before one year
there is option menu to invoke the search dialoge
now i want to invoke search dialog by pressing a button
i have created button in main.xml
now i want to code
but i dont know how to do
i m trying from long time a go but unfortunetly i dont knowledge of java so please help me out
i will be thankfull
thanks
here is my old app which i have shared in xda one year before
topic is here
http://forum.xda-developers.com/showthread.php?t=1786568
and its the screen shot
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
help me please
rafeeq02 said:
I have created a free dictionary app before one year
there is option menu to invoke the search dialoge
now i want to invoke search dialog by pressing a button
i have created button in main.xml
now i want to code
but i dont know how to do
i m trying from long time a go but unfortunetly i dont knowledge of java so please help me out
i will be thankfull
thanks
here is my old app which i have shared in xda one year before
topic is here
http://forum.xda-developers.com/showthread.php?t=1786568
and its the screen shot
here is the code
Code:
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
abstract public class SearchInterfaceBase extends ListActivity {
abstract ListAdapter makeMeAnAdapter(Intent intent);
private static final int LOCAL_SEARCH_ID = Menu.FIRST+1;
private static final int GLOBAL_SEARCH_ID = Menu.FIRST+2;
TextView selection;
ArrayList<String> items=new ArrayList<String>();
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
selection=(TextView)findViewById(R.id.selection);
try {
XmlPullParser xpp=getResources().getXml(R.xml.words);
while (xpp.getEventType()!=XmlPullParser.END_DOCUMENT) {
if (xpp.getEventType()==XmlPullParser.START_TAG) {
if (xpp.getName().equals("word")) {
items.add(xpp.getAttributeValue(0));
}
}
xpp.next();
}
}
catch (Throwable t) {
Toast
.makeText(this, "Request failed: "+t.toString(), 40000)
.show();
}
setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
onNewIntent(getIntent());
}
@Override
public void onNewIntent(Intent intent) {
ListAdapter adapter=makeMeAnAdapter(intent);
if (adapter==null) {
finish();
}
else {
setListAdapter(adapter);
}
}
public void onListItemClick(ListView parent, View v, int position,long id) {
selection.setText(parent.getAdapter().getItem(position).toString());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, LOCAL_SEARCH_ID, Menu.NONE, "Search Urdu Dictionary").setIcon(android.R.drawable.ic_search_category_default);
menu.add(0, 0, 0, R.string.about).setIcon(R.drawable.about);
menu.add(0, 1, 1, R.string.str_exit).setIcon(R.drawable.exit);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case LOCAL_SEARCH_ID:
onSearchRequested();
return(true);
case GLOBAL_SEARCH_ID:
startSearch(null, false, null, true);
return(true);
case 0:
openOptionsDialog();
break;
case 1:
exitOptionsDialog();
break;
}
return true;
}
private void exitOptionsDialog() {
// TODO Auto-generated method stub
{
new AlertDialog.Builder(this)
.setTitle(R.string.app_exit)
.setIcon(R.drawable.exit)
.setMessage(R.string.app_exit_message)
.setNegativeButton(R.string.str_no,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialoginterface, int i)
{}
})
.setPositiveButton(R.string.str_ok,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialoginterface, int i)
{
finish();
}
})
.show();
}
}
private boolean openOptionsDialog() {
// TODO Auto-generated method stub
{
new AlertDialog.Builder(this)
.setTitle(R.string.app_about)
.setIcon(R.drawable.about)
.setIcon(R.drawable.rafeeq1)
.setPositiveButton(R.string.str_ok,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialoginterface, int i)
{
}
})
.show();
}
return false;
}
}
i want to invoke the search dialogue by pressing button
lnstead of this
Code:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case LOCAL_SEARCH_ID:
onSearchRequested();
return(true);
help me please
Click to expand...
Click to collapse
You can easily achieve this by adding a androidnClick attribute for the button. Like this -
Code:
android:onClick="xyz"
Here, xyz is the name of a function which will be called when the button is clicked. Define xyz with a View object parameter like this -
Code:
public void xyz(View v)
{
//Call the onSearchRequested function here
}
Good luck
Sent from my LT26i using Tapatalk
abcdjdj said:
You can easily achieve this by adding a androidnClick attribute for the button. Like this -
Code:
android:onClick="xyz"
Here, xyz is the name of a function which will be called when the button is clicked. Define xyz with a View object parameter like this -
Code:
public void xyz(View v)
{
//Call the onSearchRequested function here
}
Good luck
Sent from my LT26i using Tapatalk
Click to expand...
Click to collapse
thanks sir ,, yes i have google for it and got the same answer
but unfortunetly i dont konw how to code for click and onSreachRequested
will u please
code it for me
i have created button and its ID is button
so please if u can i will thank full to u sir
rafeeq02 said:
thanks sir ,, yes i have google for it and got the same answer
but unfortunetly i dont konw how to code for click and onSreachRequested
will u please
code it for me
i have created button and its ID is button
so please if u can i will thank full to u sir
Click to expand...
Click to collapse
You don't need to know the id of the button if you are adding the onClick attribute in the XML file. You'll need the id only if you want to a reference to the Button from your Java code using the findViewById function. And calling the onSearchRequested function from the xyz function (on click function) should work just the same as it used to before from the menu. I'm sorry, I'm on my phone right now so I can't provide you with proper code except snippets.
Sent from my LT26i using Tapatalk
abcdjdj said:
You don't need to know the id of the button if you are adding the onClick attribute in the XML file. You'll need the id only if you want to a reference to the Button from your Java code using the findViewById function. And calling the onSearchRequested function from the xyz function (on click function) should work just the same as it used to before from the menu. I'm sorry, I'm on my phone right now so I can't provide you with proper code except snippets.
Sent from my LT26i using Tapatalk
Click to expand...
Click to collapse
THANKS SIR FOR UR REPLY
I HAVE CREATED THIS
xml
Code:
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:onClick="sInvoke" android:id="@+id/button"></Button>
</LinearLayout>
and code
Code:
public void sInvoke(View v) {
}
now how to invoke search dialog and how to use onSearchRequested()
rafeeq02 said:
THANKS SIR FOR UR REPLY
I HAVE CREATED THIS
xml
Code:
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:onClick="sInvoke" android:id="@+id/button"></Button>
</LinearLayout>
and code
Code:
public void sInvoke(View v) {
}
now how to invoke search dialog and how to use onSearchRequested()
Click to expand...
Click to collapse
i did this ,
Code:
public boolean sInvoke(View v) {
switch (((MenuItem) items).getItemId()) {
case LOCAL_SEARCH_ID:
onSearchRequested();
return(true);
}
return false;
}
but app is unfortunetly forse closed
sir ,how to code this properly ?
rafeeq02 said:
THANKS SIR FOR UR REPLY
I HAVE CREATED THIS
xml
Code:
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:onClick="sInvoke" android:id="@+id/button"></Button>
</LinearLayout>
and code
Code:
public void sInvoke(View v) {
}
now how to invoke search dialog and how to use onSearchRequested()
Click to expand...
Click to collapse
Well I have never tried using search bars but logically speaking, if you do whatever was being done in the switch case and use the same code in the sInvoke, it should work.
Sent from my LT26i using Tapatalk
abcdjdj said:
Well I have never tried using search bars but logically speaking, if you do whatever was being done in the switch case and use the same code in the sInvoke, it should work.
Sent from my LT26i using Tapatalk
Click to expand...
Click to collapse
thanks once again
Code:
public void sInvoke(View v) {
switch (((MenuItem) items).getItemId()) {
case LOCAL_SEARCH_ID:
onSearchRequested();
return;
}
}
now please let me know where is my mistake how solve this
still app is force closed
rafeeq02 said:
thanks once again
Code:
public void sInvoke(View v) {
switch (((MenuItem) items).getItemId()) {
case LOCAL_SEARCH_ID:
onSearchRequested();
return;
}
}
now please let me know where is my mistake how solve this
still app is force closed
Click to expand...
Click to collapse
Um why have you added a switch case here? When the user clicks the button, you only want the search bar to be invoked so all you have to do is call the onSearchRequested() function in sInvoke. Nothing else has to be done. If it is force closing, then please post the logcat too.
Sent from my LT26i using Tapatalk
abcdjdj said:
Um why have you added a switch case here? When the user clicks the button, you only want the search bar to be invoked so all you have to do is call the onSearchRequested() function in sInvoke. Nothing else has to be done. If it is force closing, then please post the logcat too.
Sent from my LT26i using Tapatalk
Click to expand...
Click to collapse
THANKS THANKS HUNDRED TIMES U HELPED ME
IT WORKED ,, IT WORKED
I LOVE YOU ABCDJDJ ,,I LOVE YOU XDA ,,
actualy sir I dont know java but i love do soming for my students so i tries like this things
if u dont mind may ask for this kind of helps?
rafeeq02 said:
THANKS THANKS HUNDRED TIMES U HELPED ME
IT WORKED ,, IT WORKED
I LOVE YOU ABCDJDJ ,,I LOVE YOU XDA ,,
actualy sir I dont know java but i love do soming for my students so i tries like this things
if u dont mind may ask for this kind of helps?
Click to expand...
Click to collapse
You're welcome
I understand that using technology to teach is an effective method of teaching. Nice idea:thumbup:
There is no problem in asking for help as long as you follow the rules of Xda and search before posting.
Also, learning Java will really help you a lot for developing android apps. In case you get some free time and feel like learning some Java, please do read a book called Head First Java. It is absolutely amazing and explains concepts somewhat like a comic book with lots of pictures etc. Oh and kindly do not call me sir. I'm still studying in school
Good luck with your development
Sent from my LT26i using Tapatalk
abcdjdj said:
You're welcome
I understand that using technology to teach is an effective method of teaching. Nice idea:thumbup:
There is no problem in asking for help as long as you follow the rules of Xda and search before posting.
Also, learning Java will really help you a lot for developing android apps. In case you get some free time and feel like learning some Java, please do read a book called Head First Java. It is absolutely amazing and explains concepts somewhat like a comic book with lots of pictures etc. Oh and kindly do not call me sir. I'm still studying in school
Good luck with your development
Sent from my LT26i using Tapatalk
Click to expand...
Click to collapse
U r so kind , u helped me here for development learning so u r my teacher ,
I saw ur contribution ,its quit great,, i m going to download the book , i love to learn c u soon,, one more question whats ur name ? take care
rafeeq02 said:
U r so kind , u helped me here for development learning so u r my teacher ,
I saw ur contribution ,its quit great,, i m going to download the book , i love to learn c u soon,, one more question whats ur name ? take care
Click to expand...
Click to collapse
You're welcome
Well revealing my real name would defeat the purpose of having a username but let me give you a hint - You can check the real names of developers by going on their Github page.
Regards,
abcdjdj
Sent from my LT26i using Tapatalk

Categories

Resources