(FIXED)Dismiss RecentsDialog/Add Back button function in OnClick method. - Java for Android App Development

Hello guys/girls.
i have been trying for a couple days to do something
{
"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"
}
as u can see i have three buttons in th bottom.
when i press on them it opens an application but behind the recents menu.
i would like to close the recents menu However i have tried to figure it out bit till now no solution found :/
I thought of either call/launch the close-system_dialog intent/broadcast i found in androids recentsapplicationdialog source but i couldnt find proper way or method to add.
then i wanted to try and add a Back button keycode/event but didnt really knew how to implement it.
Here is my code :
Code:
package com.example.recentsmenu;
import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class SearchButton extends Button{
public SearchButton(final Context context, AttributeSet attrs) {
super(context, attrs);
this.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v)
{
try{
v.getContext().startActivity((new Intent("android.search.action.GLOBAL_SEARCH")).setFlags(0x10000000 | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP));
}
catch(Exception ex){
Toast.makeText(context, "Not Installed/Working.",
Toast.LENGTH_LONG).show();
}
}
});
}
}
if someone could help please do
thank you
greetings spacecaker.

It is working sir ? But the only problem you are encountering sir is the it is at the back. As I can see, you need to make a new method pertaining that it will trigger to close the layout of recent dialog.
make a method that will close the layout, dont know how exactly
Code:
public class SearchButton extends Button{
public SearchButton(final Context context, AttributeSet attrs) {
super(context, attrs);
this.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v)
{
try{
v.getContext().startActivity((new Intent("android.search.action.GLOBAL_SEARCH")).setFlags(0x10000000 | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP));
}
catch(Exception ex){
Toast.makeText(context, "Not Installed/Working.",
Toast.LENGTH_LONG).show();
}
}
});
}
collapselayout(); //i think this is
}

At the end of your onClick method in Java add
Code:
finish();
This is what I did in the redundant activity that opened in the Jelly Bean Easter Egg I ported
But it should be an activity where your method is, if its a Service, you must use
Code:
Activity act = new Activity();
act.finish();
Where, Activity is the Activity name (Activity.class)
If it's a Fragment (Though I know it isn't)
Code:
getActivity().finish();

PineappleOwl said:
It is working sir ? But the only problem you are encountering sir is the it is at the back. As I can see, you need to make a new method pertaining that it will trigger to close the layout of recent dialog.
make a method that will close the layout, dont know how exactly
Code:
public class SearchButton extends Button{
public SearchButton(final Context context, AttributeSet attrs) {
super(context, attrs);
this.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v)
{
try{
v.getContext().startActivity((new Intent("android.search.action.GLOBAL_SEARCH")).setFlags(0x10000000 | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP));
}
catch(Exception ex){
Toast.makeText(context, "Not Installed/Working.",
Toast.LENGTH_LONG).show();
}
}
});
}
collapselayout(); //i think this is
}
Click to expand...
Click to collapse
Nope also isnt :/
it says this
The button works it opens the apps and such
but it wont close the recents dialog.

iamareebjamal said:
At the end of your onClick method in Java add
Code:
finish();
This is what I did in the redundant activity that opened in the Jelly Bean Easter Egg I ported
But it should be an activity where your method is, if its a Service, you must use
Code:
Activity act = new Activity();
act.finish();
Where, Activity is the Activity name (Activity.class)
If it's a Fragment (Though I know it isn't)
Code:
getActivity().finish();
Click to expand...
Click to collapse
But its neither a Activity or A Service.
its a Button
extends Button

SpaceCaker said:
Nope also isnt :/
it says this View attachment 2542371
The button works it opens the apps and such
but it wont close the recents dialog.
Click to expand...
Click to collapse
So uyou use custom button sir, hihi I check the android source linked at the 1st post and I saw this
Code:
public void onClick(View v) {
for (TextView b: mIcons) {
if (b == v) {
// prepare a launch intent and send it
Intent intent = (Intent)b.getTag();
if (intent != null) {
intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY);
try {
getContext().startActivity(intent);
} catch (ActivityNotFoundException e) {
Log.w("Recent", "Unable to launch recent task", e);
}
}
break;
}
}
dismiss();
}
So adding
RecentApplicationDialog spacecakerisawesome = new RecentApplicationDialog;
Then
In your custom button
Add these
spacecakerisawesome.onClick(); or any other method name
So we can set it as
Code:
public void onClickSearch(View v) {
// intent thingy sir here
dismiss();
}
And you can use the method in your custom view sir
Hope it helps. Hehe
Sent from my Nexus 7 using Tapatalk

Why are you even extending a button? I don't see the any reason behind it.

Import recentdialog;
public class SearchButton extends Button{
Recentdialog x = new Recentdialog;
public SearchButton(final Context context, AttributeSet attrs) {
super(context, attrs);
this.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v)
{
x.onClickSearch();
}
});
}
}
Try is. Hihii
Sent from my Nexus 7 using Tapatalk
---------- Post added at 11:55 PM ---------- Previous post was at 11:54 PM ----------
EatHeat said:
Why are you even extending a button? I don't see the any reason behind it.
Click to expand...
Click to collapse
I think he need it sir for a new button. XD
Sent from my Nexus 7 using Tapatalk

EatHeat said:
Why are you even extending a button? I don't see the any reason behind it.
Click to expand...
Click to collapse
i need a Button
otherwise i would use ImageView.
for the recentsdialog. to add the 3 quickbuttons at bottom to launch apps or such
it works but it doesnt hide recentsdialog.
Sent from my S500 using xda app-developers app

SpaceCaker said:
i need a Button
otherwise i would use ImageView.
for the recentsdialog. to add the 3 quickbuttons at bottom to launch apps or such
it works but it doesnt hide recentsdialog.
Sent from my S500 using xda app-developers app
Click to expand...
Click to collapse
Something wrong with ImageButton? :silly:

EatHeat said:
Something wrong with ImageButton? :silly:
Click to expand...
Click to collapse
Never used ImageButton xD
i think its same as Button or ImageView
Sent from my S500 using xda app-developers app

SpaceCaker said:
Never used ImageButton xD
i think its same as Button or ImageView
Sent from my S500 using xda app-developers app
Click to expand...
Click to collapse
1. What you are trying to do can be done by using an ImageView/ImageButton. You don't need to extend extra classes.
2. That's an activity. Just call finish() before passing your search intent.
3. Profit.

EatHeat said:
1. What you are trying to do can be done by using an ImageView/ImageButton. You don't need to extend extra classes.
2. That's an activity. Just call finish() before passing your search intent.
3. Profit.
Click to expand...
Click to collapse
Tried the ImageView / ImageButton but same error on the finish(); tag
also i am working on GB 2.3.6 and not ICS or Jb :/
gonna try to implement this .
try{
Object service = context.getSystemService("ACTIVITY_SERVICE");
Class<?> ActivityManager = Class.forName("android.app.Dialog");
Method collapse = ActivityManager.getMethod("collapse");
collapse.invoke(service);
}
catch(Exception ex){
Toast.makeText(context, "Dialog not closed.",
Toast.LENGTH_LONG).show();
}
Click to expand...
Click to collapse

nope didnt worked damn :/
Sent from my S500 using xda app-developers app

For GB, the recents is a dialog. Close the dialog using the following intent. This should work if its a dialog.
Code:
Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);

Will try that
Sent from my S500 using xda app-developers app

also didnt worked :/ damn
Sent from my S500 using xda app-developers app

SpaceCaker said:
also didnt worked :/ damn
Sent from my S500 using xda app-developers app
Click to expand...
Click to collapse
Did you send a broadcast with that intent? Send a broadcast and then try it.

could yo give me a sample of how / whwre i should put the broadcast?
wheni added code it displayed yello line under closedialog
Sent from my S500 using xda app-developers app

SpaceCaker said:
could yo give me a sample of how / whwre i should put the broadcast?
wheni added code it displayed yello line under closedialog
Sent from my S500 using xda app-developers app
Click to expand...
Click to collapse
I implemented these 3 on ics
They worked by using dismiss(); though i dont know how to do it on gb.
Though i have not seen the gb recentspanel view.
There is a suggestion
Search if there is a variable
Like dialog x or alertdialog xy etc.
If it is present.try to Dismiss it by 1of them
xy.dismiss();
Xy.close();
Xy.hide();
Xy.hide(true);
But if there isnt then i do not know anything about it
Edit-are u using eclipse.if yes plz tell me how u compile system apps on it
Sent from my GT-S5570 using XDA Premium 4 mobile app

Related

onCreateView() isn't executed but the fragment is on the screen

