Button Handlers in Android App - java

I am trying to add multiple button handlers for my app. I have successfully created one button that links to a web page. I am running into trouble with my next button, however. I want to go to a new screen on click. I have create the new screen xml file and the corresponding java file. I have also added the activity to the manifest. I'm just not sure how to add multiple button handlers to the main java page. I have attached how I did my first button. Any advice on how to add a second handler to this page for a button that will change view?
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
public void addListenerOnButton() {
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent browserIntent =
new Intent(Intent.ACTION_VIEW, Uri.parse("http://m.noblenet.org/eg/opac/home?locg=1"));
startActivity(browserIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

If I understand it correctly then buttons appear through onCreateOptionsMenu logic.
Best way to handle the click events in this case would be to override onOptionsItemSelected API. Look here for more details

One of the simplest ways of handling button click is to use android:onClick attribute in xml file for a button view. For example in Button View of your xml add android:onClick="clickMe"
and in your java code write Public void clickMe(View view) { //do something on button click }

Related

I want to remove the optionMenu when there are no items in ListView (emptyView is shown)?

I have an app that adds items to an sqlite database and returns a cursor, this cursor is then used with a custom CursorAdapter called StoreCursorAdapter to show the items in a ListView.
There is a (delete all) button as an optionsMenuItem.
I want to hide this optionsMenuItem when no items are avaliable in the ListView.
InventoryActivty
EditorActivity
Sorry for the links I am a new user so they don't allow me to embed images yet. :-(
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inventory);
//Declare the views
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
ListView list = (ListView) findViewById(R.id.list);
emptyView = findViewById(R.id.empty_view);
//Set the screen to be shown when there are no list items
list.setEmptyView(emptyView);
//StoreCursorAdapter is a custom CursorAdapter
mAdapter = new StoreCursorAdapter(this, null);
list.setAdapter(mAdapter);
}
#Override
protected void onStart() {
super.onStart();
invalidateOptionsMenu();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu options from the res/menu/menu_inventory.xml file.
// This adds menu items to the app bar.
getMenuInflater().inflate(R.menu.menu_inventory, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// User clicked on a menu option in the app bar overflow menu
showDeleteConfirmationDialog();
return super.onOptionsItemSelected(item);
}
I tried
1 - emptyView.visibilty() == View.INVISBLE
2 - list.getAdapter == null
but they didn't work
What statement will do the job?!
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (//what statement) {
MenuItem menuItem = menu.findItem(R.id.action_delete_all);
menuItem.setVisible(false);
}
return true;
}
Note:
OnStart() gets called after I get back from the EditorActivity
Note:
In my app I can delete individual items from another activity so adding invalidateOptionsMenu(); in the onOptionsItemSelected won't do the job.
the correct condition to put inside onPrepareOptionsMenu is:
menuItem.setVisible(!mAdapter.isEmpty());
that is the same comparison the ListView uses manages the empty view (minus null check) (https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/java/android/widget/AdapterView.java#747)
but I believe there's another issue here, is that the data is changing after the activity started, during showDeleteConfirmationDialog(). That means you have to call invalidateOptionsMenu() the moment the data is changed. There're two ways of doing it. One more robust and the other is faster to code:
faster to code (but not very good/clean):
add invalidateOptionsMenu() after the code that executes the DB operations.
more robust/clean
you'll use start/stop callbacks to listen to changes in the data. Something like the following:
#Override protected void onStart(){
super.onStart();
invalidateOptionsMenu();
mAdapter.registerDataSetObserver(dataObserver);
}
#Override protected void onStop(){
mAdapter.unregisterDataSetObserver(dataObserver);
super.onStop();
}
private final DataSetObserver dataObserver = new DataSetObserver(){
#Override public void onChanged(){
invalidateOptionsMenu();
}
#Override public void onInvalidated(){
invalidateOptionsMenu();
}
};
all code above was typed by heart, there're likely typos, but that's the idea and the typos you can fix later at your code.
if you dont have any menu item to show, why are u inflating one, if you dont inflate you wont.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return false;
}
Unless you need to dynamically remove the menu options based on the current state of the activity, this might help How do you remove an inflated menu/items from the new Lollipop Toolbar?

Create child Intent from Fragment

I'm using FragmentActivity for switching between Fragment. But I would like to have a Admin Button on a fragment, and when I click on it, a new fragment or activity appears like a child (with the back button in action bar).
How can I make it ?
Here is my code, that works, but the back button doesn't appear in action bar :
Fragment :
public class Reports extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (container == null) {
return null;
}
public void onClick(View v) {
Intent intent = new Intent(getActivity(), LoginActivity.class);
getActivity().startActivity(intent);
}
});
}
}
Activity (for the moment... but maybe Fragment if we need ?) :
public class LoginActivity extends ActionBarActivity {
public static final String TAG = LoginActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
Button loginButton = (Button) findViewById(R.id.loginButton);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView emailText = (TextView) findViewById(R.id.emailText);
TextView passwordText = (TextView) findViewById(R.id.passwordText);
ParseUser.logInInBackground(emailText.getText().toString(), passwordText.getText().toString(), new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user != null) {
Log.i(TAG, "Yeahhh Login OK");
finish();
} else {
runOnUiThread();
}
}
});
}
});
}
Maybe I have to change something in Manifest ?
All you need to do is enable it inside the activity you're currently at.
When inside a FragmentActivity: getActionBar().setHomeAsUpEnabled(boolean).
Otherwise, inside a Fragment: getActivity().getActionBar().setHomeAsUpEnabled(boolean).
U need to override the onCreateOptionsMenu and onOptionsItemSelected. In the onCreateOptionsMenu method do the following : Inflate the menu into the action bar. You can define the contents of the menu item under res/menu folder.
Next in the onOptionsItemSelected method, you can handle the clicks of the back button added in the action bar. Also keep in mind one thing. In the manifest please use a theme which has action bar in it.
Example : Under the application tag use
android:theme="#android:style/Theme.Light" and not anything like android:theme="#android:style/Theme.Light.NoTitleBar
Well if you are starting a new Activity you can enable the back button in it by writing shouldDisplayHomeUp(); in the onCreate() method and on back should take you to the previous activity in the back stack.
And in the other case of adding a new Fragment you can take a look on this answer for reference as it mentions that when you add a new Fragment you add it to the back stack like this
getSupportFragmentManager().beginTransaction()
.add(detailFragment, "detail")
// Add this transaction to the back stack
.addToBackStack()
.commit();
this will make the back button take you to your previous Fragment

