How to use java classes within one activity? - java

How can you use a java class within one activity, by that I mean is having different components of that activity spread out in a bunch of java classes. I'm a little new to android and this is what I have tried so far:
MainActivity.java
package com.example.alex.myapplication;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Something(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Something.java
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
import android.app.Activity;
public class Something {
private Activity activity;
private Button add,subtract,multiply,devide;
private EditText editA, editB, editC;
private double doubleA,doubleB,doubleC;
public Something(Activity a){
activity=a;
click();
}
public void click(){
editA = (EditText) activity.findViewById(R.id.editText);
editB = (EditText) activity.findViewById(R.id.editText2);
editC = (EditText) activity.findViewById(R.id.editText3);
doubleA =Double.parseDouble(editA.getText().toString());
doubleB =Double.parseDouble(editB.getText().toString());
add = (Button) activity.findViewById(R.id.add);
subtract = (Button) activity.findViewById(R.id.subtract);
multiply = (Button) activity.findViewById(R.id.multiply);
devide = (Button) activity.findViewById(R.id.devide);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doubleC = doubleA+doubleB;
String s = "" + doubleC;
editC.setText(s);
}
});
subtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doubleC = doubleA-doubleB;
String s = "" + doubleC;
editC.setText(s);
}
});
multiply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doubleC = doubleA*doubleB;
String s = "" + doubleC;
editC.setText(s);
}
});
devide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doubleC = doubleA/doubleB;
String s = "" + doubleC;
editC.setText(s);
}
});
}
}
So I wasn't sure why my listeners weren't working on my buttons so I tried passing the activity to the class that has the listeners added to the buttons but that didn't work in fact now my application won't even start in the emulator. All I wanted to do was have "MainActivity" handle the "Gui" and have the "Something" class handle the listeners but no matter what I do I can't seem to make them communicate with one another to form one Activity.
LogCat
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.Activity.findViewById(Activity.java:2071)
at com.example.alex.myapplication.Something.click(Something.java:32)
at com.example.alex.myapplication.MainActivity.onCreate(MainActivity.java:19)
at android.app.Activity.performCreate(Activity.java:5937)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity
(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

like a before post XD with 1 java class, call it again after pressing buttons, for example, you can have a invisible buttons, radiobuttons whatever you want invisible and just with a click it turns visible and useful for you, here i go:
First the variable which controls the activity are going to do
String num ="";
then have your buttons, i use 2 of them and the others are invisible
Button bn1;
Button bn2;
Button bn3;
Button bn4;
bn3.setVisibility(View.INVISIBLE);
bn4.setVisibility(View.INVISIBLE);
then the button code, depends on how many buttons you want
Button.setOnClickListener(new Button onclickListener(){
public void onClick(){
//get a default variable in this case String num
Intent intent = new Intent(MainActivity.this, MainActivity.class); num="cero"; intent.putExtra("po", num);
CodigoPeticion=2; startActivityForResult (intent,CodigoPeticion); finish(); break;
}
}
});
this one to get the String num:
Bundle extras = getIntent().getExtras();
if (extras!= null) {
num =extras.getString("po");
}
and at last but not least this one to do someting depending the String:
if (num.matches("cero")){
//do something, enable more buttons, disable radiobuttons,
bn3.setVisibility(View.VISIBLE);
}else if(num.matches("one")){//this string is from another button
//do something else in the same activity, as you spected enable radiobuttons, show a image, etc
bn4.setVisibility(View.VISIBLE);
}else{
//some textview with a specific title
TextView.setText("Something's Wrong");
}
don't forget the bn3 and bn4 listeners!
hope that helps you, see ya!

I think that you should rearrange the code to have the onClickListener inside Something constructor:
Something.java
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
import android.app.Activity;
public class Something {
private Activity activity;
private Button add, subtract, multiply, devide;
private EditText editA, editB, editC;
private double doubleA, doubleB, doubleC;
public Something(Activity a) {
activity = a;
editA = (EditText) activity.findViewById(R.id.editText);
editB = (EditText) activity.findViewById(R.id.editText2);
editC = (EditText) activity.findViewById(R.id.editText3);
add = (Button) activity.findViewById(R.id.add);
subtract = (Button) activity.findViewById(R.id.subtract);
multiply = (Button) activity.findViewById(R.id.multiply);
devide = (Button) activity.findViewById(R.id.devide);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
click(1);
}
});
subtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
click(2);
}
});
multiply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
click(3);
}
});
devide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
click(4);
}
});
}
public void click(int calculate) {
// assume number entered - no error
doubleA = Double.parseDouble(editA.getText().toString());
doubleB = Double.parseDouble(editB.getText().toString());
switch (calculate) {
case 1:
doubleC = doubleA + doubleB;
String s = "" + doubleC;
editC.setText(s);
break;
case 2:
doubleC = doubleA - doubleB;
String s = "" + doubleC;
editC.setText(s);
break;
case 3:
doubleC = doubleA * doubleB;
String s = "" + doubleC;
editC.setText(s);
break;
case 4:
doubleC = doubleA / doubleB;
String s = "" + doubleC;
editC.setText(s);
break;
default:
break;
}
}
}
I think the problem was putting 'click()' method inside the main constructor runs through the code once only. I hope this helps!

