How to make the switch work? - java

There is a lot programmatically created buttons, that's 2 of them:
Button agafon_1 = new Button(this);agafon_1.setText(R.string.txt_agafon_1);llPreViewList.addView(agafon_1, lParams);
Button agafon_2 = new Button(this);agafon_2.setText(R.string.txt_agafon_2);llPreViewList.addView(agafon_2, lParams);
There OnClickListener and it has a switch. What do I need to insert in place of the question marks to make the switch work?
switch (???) {
case ???:
//
break;
case ???:
//
break;
}
The file R.java not even mention the id buttons which makes it impossible to use v.getId()...

If you are using the same OnClickListener for every Button set a different id for every Button with Button.setId(int) and the use v.getId() for your switch, where v is the argument of onClick(). Otherwise you can create a different OnClickListener for every button

You class should implement OnClickListener
public class MainActivity extends Activity implements OnClickListener
Then
Button agafon_1 = new Button(this)
agafon_1.setId(yourbuttonid);
agafon_1.setOnClickListener(this);
Then
#Override
public void onClick(View v)
{
switch(v.getId())
{
case buttonid1 : // id must match
break;
case buttonid2 :
break;
...
}
}

Related

Significance of using ID in switch statements in onClick()

I wanted to ask what was the significance of creating a switch statement when implementing the onClickListener interface for multiple buttons. Like, we're already calling the setOnClickListener for that particular button by saying button_name.setOnClickListener()
So what's the point of specifying the id's again in the switch statement ? Why is it necessary to do so ? doesn't the point of doing button_name.setOnClickListener() mean - "do what's in here for this button" ?
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Capture our button from layout
Button button = (Button)findViewById(R.id.corky);
Button button2 = (Button)findViewById(R.id.corky2);
Button button3 = (Button)findViewById(R.id.corky3);
// Register the onClick listener with the implementation above
button.setOnClickListener(this);
button2.setOnClickListener(this);
button3.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// do something when the button is clicked
// Yes we will handle click here but which button clicked??? We don't know
// So we will make
switch (v.getId() /*to get clicked view id**/) {
case R.id.corky:
// do something when the corky is clicked
break;
case R.id.corky2:
// do something when the corky2 is clicked
break;
case R.id.corky3:
// do something when the corky3 is clicked
break;
default:
break;
}
}
}
What I'm trying to ask is, doing button2.setOnCLickListener() means - "Do what's set by this function for button2" right ? if not then what is the actual purpose/function performed by setOnClickListener() ?
Since you have set clickListeners to 3 different buttons, the method
....onClick(View v){.....
is going to get called when you click any of those 3 buttons. If you click the button1 you do not want to perform task actually assigned for button3. So to check and find out which button was pressed the switch statement is necessary.
Alternatively you could have done this:
corkyButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// do something when the corky is clicked
}
});
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// do something when the play is clicked
}
});
so on and so forth...
This way you don't need a switch statement as in this case you know which button is being clicked on, AS you're setting the clickListener AND ALSO specifiying what you wanna do there itself.
It's more of a clean look, a more readable code style structure. If you have multiple widgets who need click listener, by implementing View.OnClickListener interface
and overriding onClick gives a cleaner look.
and inside onClick(View view){
- you can also use if statement but when the number of widgets is more
then it becomes messy, that's why we use switch statement to look cleaner.
}
and
btn.setOnClickListener(this)
// telling the button to pass the interface
so that overridden onClick can listen to this.
But If you don't want that or you have only one widget for click
then just use this, no need to implement and override.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});

How to handle different activities that can be started based on an extra that is pass in?

I have an Activity1 and inside this activity I have a button and when it is pressed, it should go to either ActivityA, ActivityB, or ActivityC based on a specific type passed to Activity1.
I currently have a switch statement that handles this, but the issues is when I want to add in an ActivityD, and ActivityE, I would have to change the code again and the switch statement will continue to grow.
What is a better way to do this?
private int type;
public void onCreate() {
// ...
type = getIntent().getIntExtra("type", 0);
}
#Override
public void onClick(View view) {
Intent intent;
switch (type) {
case 0:
intent = ActivityA.newIntent(this);
break;
case 1:
intent = ActivityB.newIntent(this, 1);
break;
case 2:
intent = ActivityC.newIntent(this, "str");
break;
default:
throw new RuntimeException();
}
startActivity(intent);
}
You can use multiple fragments in an activity and instead of changing the activity, just replace the fragments, however even with fragments you need to call them.
You also can create multiple views and change the view based on the intents, this method works better with static views.