can't repeat text in editText using a button

I have a simple activity in android with a button and an editText widget.
I have referenced the resource for the button, created an instance variable for the button, and invoked the listener method on it.
When I run the application, the button prints to the edit text widget, but only once.
I cannot continue to type "0000000", which is the ideal output that I want, rather than being stuck on "0".
The code I have used is:
public class MainActivity extends Activity implements OnClickListener {
Button btn1;
EditText text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button) findViewById(R.id.btn0);
// set an onclick listener to listen for when the buttons are clicked
toe.setOnClickListener(this);
text = (EditText) findViewById(R.id.editTextSimple);
}
#Override
public void onClick(View v) {
text.setText(btn1.getText().toString());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Is there a method or a work around that I could implement in order to print more digits to the edit text view?
Thank you for your help
There is no need to reinvent the wheel here. You don't even have to use direct Strings.
Your onClick could simply be:
#Override
public void onClick(View v) {
text.append(btn.getText());
}
Also, I don't know what "toe" is in
toe.setOnClickListener(this);
but you should be setting the clicklistener on btn1
Replace
text.setText(btn1.getText().toString());
with
String t=text.getText().toString();
text.setText(t+btn1.getText().toString())

Quit item menu in Android application?

This is a way to close an application using a button:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
System.exit(0);
}
});
}
Instead using a button, how can i create a quit item menu? Thanks
Use methode onOptionsItemSelected(...)
#Override
public boolean onCreateOptionsMenu(Menu menu) {
...
}
#Override
public boolean onOptionsItemSelected(MenuItem Item) {
...
}
see:
http://developer.android.com/guide/topics/ui/menus.html
You can add menu in action bar by defining it in a menu.xml and can detect on click on that menu using onOptionsItemSelected and can create menu using onCreateOptionsMenu method and Here is the very good tutorial for this -: http://www.vogella.com/articles/AndroidActionBar/article.html
Best way to close you're application using click count by pressing back button you can use click count by pressing two times and use
activity.finish();
System.exit(0);
Try this after the menu thing:
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
This will kill your com.myapp.activity process

Where should i declare the button of different layout?

I've made a calculator apps and I'm trying to create an about page showing some information.
The OK button will be coded setContentView(originallayout.xml) to return to the calculator layout.
Where should i put these codes to declare the OK button?
private Button btnOK;
btnOK = (Button)findViewById(R.id.btnOK);
btnok.setOnClickListener(OKListener);
I tried to put these code just below where i did for the buttons at the main layout but the apps just stopped after launch.
07-18 09:39:43.290: E/AndroidRuntime(6984): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hychentsa.calculator/com.hychentsa.calculator.CalculatorActivity}: java.lang.NullPointerException
Instead of using setContentView() to change screens, you should have separate activities. Then, in your about activity, you can simply call finish() on button click to go back to the main activity.
http://developer.android.com/reference/android/app/Activity.html#startActivity(android.content.Intent)
if your layout doesn't content the id of the button (in your case btnOK), Eclipse throws NullPointerException - it can not find it in your layout's content.
So when you set your layout (or menu), it must content the id btnOK. Check it!
Put your button initialization after setContentView(R.layout.your_about_layout_name);
Put all this code in
Button btnOK;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
btnOK = (Button)findViewById(R.id.btnOK);
btnok.setOnClickListener(OKListener);
}
Update:
Look at the answer of invertigo:
It's wrong to change the layout when you click on the button.
You have to do it this way:
CalculatorActivity
public class CalculatorActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calculator_black);
// initialization of your views stays here
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.calculator_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.your_id_to_go_in_about_activity:
Intent intent = new Intent(CalculatorActivity.this, AboutActivity.class);
// put some extras if you need to send information from this page to the
// AboutActivity page with this code: intent.putExtra();
startActivity(intent); // with this code you go to AboutActivity
return true;
case R.id.theme:
// Do Something with the theme
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Now, the place for your initialization of OKButton is in new class, lets call it
AboutActivity
here you can put my earlier code:
public class AboutActivity extends Activity{
Button btnOK;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
btnOK = (Button)findViewById(R.id.btnOK);
btnok.setOnClickListener(OKListener);
}
// and the listener for your OK button have to look like this:
OnClickListener OKListener = new OnClickListener() {
#Override
public void onClick(View v) {
// Do something here if you need
finish(); // with finish() you are returning to the previous page
// which is CalculatorActivity
}
};
}

Categories