You can use your "something" class in the mainactivity.
first initialize "Something" class in the main activity by
Something s = new Something(MainActivity.this);
Than you can use every method of that class in your main Activity.Just as you wanted,like this
s.add.setonclicklistener(...
or
s.click();
//Just use like this.

As I know this will help someone else who encountered the same problem as me will benefit, the problem was that I needed to pass the activity into my Something(Activity a){} constructor and initialize everything into that. Like Something(Activity a){
aT1 = (EditText) a.findViewById(R.id.numberOne);
aT2 = (EditText) a.findViewById(R.id.numberTwo);
aT3 = (EditText) a.findViewById(R.id.result);
add = (Button) a.findViewById(R.id.add);
subtract = (Button) a.findViewById(R.id.subtract);
multiply = (Button) a.findViewById(R.id.multiply);
devide = (Button) a.findViewById(R.id.devide);
}
And all you need to do in main activity is pass the Activity when you make an instance/execute the code(ex: Something s = new Something(this);/new Something(this);) After you done that you can just call s.click(); and it should work.

Related

Getting error in main activity on my basic calculator app

I'm creating a simple android calculator app. There is no compile time error, but when I'm tapping on any button, the app crashes.
package com.buckydroid.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView screen;
private String str1,str2,str3,result,str,sign;
private Double a,b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (TextView)findViewById(R.id.textview);
}
private void onClick(View v){
Button button = (Button) v;
str += button.getText().toString();
screen.setText(str);
a = Double.parseDouble(str);
str = "";
}
private void onClickSigns(View v){
Button button = (Button) v;
sign = ((Button) v).getText().toString();
screen.setText(sign);
str="";
}
private void calculate(View v){
Button button = (Button) v;
str2 = screen.getText().toString();
b = Double.parseDouble(str2);
if (sign .equals("+")){
result = a+b+"";
}
else if (sign .equals("-")){
result = a-b+"";
}
else if (sign .equals("X")){
result = a*b+"";
}
else if (sign .equals("÷")){
result = a/b+"";
}
else{
result = "Something went wrong";
}
screen.setText(result);
}
}
Error Log
10-08 19:44:59.361 19449-19449/com.buckydroid.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.buckydroid.myapplication, PID: 19449
java.lang.IllegalStateException: Could not find method onClick(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
So if you need any other code then please comment
Thank you in advance..
Ok I got it after building in Android studio. The error is a lot bigger than what you pasted and I was able to track it down with the stack trace.
Basically you are trying to concatenate a string to a null with this line in your onClick method: str += button.getText().toString();
Since you can't do that you can fix the issue by replacing:
str += button.getText().toString();
With this:
str = button.getText().toString();
OR
Since this is a calculator app, you can initialize str in the onCreate method with str = ""; and then also remove str = ""; from the onClick method.
Full Code here:
public class MainActivity extends AppCompatActivity {
private TextView screen;
private String str1,str2,str3,result,str,sign;
private Double a,b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (TextView)findViewById(R.id.textview);
str = "";
}
public void onClick(View v){
Button button = (Button) v;
str += button.getText().toString();
screen.setText(str);
a = Double.parseDouble(str);
}
public void onClickSigns(View v){
Button button = (Button) v;
sign = ((Button) v).getText().toString();
screen.setText(sign);
str="";
}
public void calculate(View v){
Button button = (Button) v;
str2 = screen.getText().toString();
b = Double.parseDouble(str2);
if (sign .equals("+")){
result = a+b+"";
}
else if (sign .equals("-")){
result = a-b+"";
}
else if (sign .equals("X")){
result = a*b+"";
}
else if (sign .equals("÷")){
result = a/b+"";
}
else{
result = "Something went wrong";
}
screen.setText(result);
}
}
onClick should be public not private.
also initialize your strings to empty string. Like:
private String str1 = "",str2="",str3="",result="",str="",sign="";
Hope this fixes your issue.
Way 1:
in your main_activity xml file add android:onclick="onClick" and make onClick(View view) method public.
for example
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate"
android:onClick="onClick"/>
And in main_activity.java file
public void onClick(View view){
}
Hope it help you :) Happy coding..

How to clear the intent text?