The titles explains all of the problem, I'll provide extra info here.
I have a code in my MainActivity that calls a
Code:
mContactListFragment.notifyInvalidated();
method.
This is the method
Code:
public void notifyInvalidated() {
Log.w(MainActivity.TAG, "" + _viewExists);
Log.w(MainActivity.TAG, "The not still casted object is " + getListAdapter());
Log.w(MainActivity.TAG, "The casted object is " + (BaseAdapter)getListAdapter());
((BaseAdapter) getListAdapter()).notifyDataSetInvalidated();
}
All of the above prints false, null, null, and then the program crashes at the 4th instruction.
_viewExists is a variable that's initialized to false as soon as it's created and it's touched in no other part but in the onCreateView() method that sets it to true.
So while debugging, I arrived to the conclusion that nothing works because onCreateView() is not actually called, even though my Fragment is on the screen.
This happens after I rotated the device and I'm in landscape mode.
If I report the device in portrait mode (from landscape to portrait again) and try to call that method, all is good.
I am not sure what other code you would want to see, just ask.
I have to admin I am tired of problems involving fragments and rotations (configuration changes), what would you suggest me to read?
domenicop said:
The titles explains all of the problem, I'll provide extra info here.
I have a code in my MainActivity that calls a
Code:
mContactListFragment.notifyInvalidated();
method.
This is the method
Code:
public void notifyInvalidated() {
Log.w(MainActivity.TAG, "" + _viewExists);
Log.w(MainActivity.TAG, "The not still casted object is " + getListAdapter());
Log.w(MainActivity.TAG, "The casted object is " + (BaseAdapter)getListAdapter());
((BaseAdapter) getListAdapter()).notifyDataSetInvalidated();
}
All of the above prints false, null, null, and then the program crashes at the 4th instruction.
_viewExists is a variable that's initialized to false as soon as it's created and it's touched in no other part but in the onCreateView() method that sets it to true.
So while debugging, I arrived to the conclusion that nothing works because onCreateView() is not actually called, even though my Fragment is on the screen.
This happens after I rotated the device and I'm in landscape mode.
If I report the device in portrait mode (from landscape to portrait again) and try to call that method, all is good.
I am not sure what other code you would want to see, just ask.
I have to admin I am tired of problems involving fragments and rotations (configuration changes), what would you suggest me to read?
Click to expand...
Click to collapse
I've had these problems, too. They're really annoying.
Could you please post your code where the Fragment is created, the onCreate method of the Fragment and the onCreate method of the Activity?
You have to use (override) onActivityCreated for that.
Taptalked u see .. əəs n pəʞlɐʇdɐʇ
nikwen said:
I've had these problems, too. They're really annoying.
Could you please post your code where the Fragment is created, the onCreate method of the Fragment and the onCreate method of the Activity?
Click to expand...
Click to collapse
Sure, here they are.
Fragment
Code:
public static ContactListFragment newInstance(ContactsDatabase database) {
ContactListFragment f = new ContactListFragment();
Bundle args = new Bundle();
args.putSerializable(DATABASE, database);
f.setArguments(args);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
mDatabase = (ContactsDatabase) args.getSerializable(DATABASE);
}
Activity
Code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Initialize the mDatabase
mContactsDatabase = ContactsDatabase.getInstance(getApplicationContext());
// Determine device orientation
mDualPane = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
// Set the fragment that will be changed
mFragmentToReplace = mDualPane ? R.id.contactsPagerFragmentContainer : R.id.portraitFragmentContainer;
// Set up the GUI
FragmentManager fm = getSupportFragmentManager();
if (!mDualPane) {
Log.d(TAG, "Orientation Portrait detected.");
// First, look for previously saved fragments
// findByFragmentId(int id) look for the fragment that was previously associated
// to the resource that has for id the argument passed in. Then, we try to cast it
// to the type of fragment we want, and if that's correct, we have our fragment
mContactListFragment = (ContactListFragment) fm.findFragmentByTag(CONTACT_LIST_FRAGMENT);
if (mContactListFragment == null) {
mContactListFragment = ContactListFragment.newInstance(mContactsDatabase);
fm.beginTransaction()
.add(R.id.portraitFragmentContainer, mContactListFragment, CONTACT_LIST_FRAGMENT)
.commit();
}
}
else {
Log.d(TAG, "Orientation Landscape detected.");
// First, look for previously saved fragments
mContactListFragment = (ContactListFragment) fm.findFragmentByTag(CONTACT_LIST_FRAGMENT);
mContactsPagerFragment = (ContactsPagerFragment) fm.findFragmentByTag(CONTACTS_PAGER_FRAGMENT);
if (mContactListFragment == null) {
mContactListFragment = ContactListFragment.newInstance(mContactsDatabase);
fm.beginTransaction()
.add(R.id.contactListFragmentContainer, mContactListFragment, CONTACT_LIST_FRAGMENT)
.commit();
}
if (mContactsPagerFragment == null) {
final int FIRST_CONTACT_POSITION = 0;
mContactListFragment = ContactListFragment.newInstance(mContactsDatabase);
mContactsPagerFragment =
ContactsPagerFragment.newInstance(FIRST_CONTACT_POSITION, mContactsDatabase);
fm.beginTransaction()
.add(R.id.contactsPagerFragmentContainer, mContactsPagerFragment, CONTACTS_PAGER_FRAGMENT)
.commit();
}
}
}
Zatta said:
You have to use (override) onActivityCreated for that.
Taptalked u see .. əəs n pəʞlɐʇdɐʇ
Click to expand...
Click to collapse
Could you elaborate a little bit on that? Where should I use onActivityCreated? I need to use notifyDataSetChanged() whenever a button is pressed. Maybe you're talking about the variable.
I don't really need the _viewExists variable, it was only created to debug the problem.
domenicop said:
Sure, here they are.
Fragment
Code:
public static ContactListFragment newInstance(ContactsDatabase database) {
ContactListFragment f = new ContactListFragment();
Bundle args = new Bundle();
args.putSerializable(DATABASE, database);
f.setArguments(args);
return f;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
mDatabase = (ContactsDatabase) args.getSerializable(DATABASE);
}
Activity
Code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Initialize the mDatabase
mContactsDatabase = ContactsDatabase.getInstance(getApplicationContext());
// Determine device orientation
mDualPane = getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
// Set the fragment that will be changed
mFragmentToReplace = mDualPane ? R.id.contactsPagerFragmentContainer : R.id.portraitFragmentContainer;
// Set up the GUI
FragmentManager fm = getSupportFragmentManager();
if (!mDualPane) {
Log.d(TAG, "Orientation Portrait detected.");
// First, look for previously saved fragments
// findByFragmentId(int id) look for the fragment that was previously associated
// to the resource that has for id the argument passed in. Then, we try to cast it
// to the type of fragment we want, and if that's correct, we have our fragment
mContactListFragment = (ContactListFragment) fm.findFragmentByTag(CONTACT_LIST_FRAGMENT);
if (mContactListFragment == null) {
mContactListFragment = ContactListFragment.newInstance(mContactsDatabase);
fm.beginTransaction()
.add(R.id.portraitFragmentContainer, mContactListFragment, CONTACT_LIST_FRAGMENT)
.commit();
}
}
else {
Log.d(TAG, "Orientation Landscape detected.");
// First, look for previously saved fragments
mContactListFragment = (ContactListFragment) fm.findFragmentByTag(CONTACT_LIST_FRAGMENT);
mContactsPagerFragment = (ContactsPagerFragment) fm.findFragmentByTag(CONTACTS_PAGER_FRAGMENT);
if (mContactListFragment == null) {
mContactListFragment = ContactListFragment.newInstance(mContactsDatabase);
fm.beginTransaction()
.add(R.id.contactListFragmentContainer, mContactListFragment, CONTACT_LIST_FRAGMENT)
.commit();
}
if (mContactsPagerFragment == null) {
final int FIRST_CONTACT_POSITION = 0;
mContactListFragment = ContactListFragment.newInstance(mContactsDatabase);
mContactsPagerFragment =
ContactsPagerFragment.newInstance(FIRST_CONTACT_POSITION, mContactsDatabase);
fm.beginTransaction()
.add(R.id.contactsPagerFragmentContainer, mContactsPagerFragment, CONTACTS_PAGER_FRAGMENT)
.commit();
}
}
}
Click to expand...
Click to collapse
domenicop said:
Could you elaborate a little bit on that? Where should I use onActivityCreated? I need to use notifyDataSetChanged() whenever a button is pressed. Maybe you're talking about the variable.
I don't really need the _viewExists variable, it was only created to debug the problem.
Click to expand...
Click to collapse
After the fragment is created is stays created. When you rotated the device the onCreate of the activity is called again but not the onCreateView of the fragment. However, the onActivityCreated in the fragement is.
See for reference http://developer.android.com/guide/components/fragments.html#CoordinatingWithActivity
Your explanation was crystal clear.
However, the developer reference was not that help.
In the article you linked, it says to watch at figure 3 and notice how when the activity is created, the fragment will receive only the onActivityCreated() callback.
The flow of a fragment's lifecycle, as it is affected by its host activity, is illustrated by figure 3. In this figure, you can see how each successive state of the activity determines which callback methods a fragment may receive. For example, when the activity has received its onCreate() callback, a fragment in the activity receives no more than the onActivityCreated() callback.
Click to expand...
Click to collapse
This is Figure 3
{
"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"
}
I need to know which activity callback affects which fragment callback but I can't extrapolate anything from here.
Should I worry about my sight/cognitive decline?
Also, there is a main problem with the way I add fragments to the layout, I just noticed.
Basically, look at this code in MainActivity.java
Code:
// Set up the GUI
FragmentManager fm = getSupportFragmentManager();
if (!mDualPane) {
Log.d(TAG, "Orientation Portrait detected.");
// First, look for previously saved fragments
// findByFragmentId(int id) look for the fragment that was previously associated
// to the resource that has for id the argument passed in. Then, we try to cast it
// to the type of fragment we want, and if that's correct, we have our fragment
mContactListFragment = (ContactListFragment) fm.findFragmentByTag(CONTACT_LIST_FRAGMENT);
if (mContactListFragment == null) {
mContactListFragment = ContactListFragment.newInstance(mContactsDatabase);
fm.beginTransaction()
.add(R.id.portraitFragmentContainer, mContactListFragment, CONTACT_LIST_FRAGMENT)
.commit();
}
}
else {
Log.d(TAG, "Orientation Landscape detected.");
// First, look for previously saved fragments
mContactListFragment = (ContactListFragment) fm.findFragmentByTag(CONTACT_LIST_FRAGMENT);
mContactsPagerFragment = (ContactsPagerFragment) fm.findFragmentByTag(CONTACTS_PAGER_FRAGMENT);
if (mContactListFragment == null) {
mContactListFragment = ContactListFragment.newInstance(mContactsDatabase);
fm.beginTransaction()
.add(R.id.contactListFragmentContainer, mContactListFragment, CONTACT_LIST_FRAGMENT)
.commit();
}
if (mContactsPagerFragment == null) {
final int FIRST_CONTACT_POSITION = 0;
mContactListFragment = ContactListFragment.newInstance(mContactsDatabase);
mContactsPagerFragment =
ContactsPagerFragment.newInstance(FIRST_CONTACT_POSITION, mContactsDatabase);
fm.beginTransaction()
.add(R.id.contactsPagerFragmentContainer, mContactsPagerFragment, CONTACTS_PAGER_FRAGMENT)
.commit();
}
}
When I am in dualPane mode, the mContactListFragment won't be on the screen.
That happens because
Code:
(ContactListFragment) fm.findFragmentByTag(CONTACT_LIST_FRAGMENT);
does not return null even though the fragment is not in the layout (it look for fragments in the BackStack in that case).
I fixed this explicitly checking for that case:
Code:
(mContactsPagerFragment == null || !mContactListFragment.isInLayout())
but I still have a doubt: Should the fragment be treated in another way when found in the BackStack?
Maybe I can take it back on top of the stack, refreshing its view?
I ask this because it seems like a candidate to performance issue, or worse, something that could result in the creation of double/triple fragment running on the activity (with just one of them visible, of course)
Sorry if the explanation was messy, bring that up and I'll try to reformulate the problem in other words.
Thank you guys
Zatta said:
After the fragment is created is stays created. When you rotated the device the onCreate of the activity is called again but not the onCreateView of the fragment. However, the onActivityCreated in the fragement is.
See for reference http://developer.android.com/guide/components/fragments.html#CoordinatingWithActivity
Click to expand...
Click to collapse
No, the Fragments are destroyed when the Activity is destroyed. However, you can call
Code:
setRetainInstance(true)
in the Fragment code/onCreate method so that it won't be destroyed. But in general Fragments are destroyed when the Activity is destroyed.
Aditionally, the setRetainInstance() method is meant to be used with Fragments without UI only. That way you can use it to execute background tasks. (It does work with UI Fragments, too, but it's bad practice.)
Evidence:
If an activity stops, its fragments are also stopped; if an activity is destroyed its fragments are also destroyed.
Click to expand...
Click to collapse
Source: http://www.vogella.com/articles/AndroidFragments/article.html#usingfragments_lifecycle
---------- Post added at 07:51 PM ---------- Previous post was at 07:38 PM ----------
domenicop said:
Also, there is a main problem with the way I add fragments to the layout, I just noticed.
Click to expand...
Click to collapse
Exactly, that's why the onActivityCreated() method isn't called.
You create the Fragments after the Activity has been created. So it wouldn't make sense to call that method. Maybe you could use onAttach() instead.
Try to do the dual pane implementation like this: http://developer.android.com/guide/components/fragments.html#Example
(Or use the template in Android Studio/Eclipse.)
nikwen said:
No, the Fragments are destroyed when the Activity is destroyed. However, you can call
Code:
setRetainInstance(true)
in the Fragment code/onCreate method so that it won't be destroyed. But in general Fragments are destroyed when the Activity is destroyed.
Aditionally, the setRetainInstance() method is meant to be used with Fragments without UI only. That way you can use it to execute background tasks. (It does work with UI Fragments, too, but it's bad practice.)
Evidence:
Source: http://www.vogella.com/articles/AndroidFragments/article.html#usingfragments_lifecycle
Click to expand...
Click to collapse
I should have replied before that all is good if I add the adapter from the onActivityCreated callback.
I also knew about fragment being destroyed when the activity is destroyed when setRetainInstance() was not called.
Maybe when fragments are recreated, the callbacks invoked are just a sub-set of the original one.
PS. Have you read my previous post?
domenicop said:
PS. Have you read my previous post?
Click to expand...
Click to collapse
I did. Check my answer. (Did it one by one.)
nikwen said:
Exactly, that's why the onActivityCreated() method isn't called.
You create the Fragments after the Activity has been created. So it wouldn't make sense to call that method. Maybe you could use onAttach() instead.
Click to expand...
Click to collapse
I didn't follow your line of thought, could you please re-elaborate?
nikwen said:
Try to do the dual pane implementation like this: http://developer.android.com/guide/components/fragments.html#Example
(Or use the template in Android Studio/Eclipse.)
Click to expand...
Click to collapse
I can't because I need to dynamically change them later and this wouldn't be possible with the static xml initialization.
Fragments present in XML, can't be .remove()'ed.
domenicop said:
I didn't follow your line of thought, could you please re-elaborate?
Click to expand...
Click to collapse
Sorry, forget about the first part of my post. Just checked the documentation:
onActivityCreated(Bundle) tells the fragment that its activity has completed its own Activity.onCreate().
Click to expand...
Click to collapse
(Source: http://developer.android.com/reference/android/app/Fragment.html)
I can't because I need to dynamically change them later and this wouldn't be possible with the static xml initialization.
Fragments present in XML, can't be .remove()'ed.
Click to expand...
Click to collapse
Why can't you remove them?
---------- Post added at 08:13 PM ---------- Previous post was at 08:09 PM ----------
nikwen said:
Sorry, forget about the first part of my post. Just checked the documentation:
(Source: http://developer.android.com/reference/android/app/Fragment.html)
Click to expand...
Click to collapse
OK, don't forget about it. Checked it again. :laugh:
The commit() method of FragmentTransaction:
Schedules a commit of this transaction. The commit does not happen immediately; it will be scheduled as work on the main thread to be done the next time that thread is ready.
Click to expand...
Click to collapse
http://developer.android.com/reference/android/app/FragmentTransaction.html#commit()
This means that the Fragment is added after the Activity has finished the onCreate() method.
However, the onActivityCreated() method is just called when the onCreate() method of the Activity has finished. In this case the Fragments doesn't exist at that time. So the method cannot be called.
Does it make sense now?
---------- Post added at 08:17 PM ---------- Previous post was at 08:13 PM ----------
One more try:
Activity is created
FragmentTransaction is sheduled
onCreate() finishes
No Fragment whose onActivityCreated() method can be called exists
Fragment is created
onActivityCreated() isn't called as it's just called when the Activity's onCreate() method finishes (on all Fragments that exist at that time).
nikwen said:
Activity is created
FragmentTransaction is sheduled
onCreate() finishes
No Fragment whose onActivityCreated() method can be called exists
Fragment is created
onActivityCreated() isn't called as it's just called when the Activity's onCreate() method finishes (on all Fragments that exist at that time).
Click to expand...
Click to collapse
Nice catch man!
I tried to just initialize the adapter onCreate() and all is good.
Do you have any particular reason for indicating onAttach()?
I have to say if it wasn't for this list though, I thought you were just going crazy making things up
Also I've to ask one thing at this point, why do you say that the fragments are not created when the onCreate() method ends?
Aren't they initialized inside that method?
domenicop said:
Nice catch man!
I tried to just initialize the adapter onCreate() and all is good.
Do you have any particular reason for indicating onAttach()?
I have to say if it wasn't for this list I though you were just going crazy making things up
Click to expand...
Click to collapse
Haha. Great. :laugh:
Why I talked about onAttach(): At that point you can be sure that there's an Activity which is available via getActivity().
But if it works for you now, don't change it.
---------- Post added at 09:15 PM ---------- Previous post was at 09:10 PM ----------
domenicop said:
Also I've to ask one thing at this point, why do you say that the fragments are not created when the onCreate() method ends?
Aren't they initialized inside that method?
Click to expand...
Click to collapse
Ah, I haven't been accurate enough. Should have been like this:
Activity is created
Fragment is created
FragmentTransaction is sheduled
onCreate() finishes
No Fragment whose onActivityCreated() method can be called is attached to the Activity
Fragment is added to the Activity
onActivityCreated() isn't called as it's just called when the Activity's onCreate() method finishes (on all Fragments that exist at that time).
It's being created during onCreate() but it's added to the Activity later. That's why there's no attached Fragment whose onActivityCreated() method can be called.
And why it's added later:
The commit() method of FragmentTransaction:
Schedules a commit of this transaction. The commit does not happen immediately; it will be scheduled as work on the main thread to be done the next time that thread is ready.
Click to expand...
Click to collapse
http://developer.android.com/reference/android/app/FragmentTransaction.html#commit()

[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

Need help creating a menu in my app

Im new to app development and im having trouble adding a menu to my app. Im using eclipse. I don't get any errors but when I start the app and press the menu button on my phone nothing happens.
Code:
package com.JEB.mybills;
import android.annotation.TargetApi;
import android.app.ListFragment;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
public class ReminderListFragment extends ListFragment {
[user=439709]@override[/user]
public void onActivityCreated (Bundle savedInstanceState){
super.onActivityCreated (savedInstanceState);
setEmptyText (getResources() .getString(R.string.no_reminders));
}
private ListAdapter mAdapter;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
String[] items = new String[] {"Foo", "Bar", "Fizz", "Bin"};
mAdapter = new ArrayAdapter<String>(getActivity(),
R.layout.reminder_row, R.id.text1, items);
setListAdapter(mAdapter);
}
public void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
Intent i = new Intent(getActivity(), ReminderEditActivity.class);
i.putExtra(ReminderProvider.COLUMN_ROWID, id);
startActivity(i);
}
public void onViewCreate(Bundle savedInstanceState){
super.onViewCreated (getView(), savedInstanceState);
registerForContextMenu(getListView());
setHasOptionsMenu(true);
}
[user=439709]@override[/user]
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater){
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.list_menu, menu);
}
[user=439709]@override[/user]
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.menu_insert:
editReminder(0);
return true;
}
return super.onOptionsItemSelected(item);
}
[user=439709]@override[/user]
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo
menuInfo){
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater mi = getActivity().getMenuInflater();
mi.inflate(R.menu.list_menu_item_longpress, menu);
}
public void editReminder(long id){
Intent i=new Intent(getActivity(), ReminderEditActivity.class);
i.putExtra(ReminderProvider.COLUMN_ROWID, id);
startActivity(i);
}
public boolean onCrontextItemSelected(MenuItem item){
switch(item.getItemId()){
case R.id.menu_delete:
//Delete the task
return true;
}
return super.onContextItemSelected(item);
}}
jeb192004 said:
Im new to app development and im having trouble adding a menu to my app. Im using eclipse. I don't get any errors but when I start the app and press the menu button on my phone nothing happens.
Click to expand...
Click to collapse
First I have to say that using the "CODE /CODE" tags (obviously with "[ ]") would be a good idea, when posting so that it looks better
Code:
@override
public void onActivityCreated (Bundle savedInstanceState){
super.onActivityCreated (savedInstanceState);
setEmptyText (getResources() .getString(R.string.no_reminders));
}
Your not very clear but I assume, you want something to happen when you press the physical menu key on your device ? If so I don't see anything that captures the event of this key ? Or am I missing something ? If I wanted to close my app by pressing a physical menu key I would probably do something like
Code:
@Override
public boolean onKeyDown(int keycode, KeyEvent e) {
switch(keycode)
{
case KeyEvent.KEYCODE_MENU:
this.finish();
break;
}
return super.onKeyDown(keycode, e);
}
But not all devices have physical menu keys. My answer is based on assumptions and guess work of what your wanting
My phone has the menu button on the screen.(LG g flex)
Sent from my LG-LS995 using xda app-developers app
deanwray said:
Code:
@Override
public boolean onKeyDown(int keycode, KeyEvent e) {
switch(keycode)
{
case KeyEvent.KEYCODE_MENU:
this.finish();
break;
}
return super.onKeyDown(keycode, e);
}
But not all devices have physical menu keys. My answer is based on assumptions and guess work of what your wanting
Click to expand...
Click to collapse
where you have
Code:
return super.onKeyDown(keycode, e);
I get an error saying its "undefined for the type ListFragment"
jeb192004 said:
where you have
Code:
return super.onKeyDown(keycode, e);
I get an error saying its "undefined for the type ListFragment"
Click to expand...
Click to collapse
I never said your phone didn't have a menu key (I obviously assumed it did, was just saying not all do)
The error is because your inside a fragment, that while has access to Context does not have direct reference. Overriding a key is for Activity/FragmentActivity/Application context
deanwray said:
I never said your phone didn't have a menu key (I obviously assumed it did, was just saying not all do)
The error is because your inside a fragment, that while has access to Context does not have direct reference. Overriding a key is for Activity/FragmentActivity/Application context
Click to expand...
Click to collapse
So...Everything for my menu go into the activity? Not my fragment?
I been trying to learn form "Android Application Development For Dummies" and its telling me to put it all in my fragment...
Ok...I got your code to work and it exited the app but now I'm having trouble getting it to open my options menu
jeb192004 said:
Ok...I got your code to work and it exited the app but now I'm having trouble getting it to open my options menu
Click to expand...
Click to collapse
well thats unrelated, you mean you dont know in android how to open the options menu ? There are simple tutorials on it on d.android.com you should have a read, lots of good info there