One OnClick handler for multiple buttons in a fragment

I have 3 buttons in a fragment that I want to use the same click event. How can this be achieved within a fragment?
XML
<Button
android:id="#+id/btn_1"
android:onClick="btnClick_DoSomething"
android:text="#string/one"/>
<Button
android:id="#+id/btn_2"
android:onClick="btnClick_DoSomething"
android:text="#string/two"/>
<Button
android:id="#+id/btn_3"
android:onClick="btnClick_DoSomething"
android:text="#string/three"/>
Java
#Override
public void btnClick_DoSomething(View v) {
}
Error
#Override (within the fragment Java class) becomes underlined in red and the following error is returned
Annontations are not allowed here
I want the onClick event to be the same for all 3 buttons
You dont need to write #Override annotation as you are not overriding the method. Just use
public void btnClick_DoSomething(View v) {
}
You will get a callback in this method at runtime.
you simply don't do it in XML, do it in Java instead:
<Button
android:id="#+id/btn_1"
android:text="#string/one"/>
<Button
android:id="#+id/btn_2"
android:text="#string/two"/>
<Button
android:id="#+id/btn_3"
android:text="#string/three"/>
then...
private final OnClickListener onClick = new OnClickListener(){
#Override
public void onClick(View view){
switch(view.getId()){
... cases...
}
}
somewhere initialising the views you do:
fragmentView.findViewById(R.id.btn_1).setOnClickListener(onClick);
fragmentView.findViewById(R.id.btn_2).setOnClickListener(onClick);
fragmentView.findViewById(R.id.btn_3).setOnClickListener(onClick);
}
What method are you trying to override? Do any of the parent classes have a method btnClick_DoSomething? You do not need to override anything when setting a click listener from a Layout XML. Just ensure that a method of the same name with a void return type and a View as its only argument exists in the activity class that will use this layout
The general way to distinguish clicks from different Views in the same onClick handler is to identify them by id
public void btnClick_DoSomething(View v){
switch(v.getId()){
case R.id.btn_1:
// handle click from button 1
break;
case R.id.btn_2:
// handle click from button 2
break;
case R.id.btn_3:
// handle click from button 3
break;
}
}
There are some misunderstandings here. To override a Click event, your Fragment need to implement the View.OnClickListener interface like this:
public class YourFragment extends Fragment implements View.OnClickListener{
#Override
public void onClick(View v) {
}
}
Note that the name of the method must be onCLick, must return void and recives a View as a parameter to be overrided from the interface. In this case you need to set a Listener to each button in your fragment:
btn1 = (Button) view.findViewById(R.id.btn_1);
btn1.setOnClickListener(this);
Inside this method you can control which object was clicked by it´s ID
#Override
public void onClick(View v) {
int id = v.getId();
switch(v.getId()){
case R.id.btn_1:
// handle click from button 1
break;
case R.id.btn_2:
// handle click from button 2
break;
case R.id.btn_3:
// handle click from button 3
break;
}
}
Or, you don't need to override the method, so remove the anotation that will work's fine :
public void btnClick_DoSomething(View v) {
switch(v.getId()){
case R.id.btn_1:
// handle click from button 1
break;
case R.id.btn_2:
// handle click from button 2
break;
case R.id.btn_3:
// handle click from button 3
break;
}
}
Instead of declaring the onClick method in the xml layout file, you could have your Fragment implement View.onClickListener interface, override onClick(), and set all 3 buttons onClickListener like this btn.setOnClickListener(this). Put the behavior you want for all 3 buttons in onClick(). All 3 will have the same behavior (unless you check which button the event came from in onClick()).

Trying to call a method from 1st class activity and keep the same argument in a 2nd class activity (android studio)