I have a reset button in Activity A and it works fine since it can clear all the text and display null when the save button in Activity B is clicked. But this only works if there are nothing in the textView before pass to B.
It does not works in below cases.
In Activity A, type " Project 123', click next button go to B. Then I back to Activity A again and click the reset button to clear "Project 123". After done go to Activity B and click submit button. It shows "Project 123" instead of "null"...
Activity A
private TextView c;
String result; // 123
String name; // project
reset=(Button)claims.findViewById(R.id.button14); // reset button
Button button = (Button) claims.findViewById(R.id.button8); //next button
reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
c.setText("");
d.setText("");
e.setText("");
f.setText("");
g.setText("");
h.setText("");
}
});
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent(getActivity().getApplicationContext(), B.class);
if(c!=null){
intent.putExtra("name", name);
intent.putExtra("result", result);
}
});
return A;
}
Activity B
Name=getIntent().getExtras().getString("name");
Result=getIntent().getExtras().getString("result");
save=(Button)findViewById(R.id.button8);
save.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if((Name!=null)&&(Result!=null)){
Toast.makeText(getApplicationContext(), Name+Result, Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(),"null", Toast.LENGTH_LONG).show();
}
}
});
This is because you only clear the setText but not the string.
reset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
c.setText("");
name="";
result="";
}
});
You have to add name="" and result="" in your reset method. It should works.
Kindly refer clear a value from a string android
Actually, the name is not null but with empty string ""
Try to take replace the Name != null with !TextUtils.isEmpty() in B activity.

Syntax error in Eclipse for Android Application [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I think I am going insane, Eclipse throwing up these errors "Syntax error, insert ";" to complete Statement" "Syntax error, insert ")" to complete Expression" "Syntax error, insert "}" to complete ClassBody" "Syntax error, insert "}" to complete MethodBody" and I cant seem to work out why!
Q: Can anybody work out where the syntax errors are or why Eclipse would be saying that there are errors?
Note: The idea of the code is to change the text on the button once it is pressed using the reference: Change button text and action - android development
These errors came up after I added the following lines of code:
/** Called when user clicks Start */
public void sendStart(View view) {
// Do something in response to button
final Button b_start = (Button) findViewById(R.id.b_start);
b_start.setTag (1);
b_start.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
final int status =(Integer) v.getTag();
if(status == 1) {
b_start.setText("Stop");
v.setTag(0);
} else {
b_start.setText("Start");
v.setTag(1);
}
}
The entire class code is as follows:
package com.example.rius;
import android.support.v7.app.ActionBarActivity;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View; // view method to create methods
import android.widget.Button;
import android.widget.EditText;
import android.widget.ToggleButton;
import android.content.Intent; // Intent class for new activities (windows)
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.example.rius.MESSAGE"; // Key for intents extra data
int set_state_start_one = 0;
int set_state_start_two = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/** Called when user clicks RPM */
public void sendRPM(View view) {
// Do something in response to button
Intent intent = new Intent(this, DisplayRPMActivity.class); // Created Intent to bring up new activity (RPM Screen)
startActivity(intent); // Start a new activity (window)
}
/** Called when user clicks SPEED */
public void sendSpeed(View view) {
// Do something in response to button
Intent intent = new Intent(this, DisplaySpeedActivity.class); // Created Intent to bring up new activity (RPM Screen)
startActivity(intent); // Start a new activity (window)
}
/** Called when user clicks DIAGNOSTICS */
public void sendDiag(View view) {
// Do something in response to button
Intent intent = new Intent(this, DisplayDiagnosticActivity.class); // Created Intent to bring up new activity (RPM Screen)
startActivity(intent); // Start a new activity (window)
}
/** Called when user clicks THE TOGGEL BUTTON TO CONNECT */
public void startconnection(View view) {
// Is the toggle on?
boolean on = ((ToggleButton) view).isChecked();
if (on) {
// Enable vibrate
WifiConfiguration wificonfig = new WifiConfiguration();
wificonfig.SSID = String.format("\"%s\"", "XXXXXX");
wificonfig.preSharedKey = String.format("\"%s\"", "XXXXXX");
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
//Remember ID
int netId = wifiManager.addNetwork(wificonfig);
wifiManager.disconnect();
wifiManager.enableNetwork(netId, true);
wifiManager.reconnect();
} else {
// Disable vibrate
WifiConfiguration wificonfig = new WifiConfiguration();
wificonfig.SSID = String.format("\"%s\"", "XXXXXX");
wificonfig.preSharedKey = String.format("\"%s\"", "XXXXXX");
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
//Remember ID
wifiManager.disconnect();
}
} // togglebutton final bracket
/** Called when user clicks Start */
public void sendStart(View view) {
// Do something in response to button
final Button b_start = (Button) findViewById(R.id.b_start);
b_start.setTag (1);
b_start.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
final int status =(Integer) v.getTag();
if(status == 1) {
b_start.setText("Stop");
v.setTag(0);
} else {
b_start.setText("Start");
v.setTag(1);
}
}
} // Final bracket
You're missing the closing }) for setOnClickListener:
b_start.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
final int status =(Integer) v.getTag();
if(status == 1) {
b_start.setText("Stop");
v.setTag(0);
} else {
b_start.setText("Start");
v.setTag(1);
}
}
});

