Setting an onClickListener - android

I am setting an on click listener and I was wondering if this was an ok way to do it? I see a lot of people define the onClickListener in line with the setOnClickListener but that seems really messy so I was wondering if I would run into any problems doing it this way down the road?
public class Login extends Activity {
protected Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
login = (Button) findViewById(R.id.loginButton);
login.setOnClickListener(myOnClick());
}
#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_login, menu);
return true;
}
protected OnClickListener myOnClick() {
OnClickListener v = new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Do stuff
}
};
return v;
}
}

How you define it is your personal coding style choice. You can have the entire class implement the interface, do it inline, do it as you are doing or specify the method to be called via XML. The end result is more or less the same.

If you would like to keep all your onclicklistener methods within one method you could implement the method. For this you do
login.setOnClickListener(this);
And then
extends Activity implements OnClickListener
And finally you will add the unimplemented methods. This will pass all your button clicks to the onclick method where you can use if/else or switch/case to assign whatever method.
Alternatively you can also define it in XML or use the method you've described.
However to go into the benefits and drawbacks: defining the onClick within xml can lead to problems with proguard. Personally I feel the easiest is using a switch and case within the onclicklistener, but if the method is a lot longer then it's nice to give it it's own method so to "hide" it away. If you however need common code to run after any button is pressed (for example a UI refresh) might be better to leave it to a switch and case or if/else
// Just to add for those wanting to use OnClick within xml and proguard
Add this:
-keepclassmembers class * extends android.app.Activity {
public void *(android.view.View);
}

There are multiple approaches for implementing onClickListner on the views. What you have used is also correct and will not create any problem to you. What i personally prefer is to let the Class implement OnClickListener interface and use switch case scenario inside the override onClick method .
e.g.
public class LoginExampleImplements extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
btn1 = (Button)findViewById(R.id.btn1);
btn2 = (Button)findViewById(R.id.btn2);
// Set Click Listener
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btn1:
// do stuff related btn1 click
break;
case R.id.btn2:
// do stuff related btn2 click
break;
}
}

Depends on your code style, still:
Want to use same method for a lot of buttons: let class implement listener interface, and use a switch on view id to find out which button clicked.
Really complex logic follows click: Have an inner/external class implement that listener.
Few lines, nothing special: do inline, the person reading you code need not go looking for a small piece of code.

Related

Android Studio onClick and OnclickListener not working once changed to another Activity

I've added my acivity class in this link
Click MeI am fairly new to Android and am having difficulty trying to add a button on my second activity. I am able to place a button in my main activity and then I use it to navigate to my secondary activity (using setContentView(R.layout.)) and then I use the same 'onClick' method or even 'OnClickListener' method but the button on my second activity just wont work on another activity. Maybe i am missing something
]3
just try to do this:
public class FirstActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first_activity);
findViewById(R.id.about_us).setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(FirstActivity.this, SecondActivity.class));
}
});
}
}
and in second activity again find your button in second activity xml by id and write onClickListener for it
You need to implement two separate methods for two different buttons. I would suggest do these things in the Java code instead of XML.
You can do some thing like this:
Button button = findViewById(R.something.something);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//perform your operation(s) here.
}
});
As I understand you try to use one layout.xml for both activities.
You need to declare method click1 in both activities, not only in first.
It means that your first activity has to have method public void click1() and the second activity has to duplicate method public void click1()
I know it's old however,
#Meikiem idea is great. When you use setContentView(View View) you are just setting the activity's
content to another view (xml), and thus not really using the other .java file which has another
onClick method defined for the second button.
Activity's setContentView(view)
You need to create an Intent and pass it along the startActivity method.
Intent Definition

Multiple OnClickListener with case

