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;
}
}
}
Related
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
I have a rather simple screen that only has 4 buttons. I'm implementing it as a Fragment like so:
public class MainFragment extends Fragment implements View.OnClickListener {
// ...
#Override
public void onClick(View view) {}
}
Each button already has onClick specified to a function in the Activity that the Fragment is attached. The issue I'm having is that the onClick functions aren't called when the buttons are clicked. I've left MainFragment.onClick() empty - but is that the right approach? Does it need to be implemented for the functions to be invoked? If so, the onClick attributes in the Button layouts would seem redundant.
Any help will be appreciated.
Thanks
The right approach is to use a fragment listener to communicate back with the activity:
public static class MainActivity extends Activity
implements MainFragment.onFragmentInteraction{
...
public void onFragmentInteraction() {
// Do something
callFunction();
}
}
Then in your fragment:
mYourButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (mListener != null) {
mListener.onFragmentInteraction();
}
}
});
FWIW I never use the xml onClick attributes. Although they may save a couple of lines of typing, they make it more difficult to follow what's happening in your code.
If your class implements View.OnClickListener and you have correctly overriden the onClick method (which it looks like you have), then you can safely remove any onClicks in your layout files and instead assign methods to your widget clicks in the following way:
public class MainFragment extends Fragment implements View.OnClickListener {
private Button viewOne, viewTwo, viewThree;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.your_layout, container, false);
viewOne = (Button) rootView.findViewById(R.id.view_one);
viewTwo = //etc...
//"this" refers to the current object. As the object is of a class that implements OnClickListener,
//passing "this" satisfies the View.OnClickListener parameter required for the setOnClickListener() method.
viewOne.setOnClickListener(this);
viewTwo.setOnClickListener(this);
viewThree.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View view) {
//To identify the correct widget, use the getId() method on the view argument
int id = view.getId();
switch (id) {
case R.id.view_one:
//viewOne clicked
break;
case R.id.view_two:
//And so on...
}
}
}
If you set the onClick in your XML, the click events will go to your container Activity. But you can have the click events go directly to your Fragment by setting the onClickListener to your Fragment's implementation of it. So in your Fragment's onCreateView() method, you would inflate your layout, then set the Button's onClickListener to your Fragment's implementation like this...
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.your_fragment, container, false);
Button button = (Button) view.findViewById(R.id.your_button);
button.setOnClickListener(this);
return view;
}
By setting the setOnClickListener() to this, you are sending all click events for that button to your Fragment instead of your Activity. Then you would just handle your onClick events as you're already doing...
#Override
public void onClick(View view) {
Log.d("YOUR BUTTON", "This is called from your Fragment instead of your Activity");
}
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;
.......
.......
}
}
}
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.
I'm developing an Android 3.1 application that uses fragments.
On one of those fragments a need to create n buttons and set an onClick event handler for each of them.
To do it I want to create a method on FragmentActivity that handles those events but I don't know how. Note: FragmentActivity is a android.support.v4.app.FragmentActivity that manages all fragments using android.support.v4.view.ViewPager.
On another fragment I have the following XMLcode:
<Button
android:id="#+id/btnTakeArticlePhotos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="#string/btn_take_photo"
android:onClick="onTakePhotoClick" />
And this code on FragmentActivity:
public void onTakePhotoClick(View view)
{
Log.v("FillEReportFragmentActivity", "onTakeFactoryPhotoClick");
int imgType, imgSubType;
switch (view.getId())
{
case R.id.btnTakeFactoryPhotos:
imgType = ImageType.EREPORT;
imgSubType = SubImageType.EREPORT_FACTORY_OUTLOOK;
break;
case R.id.btnTakeArticlePhotos:
imgType = ImageType.ARTICLE;
imgSubType = SubImageType.NONSET;
default:
imgType = -1;
imgSubType = -1;
break;
}
Intent intent = new Intent(FillEReportFragmentActivity.this, CameraActivity.class);
intent.putExtra(BundleKeys.tablePk, eReportId);
intent.putExtra(BundleKeys.imgType, imgType);
intent.putExtra(BundleKeys.imgSubType, imgSubType);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
I want to do the same with these n buttons: create a method on FragmentActivity to handle all onClick events.
I see that if I want to handle onClick event on a button created programmatically I need to implement onClickEventListener.
How can I handle those onClick events on FragmentActivity? or is there a better approach?
You should make your FragmentActivity implement View.OnClickListener.
Then in your Fragment in the onActivityCreated() callback you can do the following :
getView().findViewById(R.id.Button1).setOnClickListener(
(OnClickListener)getActivity));
You could also define your own interface and make your Activity implement that interface and the same in onActivityCreated(), and let the Fragment implement OnClickListener and then call your Activity like this :
public MyFragment extends Fragment implements OnClickListener(){
public MyInterface mInterface;
protected void onActiviyCreated(){
mInterface=(MyInterface)getActivity();
}
public void onViewCreated(View view, Bundle savedInstanceState){
view.findViewById(R.id.myButton).setOnClickListener(this);
}
public void onClick(View v){
....
mInterface.buttonClicked();
}
}