Reputation: 21
There are many activities in my application, every activity has a same button, I would like to set the button's listener in a public class,and then every activity could use it . May I? And how to do?
for example:
public class MainActivity extends Activity implements OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MessageSend ms=new MessageSend(getApplicationContext(),???);
}
}
public class MessageSend implements OnClickListener{
public MessageSend(Context context,???){
this.context=context;
View mView=LayoutInflater.from(context).inflate(R.layout.layout_message_send, null);
Button button= (Button)mView.findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
//Do someting
}
});
}
} The activity_main layout include the layout_message_send. Could i use the way to use the button's listener? if could, the ??? param is ? if not, can you give me a sample?
Upvotes: 0
Views: 155
Reputation: 8337
First Refer this Question/Answer from this Link..
Use any of them or Try it other way which is described below.
If you want to use same method for multiple button from different activities, and you don't want to repeat code.
I prefer to make Common Class For all activities.
Example
Create a class
and public static
method in that class
, and use that method for different Button
from different Activities
.
public class CommonUtils {
// Common Functions
public static void yourMethodName(Context contx,Other Params) {
//Do ur code
}
}
Write this code when you want to use that Function. You can write this on Button's onClickListener()
;
CommonUtils.yourMethodName(Your params);
It helps you to do less coding and you have to change only once if you ever want to change anything.
Upvotes: 1