Currently finishing up an app I have been working on but I'm kinda stuck on this last thing.
The app has 2 activities, one with buttons that are categories and the other shows the information according to the button pressed. For example if you click the button Fast food, it goes to the 2nd screen and displays info on that.
I'm trying to get a refresh button on the 2nd activity that will call a method in the 1st activity to refresh new information depending on the button pressed. The problem is that I don't know how to make it so the method keeps the same argument when called. What I mean is, if fast food was clicked, the refresh button would get new info that still relates to the fast food category.
Here's the relevant code in the Main activity:
public void yelpSearch(View view) {
switch (view.getId()) {
case R.id.button: buttoncategory = "Restaurant";
break;
case R.id.button2: buttoncategory = "Chinese restaurant";
break;
case R.id.button3: buttoncategory = "Fast Food";
break;
and this on the 2nd Activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.refresh:
Refresh();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void Refresh() {
MainActivity mActivity = new MainActivity();
mActivity.yelpSearch();
}
I'm not sure what to put inside mActivity.yelpSearch();
I tried using (View view) but it'll say cannot resolve symbol view. And if I make a local variable for view, it'll say not initialized and I don't know what to set it as
Any help would be awesome, been googling on this for a while now and searched through tons of questions on here as well. I'm still new at this so bear with me
I think you want to pass data between activities?
First Activity(Send DATA):
String data="YourXXXdata"
Intent intent = new Intent(getBaseContext(), MainActivity.class);
intent.putExtra("DATANAME", data);
startActivity(intent)
second Activity(Receive DATA):
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("DATANAME");
}
The data now is in String value
*you have to put in data the value you need depend you preview select button.
Make your yelpSearch method static
and call it like this from 2nd activity MainActivity.yelpSearch();

How does one properly set an onclicklistener within another class?

I have an activity which does all the setup process, i.e. creating the initial view and the OnClickListener, which then at some point creates an object passing the activity and OnClickListener as parameters. The object then does it's own setup, changing to view and setting TableRows with the OnClickListener. I run into the issue that when ever I click on one of the Rows, it seems OnClick(View v) is not called. The code seems solid but I'm either missing something or my implementation simply wont work. Any help would be appreciated.
public class MyActivity extends Activity {
private Object mObject;
private TextView textView;
private OnClickListener mListener = new OnClickListener() {
public void onClick(View v) {
switch(v.getId()) {
case R.someId:
mObject = new Object(MyActivity.this, mListener);
break;
case R.id.table_row:
doSomething();
break;
}
}
}
textView = (TextView)findViewById(R.id.someId);
textView.setOnClickListener(mListener);
}
public class Object {
private Activity mActivity;
private OnClickListener mListener;
private TableRow tableRow;
public Object(Activity a, OnClickListener o) {
mActivity = a;
mListener = o;
mActivity.setContentView(R.layout.layout);
tableRow = (TableRow)findViewById(R.id.table_row);
tableRow.setOnClickListener(mListener)
}
}
Edited code as suggested:
public class MyActivity extends Activity implements OnClickListener{
private Object mObject;
private TextView textView;
#override
public void onClick(View v) {
switch(v.getId()) {
case R.someId:
mObject = new Object(MyActivity.this, mListener);
break;
case R.id.table_row:
doSomething();
break;
}
}
}
I omitted the Object class because with the above code onClick is not called without setting the OnClickListener with view.setOnClickListener(this); This also does not allow me to pass the Listener itself as a parameter, as far as I know.
at first glance, it appears that you aren't attaching that listener to anything in the first place... What element gets to call your listener the first time around? Your Object gets created when someone calls your Listener, but no one's calling it :)
Btw, you can implement onClickListener at the start of your Activity class creation, in which case, everything becomes clickable and you can then just listen for the id of what got clicked and react accordingly (rather than adding listeners, one at a time, to everything on the screen)... obviously this approach makes more sense when you have a bunch of clickable items (like a Battleship grid), rather than just a couple of buttons.
EDIT with example
public class MyGame extends Activity implements OnClickListener{
//... onCreate and all that jazz
//.. here you capture anything and everything getting clicked
public void onClick(View v){
switch (v.getId()){
case R.id.myClickableObj1:
//react to obj1 being clicked
break;
case R.id.myClickableObj2:
//etc. etc.
break;
}
}
}

Categories