Event get String from 2 buttons

I am using an Adapter to generate buttons in a GridView.
Using an OnClickListener, whenever I click a button from the GridView, it is possible to get the String of the button in a variable. However, I want to click a button, store its text in a variable, then click a different button, store its text in another variable so later I can compare the two texts. How could I do that?
gI'm using OnClickListener, therefore my previous implementation for one button was the following:
public void onClick(View v) {
Button b = (Button)v;
String text = b.getText.toString();
With this approach, I can only get and store text from first button clicked, unless I store all the values in an array.
Ok so from what I can understand, you want to compare the strings of the two items in a grid view. If this is what you want, heres how I would do it(just a psuedocode):
String mValue1, mValue2;
boolean isOneClicked = false;
onItemClickedListener(item, position){
if(!isOneClicked){
mValue1 = item.stringValue;
isOneClicked = true;
}
else{
mValue2 = item.stringValue;
//do whatever you want here
//Reset when done
mValue1 = "";
mValue2 = "";
isOneClicked = false;
}
}
Please you can share your code to turn the things more comprehensible? Edit your question please... Anyways:
MainActivity.java
public class MainActivity extends Activity {
private Button button1;
private Button button2;
private String butString, butString2;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
butString = (String) button1.getText();
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
butString2 = (String) button1.getText();
}
});
}
}
After that you can compare the two strings.

Pass method as parameter in Java to assign Listeners to multiple Buttons

I'm new to Java (coming from Python) and I'm trying to pass a method as a parameter in order to convert this code:
Button button1;
Button button2;
...
Button buttonN;
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClick_button1(v);
}
});
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onClick_button2(v);
}
});
(...)
buttonN = (...)
To something like:
public AssignListener( integer tButton, Method tMethod )
{
button_view = (Button) findViewById(tButton);
button_view.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
tMethod(view);
}
}
}
(...)
AssignListener( R.id.button1, onClick_button1 );
AssignListener( R.id.button2, onClick_button2 );
(...)
AssignListener( R.id.buttonN, onClick_buttonN );
I've read that you can't pass methods to functions, and some advice to wrap my function using Runnable to achieve this.
I have not clear idea about how to do it. Any idea on how do it easily? :?
Thanks.
EDIT: Should I wrap "AssignListener" in its own class and pass the class itself? :?
You can call findViewById() and seOnClickListener into onCreate method, and OnClickListenet outside the onCreate.
Button button1 = (Button)findViewById(R.id.button1);
or
findViewById(R.id.button1).seOnClickListener(mClickListener);
findViewById(R.id.button2).seOnClickListener(mClickListener);
findViewById(R.id.button3).seOnClickListener(mClickListener);
findViewById(R.id.button4).seOnClickListener(mClickListener);
private OnClickListener mClickListener = new View.OnClickListener(
public void onClick(View view){
switch(view.getId()){
case R.id.button1:
//button1 click handle here...
break;
case R.id.button2:
//button2 click handle here...
break;
case R.id.button3:
//button3 click handle here...
break;
case R.id.button4:
//button4 click handle here...
break;
}
});
Try it, hope it will helpful to you.
You could define and pass an onClickListener like this:
public AssignListener( integer tButton, OnClickListener listener ){
tButton.setOnClickListener(listener);
}
The simplest way is to create listener implementation for each button, as is written in your first snippet.
I don't see any reasonable benefit of having universal method like AssignListener(). Don't reinvent bicycle, use existing setOnClickListener() method and pass listener specific for button.
An easy solution would be to create a function called tMethod that takes a button id, and has a switch statement that allows for a certain action to be performed for the given button id. This would then be called inside the onClick function like tMethod(view.getId()).
Btw, Python has methods. Java has functions. Pedant mode turned off!
public class MyClass implements OnClickListener, OnLongClickListener {
Button button1;
Button button2;
...
Button buttonN;
. . .
setButtonsListener(findViewById(<your top view id>));
. . .
void setButtonsListener(ViewGroup vg) {
int count = vg.getChildCount();
Button btn;
View v;
for(int i=0; i < count ; i++) {
v = vg.getChildAt(i);
if( v instanceof Button ) {
btn = (Button)v;
btn.setOnClickListener(this);
btn.setOnLongClickListener(this);
} else if( v instanceof ViewGroup ) {
setButtonsListener((ViewGroup) v);
}
}
}
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}

Categories