[Guide] Listeners in Java development

You are new to java development and want to get buttons working?
Maybe you are a Pro but want a reminder?
whatever you are this Guide is to help you to make buttons/check boxes...etc working and functional
Some people are distracted between guides over internet and want the easiest way to get their project working, me too
Steps :
1-Define the button :
Code:
Button btn1;
Checkbox chkbox1;
RadioButton radio1;
2- Intialize it :
Code:
btn1 = (Button) findViewById(R.id.btn1);
chkbox1= (Checkbox ) findViewById(R.id.chkbox1);
radio1= (RadioButton) findViewById(R.id.radio1);
3-Add the listener :
Button:
Code:
btn1.setOnClickListener(new OnClickListener() {
@SuppressWarnings("deprecation")
@Override
public void onClick(View arg0) {
//Write awesome code here
}
});
CheckBox :
Code:
chkbox1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (start.isChecked()) {
//if the checkbox checked
} else {
//if not checked
}
}
});
}
radio button:
Code:
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId()) {
case R.id.radio1:
if (checked){
}
else{
}
break;
}
}
or use it in a radio Group :
Code:
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio1:
if (checked)
//Write code
break;
case R.id.radio2:
if (checked)
//Write code
break;
}
}
Also insted of this you can use a onCheckedChanged for a radio button (Thanks for GalaxyInABox)
Code:
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (radioGroup.getCheckedRadioButtonId()) {
//Code
}
}
____________________________________________________________________
____________________________________________________________________
Also you can implement a Onclicklistener for the whole class to save resources : (thanks for @Jonny )
after defining and initializing your objects add this :
Code:
OnClickListener click_listener = new OnClickListener() {
public void onClick(View view) {
int id = view.getId();
if (id == your_id) {
//do stuff for this object
} else if (id == your_id2) {
//do other stuff for diffrent object
} else if (id == your_id3) {
//and so on
}
}
};
To do list :
-add on touch listeners
-add on drag listeners
Note : you can add a click listener to almost any thing (Textview or imageView or even EditText) just using the same method of adding listener to button
also there is some other ways to add a listener but this is the fastest and less disturbing :good:
If this guide is useful, press thanks
@ OP
CheckBox and RadioButtons don't they provide a CheckedChangeListener ?
Sent from my GT-S5302 using Tapatalk 2
sak-venom1997 said:
@ OP
CheckBox and RadioButtons don't they provide a CheckedChangeListener ?
Click to expand...
Click to collapse
Yes, and now you can use
Code:
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (radioGroup.getCheckedRadioButtonId()) {
//Code
}
}
to get the checked button. They are pretty much the same, but you can use view.getTag() easier in the first one.
And @mohamedrashad please show how to put the listener into a inner class. Many people don't know/use it, but it's that useful!
GalaxyInABox said:
Yes, and now you can use
Code:
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (radioGroup.getCheckedRadioButtonId()) {
//Code
}
}
to get the checked button. They are pretty much the same, but you can use view.getTag() easier in the first one.
Click to expand...
Click to collapse
I meant that the op shuld edit this guide and use those instead of OnCickListeners
GalaxyInABox said:
And @mohamedrashad please show how to put the listener into a inner class. Many people don't know/use it, but it's that useful!
Click to expand...
Click to collapse
ya new with java8 it will be a nice usage scenario of lambadas
Sent from my GT-S5302 using Tapatalk 2
GalaxyInABox said:
Yes, and now you can use
Code:
@Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
switch (radioGroup.getCheckedRadioButtonId()) {
//Code
}
}
to get the checked button. They are pretty much the same, but you can use view.getTag() easier in the first one.
And @mohamedrashad please show how to put the listener into a inner class. Many people don't know/use it, but it's that useful!
Click to expand...
Click to collapse
sak-venom1997 said:
@ OP
CheckBox and RadioButtons don't they provide a CheckedChangeListener ?
Sent from my GT-S5302 using Tapatalk 2
Click to expand...
Click to collapse
ok, i will add this
You can also add onClick property in XML and then handle it in a code.
Awesome tutorial! Thank you very much!
Please, you could share more related knowledge. It's really useful!
Also, an activity can be a listener. In this case:
MyActivity implements onClickListener {
btn1.setOnClickListener(this);
public void onClick (View v) {
//your code
}
}
For this kind of stuff, using some well known libraries from well known Android dev is a must.
https://github.com/JakeWharton/butterknife
Very powerfull, super easy to use, error prone and without any performance impact.
rafalniski said:
You can also add onClick property in XML and then handle it in a code.
Click to expand...
Click to collapse
SKAm69 said:
Also, an activity can be a listener. In this case:
MyActivity implements onClickListener {
btn1.setOnClickListener(this);
public void onClick (View v) {
//your code
}
}
Click to expand...
Click to collapse
will add them both, although I don't like this way
Mohamedrashad. Thanks a lot.
Sent from my P880 using Tapatalk
If you have multiple clickable objects then it's best to use just 1 onClickListener for all of them and use a switch on their ID's. This reduces resource usage as you only have 1 listener, not 5, 10 or however many you would have otherwise. It's not essential for this but it is a best practice if you want to streamline your code.
Mobile right now so I can't chuck up an example until tomorrow evening or so.
You dude had a great thread. Its helping me. Bravoo !!
Sent from my GT-I8190 using XDA Premium 4 mobile app
As @Jonny already pointed out: Use your class as a listener instead of creating a new (anonymous) inner class! Say you have a ListView, instead of doing this:
Code:
class MyFragment extends Fragment {
private void someMethod() {
((ListView) getView().findViewById(R.id.someListView)).setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Code...
}
});
}
}
you can do this:
Code:
class MyFragment extends ListFragment implements AdapterView.OnItemClickListener, View.OnClickListener {
private void someMethod() {
((ListView) getView().findViewById(R.id.someListView)).setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Code...
}
}
This may look stupid, but when you have many listeners, you can un-clutter it. In my opinion this is the best way. You can also add "this" class as listener for as many ui elements as you want(because all of them extend view, you can use one OnClickListener), then you only need to have a switch statement to distinguish between the views. And voila, you prevented cluttering the code with boilerplate stuff.
Example using code in an app I'm making - app for my school.
Code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Some code here for view/layouts etc
websitebutton = (Button) view.findViewById(R.id.website_btn);
facebookbutton = (Button) view.findViewById(R.id.facebook_btn);
twitterbutton = (Button) view.findViewById(R.id.twitter_btn);
websitebutton.setOnClickListener(handler);
facebookbutton.setOnClickListener(handler);
twitterbutton.setOnClickListener(handler);
return view;
}
OnClickListener handler = new OnClickListener() {
public void onClick(View view) {
switch (view.getId()) {
case R.id.website_btn :
Uri website = Uri.parse("http://wirralgrammarboys.com/");
Intent websiteintent = new Intent(Intent.ACTION_VIEW, website);
startActivity(websiteintent);
break;
case R.id.facebook_btn :
Uri facebook = Uri.parse("https://www.facebook.com/WirralGSB");
Intent facebookintent = new Intent(Intent.ACTION_VIEW, facebook);
startActivity(facebookintent);
break;
case R.id.twitter_btn :
Uri twitter = Uri.parse("https://twitter.com/WGSB");
Intent twitterintent = new Intent(Intent.ACTION_VIEW, twitter);
startActivity(twitterintent);
break;
}
}
};
Jonny said:
Example using code in an app I'm making.
Code:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Some code here for view/layouts etc
websitebutton = (Button) view.findViewById(R.id.website_btn);
facebookbutton = (Button) view.findViewById(R.id.facebook_btn);
twitterbutton = (Button) view.findViewById(R.id.twitter_btn);
websitebutton.setOnClickListener(handler);
facebookbutton.setOnClickListener(handler);
twitterbutton.setOnClickListener(handler);
return view;
}
OnClickListener handler = new OnClickListener() {
public void onClick(View view) {
int id = view.getId();
if (id == R.id.website_btn) {
Uri website = Uri.parse("http://wirralgrammarboys.com/");
Intent websiteintent = new Intent(Intent.ACTION_VIEW, website);
startActivity(websiteintent);
} else if (id == R.id.facebook_btn) {
Uri facebook = Uri.parse("https://www.facebook.com/WirralGSB");
Intent facebookintent = new Intent(Intent.ACTION_VIEW, facebook);
startActivity(facebookintent);
} else if (id == R.id.twitter_btn) {
Uri twitter = Uri.parse("https://twitter.com/WGSB");
Intent twitterintent = new Intent(Intent.ACTION_VIEW, twitter);
startActivity(twitterintent);
}
}
};
Click to expand...
Click to collapse
i'm adding this to OP if you don't mind jonny
mohamedrashad said:
i'm adding this to OP if you don't mind jonny
Click to expand...
Click to collapse
That's fine - if I didn't want people to use/adapt/learn from the code then I wouldn't put it up, use it as you want :good:
Sent from my HTC One using Tapatalk
Keep it up
Great tutorials, keep em coming!
Hey what about starting a new activity with onClickListiner
Sent from my M3S_D7 using XDA Free mobile app
---------- Post added at 03:57 PM ---------- Previous post was at 03:49 PM ----------
Hey and do u mind sending a source codes.zip file
Sent from my M3S_D7 using XDA Free mobile app
Rebound.co said:
Hey what about starting a new activity with onClickListiner
Sent from my M3S_D7 using XDA Free mobile app
---------- Post added at 03:57 PM ---------- Previous post was at 03:49 PM ----------
Hey and do u mind sending a source codes.zip file
Sent from my M3S_D7 using XDA Free mobile app
Click to expand...
Click to collapse
in the onClick method just have this code:
Code:
startActivity(new Intent(this, YourActivity.class));

