Common class for click listener - android

I have 7 buttons in all my 6 activities. All 6 buttons have the same functionality in all activities. How can I perform a common click event lisnter for these 6 buttons.

You can create a new class that implements View.OnClickListener like this:
public class MyClickListener implements View.OnClickListener {
#Override
public void onClick(View view) {
// TODO handle the click
}
}
In all your activities you can then set the click listener like this:
button.setOnClickListener(new MyClickListener());
You could even save the context in the class for displaying Toasts etc.
public class MyClickListener implements View.OnClickListener {
private Context context;
public MyClickListener(Context context) {
this.context = context;
}
#Override
public void onClick(View view) {
Button button = (Button) view;
Toast.makeText(this.context, button.getText().toString(), Toast.LENGTH_SHORT).show();
}
}

Have a class like this:
public class OnClickMaker{
public static View.OnClickListener getOnClick(){
return new View.OnClickListener(){
public void on click(View v){
//do stuff
}
};
}
}
And then in your other class, do this
button.setOnClickListener(OnClickMaker.getOnClick());

Putting more words in Sagar's answer given above.
Assumption:
As you have said you have 7 buttons in your 6 activities, I assume all the 7 buttons have same functionality/code.
Solution:
Step 1: Include android:click="btnFirstClick" in <Button> inside your XML layouts.
Step 2: Define abstract BaseActivity class by extending Activity and include methods with the same name you have given in android:onClick attribute.
abstract public class BaseActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void btnFirstClick(View v) {
}
public void btnSecondClick(View v) {
}
.....
.....
// same for other buttons
}
Step 3: Now extends this BaseActivity to all your 6 activities.
For example:
public class FirstActivity extends BaseActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_first);
}
}

Make a Function in a Class and put that class in the same package where all other classes are there. Simply just call that function in 6 onclicklisteners .

You can do this,
Put the click events in the XML files android:click="clickMe"
Create this function in a Activity say
public void clickMe(View view) {
...//You handling code
}
and extend this Activity by all your activities.

You can do like following
create a base activity
class BaseActivity extends Activity{
public void onSpecificEvent(View v){
// do your tasks
}
}
now extends your activities from this one
class Activity1 extends BaseActivity
class Activity2 extends BaseActivity
In which buttons you need to implement the onClick use following in xml
android:onClick="onSpecificEvent"

If you are in the same situation like me, I have a linear layout with undetermined number of buttons in it (generated dynamically) and you want a common listener for all of the button (log out their text for example), you can do like this
for (int i = 0; i < linearLayout.getChildCount(); i++)
{
final Button b = (Button) linearLayout.getChildAt(i);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Commons.log(b.getText().toString());
//your other code here
}
});
}
Now all the children (buttons) of the linear layout have same click listener

Related

How to control other View in different Activity?

I have created the customAdapter of ListView. when I click the Button in the ListView,I want to control the TextView outside the ListView from different layout. Notice ! There are not in the same Java code.
here is what I want to do:
viewHolder.plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView tx=(TextView) txt.findViewById(R.id.moneytext);
//find the textview outside listview (now In the same java code and xml)
totalmoney= (Integer.parseInt(tx.getText().toString()))+(Integer.parseInt(price[position]));
//get the textview integer and add to my present number
tx.setText(""+totalmoney);
//post on the textview
}
});
There is couple ways to do that I remember 3 of :
1) Add TextView to your ListView adapter constructor's parameters
2) Add your Activity to constructor
3) Use Event based solution like EventBus [This can be used even your TextView and ListView in different Activity and you don't need parameters]
There is example of 1 and 2:
public class YourListAdapter{
TextView strangerTextView;
YourActivity yourActivity;
public YourListAdapter(TextView strangerTextView,Activity yourActivity){
//using one of them is enough
this.strangerTextView=strangerTextView;
this.yourActivity=yourActivity;
}
//when changing text use like
strangerTextView.setText("Class Board");
//or (make sure you have global public textview attribute in your YourActivity class)
yourActivity.textview.setText("Class Board");
}
For EventBus :
1) Create a class that holds event information :
public class TextChangeEvent{
public String newtext;
public TextChangeEvent(String newtext){
this.newtext=newtext;
}
}
2) Then in your relevant Activity :
#Override
protected void onStart() {
super.onStart();
if(!EventBus.getDefault().isRegistered(this))EventBus.getDefault().register(this);
}
#Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
#Subscribe
public void onEvent(TextChangeEvent event) {
this.textView.setText(event.newtext)
}
3) Post events like that, anywhere you want :
EventBus.getDefault().post(new TextChangeEvent("newtext"));
Are your TextView in the same activity? If yes, then you should put
tx = (TextView) findViewById(R.id.moneytext);
in onCreate() method and then access it from listener you have:
tx.setText("" + totalmoney);
If it is not in the same activity, you can make something like this:
public class ClassA extends Activity
{
public TextView textView;
public void onCreate()
{
super.onCreate();
textView = (TextView) findViewById(R.id.moneytext);
}
}
public class ClassB extends Activity
{
...
viewHolder.plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//classA is a global variable that you get for example from contructor
tx = classA.textView;
totalmoney= (Integer.parseInt(tx.getText().toString()))+(Integer.parseInt(price[position]));
//get the textview integer and add to my present number
tx.setText(""+totalmoney);
//post on the textview
}
});
...
}