Here is the sample i'm doing:
Hi i want to ask if it's possible to set the calculator buttons on a single OnClickListener with a Case switch statement, it would be helpful if there's an answer
Yes it is possible. do the following things :
implement onclickListener in your activity and override onClick method
In onCreate add listeners for all the buttons like
btn1.setonclickListner(this);
btn2.setonclickListner(this);
and so on
In onCLick() method use switch case to check id values of buttons as :
switch(v.getId())
and make cases with your button ids like R.id.btn1 , R.id.btn2 etc
you can do it like this:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View.setonclickListner(this);//must add to each view for onclicklistener to work
}
#Override
public void onClick(View view) {
int id =view.getId();
switch(id){
case R.id.View :
//your code here
break;
}
}
}

Android onClickListener for all inflated views

I have ran into a problem where I have somehow made a dead spot where I can't find the view for it in my app. In that dead spot I need to put a on click listener for that area but I'm unable to find the item.
My question is:
Is there a way to get all of the views that have been inflated for an activity and add a listener to identify which one was clicked?
You can inflate your view in onCreate() set listener for your view
like
yourView.setOnclickListenre(..)
Then You can catch click listener in
#override
public void onClick(View v)
{
switch(v.getId())
{
case R.id.youViewId1:
// youViewId1 id view is clicked
break;
case R.id.youViewId2:
// youViewId2 id view is clicked
break;
}
}
You can implement View.onClicklistener in that activity and override onClick method like below:
Public class MyActivity extends activity implements OnClicklistern {
Public void onCreate(....) {
//here you can inflate view and add setOnclicklister to every view to this activity
}
#Override
Public void OnClicklistern(View view) {
Switch (c.getid()) {
Case R.id.oneview :
//do something
break;
Case R.id.anotherview:
// do something
break;
.......
.......
}
}
}

how to pass data from one fragment to an other if both are visible at a time

I have two fragments in a activity .one has edit field and second has textview .both are visible at time. I have to enter text into edit field and that text should be displayed on the second fragment which a textview. I have one solution , i can make static textview in secodn fragment but i think it is not best way to do that.Kindly guide me.
From the Fragment documentation:
Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.
So i would suggest something like this:
You have two fragments and one associated activity
Code for Activity
public class MainActivity extends FragmentActivity{
//On create stuff .....
#Override
public void onButtonPressed(String msg) {
// TODO Auto-generated method stub
LayOutTwo Obj=(LayOutTwo) getSupportFragmentManager().findFragmentById(R.id.frag_2);
Obj.setMessage(msg);
}
}
Code For Layout 1:
Button but=(Button)root.findViewById(R.id.button1);
but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
buttonListener.onButtonPressed("Message From First Fragment");
}
});
Code For Layout 2:
void setMessage(String msg){
TextView txt=(TextView)root.findViewById(R.id.textView1);
txt.setText(msg);
}
This how you can easily pass data between fragments using its associated activity.
Hope this helps

android button event listener does not work

I know this is the basic stuff but I couldn't figure it out. Here is my code:
public class test extends Activity{
private static final String TAG = "test";
private Button Test;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.v(TAG,"onCreate is called.");
this.setContentView(R.layout.main);
Test= (Button)this.findViewById(R.id.Test);
Test.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v(TAG, "onClick Entered.");
// Perform action on click
}
});
setContentView(R.layout.main);
}
}
I can see the first log "OnCreate" but the button click event listener doesn't seem
to work because I can't see "OnClick Entered". Where did I do wrong?
Thanks
You are calling setContentView twice, the second time after you have set up your on click listener. This means that the view that you add the listener to is no longer visible, it is replaced with a different instance of the view. Remove the second setContentView.
A few comments / things to try:
You have your naming conventions backwards. You should be naming your activity in title case, your variables in camel case (e.g. your activity "test.java" should be Test.java, your Button Test should be Button test). That's not your problem, but just something to keep in mind.
You're calling super.onCreate() twice. I really don't know what effect that has, but it shouldn't be there. You're also calling setContentView() twice. One call to onCreate, one call to setContentView is all you should have. EDIT: Apparently three times, per Jems's comment.
In main.xml, do you have a Button with an id of test? (i.e. android:id="#+id/test")
Where is showTrafficButton defined? Are you sure that shouldn't be:
Button showTrafficButton = (Button)this.findViewById(R.id.Test);

Categories

Resources