Lock App

i am trying to make a lockscreen replacement app. I want my app to diplay instead of android lockscreen .
I 've done some search and made it work fine , but when home button is pressed my app exits. I've read that it is not possible to ignore home button on android >4.0.1
But apps on playstore don't have this problem. There must be a way not to exit on home button pressed
TakisBeskos said:
i am trying to make a lockscreen replacement app. I want my app to diplay instead of android lockscreen .
I 've done some search and made it work fine , but when home button is pressed my app exits. I've read that it is not possible to ignore home button on android >4.0.1
But apps on playstore don't have this problem. There must be a way not to exit on home button pressed
Click to expand...
Click to collapse
Try this I am forget after it
@override
public void onPause() {
super.onPause();
return;
}
@override
public void onBackPressed() {
super.onBackPressed();
return;
}
@override
public void onStop() {
super.onStop();
return;
}
@override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return keyCode == KeyEvent.KEYCODE_HOME
|| keyCode == KeyEvent.KEYCODE_BACK;
}
Sent from my SM-G530H using XDA Free mobile app
AndroidFire said:
Try this I am forget after it
@override
public void onPause() {
super.onPause();
return;
}
@override
public void onBackPressed() {
super.onBackPressed();
return;
}
@override
public void onStop() {
super.onStop();
return;
}
@override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return keyCode == KeyEvent.KEYCODE_HOME
|| keyCode == KeyEvent.KEYCODE_BACK;
}
Sent from my SM-G530H using XDA Free mobile app
Click to expand...
Click to collapse
it didn't work Any other ideas ?
AndroidFire said:
Try this I am forget after it
@override
public void onPause() {
super.onPause();
return;
}
@override
public void onBackPressed() {
super.onBackPressed();
return;
}
@override
public void onStop() {
super.onStop();
return;
}
@override
public boolean onKeyDown(int keyCode, KeyEvent event) {
return keyCode == KeyEvent.KEYCODE_HOME
|| keyCode == KeyEvent.KEYCODE_BACK;
}
Sent from my SM-G530H using XDA Free mobile app
Click to expand...
Click to collapse
You don't need return statements on void methods. By definition void doesn't return anything - your IDE should have already notified you of that.
Edit: Do you even know what the code you wrote does? Why on earth are you overriding all those super methods then just calling the super method from within the overridden method - your code makes absolutely no sense whatsoever.
i am searching a few weeks and i didn't find a thing.
The only idea i have is to make my lockscreen app a launcher , so home button will not exit the locksceen, and when user unlocks it , to open an installed launcher.
but how can i get installed launchers ?
Jonny said:
You don't need return statements on void methods. By definition void doesn't return anything - your IDE should have already notified you of that.
Edit: Do you even know what the code you wrote does? Why on earth are you overriding all those super methods then just calling the super method from within the overridden method - your code makes absolutely no sense whatsoever.
Click to expand...
Click to collapse
can't reconsize it through phone
Sent from my SM-G530H using XDA Free mobile app
TakisBeskos said:
i am searching a few weeks and i didn't find a thing.
The only idea i have is to make my lockscreen app a launcher , so home button will not exit the locksceen, and when user unlocks it , to open an installed launcher.
but how can i get installed launchers ?
Click to expand...
Click to collapse
Try looking here for disabling home button - I'm not sure if it works but might be worth a try:
http://stackoverflow.com/questions/21983462/creating-custom-lockscreen-in-android/28603790#28603790
As for getting a list of installed launchers try the below link:
http://stackoverflow.com/questions/6175821/get-a-list-of-every-launcher-in-android
Jonny said:
Try looking here for disabling home button - I'm not sure if it works but might be worth a try:
http://stackoverflow.com/questions/21983462/creating-custom-lockscreen-in-android/28603790#28603790
As for getting a list of installed launchers try the below link:
http://stackoverflow.com/questions/6175821/get-a-list-of-every-launcher-in-android
Click to expand...
Click to collapse
nope. it didn't work

Categories

Resources