How to overide onClick(View v) so that all the buttons in my application can excute common task

I have several buttons and several activity. I want all the buttons should execute one common task other then its specific task. I want solution like below which I used to execute backpress for all the activity of application just by writing function of backpress once .
public class BackPressActivity extends Activity {//Now My all activity will be extend BackPressActivity
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
showDialogToSearch();
}}
My Activities
public class ActivityA extends BackPressActivity {
}
public class ActivityB extends BackPressActivity {
}
public class ActivityC extends BackPressActivity {
}
So all my activity will respond to back press without writing it everytime.
I haven't used this but I think it should solve your problem
create a custom OnClickListener
public class MyListener implements View.OnClickListener {
#Override
public void onClick(View view) {
//do something here
}
}
and then in your activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(...);
Button btn = (Button)findViewById(R.id.btnSomething);
btn.setOnClickListener(new MyListener());
}
EDIT
public class BaseActivity extends Activity {
//Now all classes should extend BaseActivity
public void onClick(View v) {
doSomething();
}}
and in your xml file
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClick" />

Android Main Activity Object Access

Im new to Android and got a problem. I wanted to seperate the OnClickListener from the MainActivity class but I don't know how to access the Objects in the Main Activity class except of using static. Would be happy about a solution.
public class MainActivity extends ActionBarActivity {
public Button btn;
public TextView tv;
public MyListener listener;
public MainActivity() {
this.listener = new MyListener();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.btn = (Button) findViewById(R.id.btn1);
this.tv = (TextView) findViewById(R.id.textView1);
this.btn.setOnClickListener(listener);
}
}
public class MyListener implements OnClickListener {
MainActivity activity;
#Override
public void onClick(View v) {
activity.tv.setText("Hi");
}
}
Doesnt work.
I would appreciate any help.
I don't see why you would want them separated like that.
If you don't want to cram the onCreate method of your activity, just implement the listener in your class like so:
public class MainActivity extends ActionBarActivity implements OnClickListener {
...
}
Then reference the listener with this:
this.btn.setOnClickListener(this);
MainActivity is a Activity class. You should not have constructors for the same. You should not instantiate a activity class. You only declare activities in manifest file
You can have this.listener = new MyListener(); in onCreate itself
Make MyListener an inner class of MainActivity

How do I add another listener in the main .java file

When i add another button (nextButton2) in (main activity. x m l) !
Now i want to make button open (third screen.x m l)
can you help me to to add listener to it in this android project in (main.java) but failed??
link original project
my project link
followed by existing logic from your code, this is how it could look like:
public class Main extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.nextButton).setOnClickListener(new handleButton());
findViewById(R.id.nextButton2).setOnClickListener(new handleButton2());
}
class handleButton implements OnClickListener {
public void onClick(View v) {
Intent intent = new Intent(Main.this, Screen2.class);
startActivity(intent);
}
}
class handleButton2 implements OnClickListener {
public void onClick(View v) {
Intent intent = new Intent(Main.this, Screen3.class);
startActivity(intent);
}
}
}
It assumes that you already created new activity called Screen3.java and add it to manifest file:
<activity android:name="your.project.package.Screen3" android:label="#string/app_name" />
There are a number of ways to achieve that:
Anonymous listeners
If you need the listeners only once:
public class Main extends Activity {
public void onCreate(Bundle savedInstanceState) {
button1.setOnClickListener(new OnClickListener() {
// your first listener here
});
button2.setOnClickListener(new OnClickListener() {
// your second listener here
});
}
}
Multiple nested classes
If you want to re-use the listeners in the same class:
public class Main extends Activity {
public void onCreate(Bundle savedInstanceState) {
button1.setOnClickListener(new Listener1());
button2.setOnClickListener(new Listener2());
}
class Listener1 implements OnClickListener {
// your first listener here
}
class Listener2 implements OnClickListener {
// your second listener here
}
}
Multiple top-level classes
If you want to re-use the listeners in more than one class:
public class Main extends Activity {
public void onCreate(Bundle savedInstanceState) {
button1.setOnClickListener(new Listener1());
button2.setOnClickListener(new Listener2());
}
}
class Listener1 implements OnClickListener {
// your first listener here
}
class Listener2 implements OnClickListener {
// your second listener here
}

How should onClick Listener by defined and instantiated for an Activity

My Activity has multiple lists so I have defined MyClickListener as below:
My question is how I should instantiate this class:
MyClickListener mMyClickListener = new MyClickListener();
Or maybe it is better to instantiate inside the onCreate(Bundle) and just define above. Whats considered the better way? I don't want too much in onCreate() its already full of stuff. Any thoughts on the declaration and instatiation? Whats the best way?
private class MyClickListener implements OnClickListener
{
#Override
public void onClick(View view) {
}
}
I use same kind of class mechanism as you mentioned in the question.
this is the way i use,
public class myActivity extends Activity
{
private MyListener listener = null;
private Button cmdButton = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cmdButton = (Button) findViewById(R.id.cmdButton);
cmdButton.setOnClickListener(getListener());
}
// method to fetch the listener object
private MyListener getListener()
{
if (listener == null)
{
listener = new MyListener();
}
return listener;
}
private class MyListener implements Button.OnClickListener
{
public void onClick(View v)
{
}
}
}
Why are you instantiating a listener like that in the first place? Just create a new one when you assign it to your listView.
listView.setOnClickListener( new MyListener());

Categories

Resources