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
Related
I decided to try and make my code more object oriented and avoid repetitive code in another class.
Source code for Activities :
public class EasyMode extends MainActivity {
GameActivityPVP game = new GameActivityPVP();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout_pvp);
game.initializeButtons();
}
}
public class GameActivityPVP extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout_pvp);
initializeButtons();
}
public void initializeButtons() {
button[0] = (Button) findViewById(R.id.button1);
}
}
The second the program gets to the line where I try to call a method using game.methodName(); the program crashes. No compiling errors or anything.
I am new to programming in general so please take it easy on me and I tried to simplify my code as much as possible.
Android Monitor/logcat :
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
and
W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
You can use another class's method by creating object of parent class.
See below example;
Here you want to use method from 'GameActivityPVP' class. So you need to create one object in this class only.
public class GameActivityPVP extends MainActivity {
public static GameActivityPVP mGameActivity;
public GameActivityPVP getInstance(){
return mGameActivity; // assign value in onCreate() method.
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout_pvp);
mGameActivity = this; // Do not forget this, otherwise you'll get Exception here.
initializeButtons();
}
public void initializeButtons() {
button[0] = (Button) findViewById(R.id.button1);
}
}
Now use this Object in another class 'EasyMode' like this;
if(GameActivityPVP.getInstance()!=null){
GameActivityPVP.getInstance().initializeButtons();
}
Try This:
Make one Class Utils:
In Utils:
public class Utils{
private Activity context;
Button button;
public Utils(Activity context) {
this.context=context;
}
public void inititializeButton(Activity context){
button[0]= (Button) context.findViewById(R.id.button_flasher);
}
}
And in your Class use:
public class EasyMode extends MainActivity {
Utils utils;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout_pvp);
utils=new Utils(this);
utils.initializeButtons();
}
}
As already stated, you shouldn't use nested activities, they are not supposed to interact like this. If you want two activities to interact you have to do it through an intent. Regarding the duplicated code, you have few solution presented but my personal opinion is that the OOP rules are not followed. If I had to write that logic, I would create a BaseActivity to hold the common logic of the other two activities and use inheritance to extend them.
public class BaseActivity extends Activity {
protected List<Button> buttons = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game_layout_pvp);
initializeButtons();
}
protected void initializeButtons() {
buttons.add((Button) findViewById(R.id.button1));
}
}
public class EasyMode extends BaseActivity {
// Add here logic that is used only in EasyMode activity
}
public class GameActivityPVP extends BaseActivity {
// Add here logic that is used only in GameActivityPVP activity
}
Note that in this way you don't have to override onCreate again to initialise the buttons and so on. Also, I saw that you used the same layout for both activities, but if you want to use different layouts you can do it as usual and then call initializeButtons.
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
}
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
I am working on an android application,
and I have number of activities that extend from a custom activity.
Now I created a new FragmentActivity and I need the same functions that I have implemented in my custom activity.
How can I do that?
Edit
This is an simple example
public class BaseActivity extends Activity
{
protected void someFunction()
{
Log.i("TEST","This is a test");
}
}
public class MainActivity extends BaseActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
someFunction();
}
}
this is my FragmentActivity:
public class MyFragmentActivity extends FragmentActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// here I want to use someFunction()..
}
}
In Java you can't extend more than one class.
So I guess you should extend BaseActivity from FragmentActivity instead of 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());