Reputation: 5
Just made a button with a click event that opens a link to a webpage, on this layout there are multiple buttons. Now I want to duplicate the event of the first button to use it for the others as well. But when I duplicate the code and replace the names to the other button I get some errors. What is the problem?;
public class FourthFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fourth_layout, container, false);
final Button button2 = (Button) view.findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://maurick.magister.net"));
startActivity(browserIntent);
}
});
return view;
final Button button3 = (Button) view.findViewById(R.id.button3);
//a red line is showing line above
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://maurickcollege.net"));
startActivity(browserIntent);
}
});
return view;
}
}
Upvotes: 0
Views: 255
Reputation: 3285
Rather than using new OnClickListener, Implement View.OnClickListener in your class, which will create one common method for all click events
where do like this..
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button_1:
case R.id.button_2:
//your common action goes here which will be executed for both buttons
}
}
Upvotes: 0
Reputation: 613
Your first return view
statements causes the method to return at this point.
So your code below this statement will not be executed. Your ide should show you the error message Unreachable statement
.
To your two listeners: create just one listener and set it to both views:
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://maurickcollege.net"));
startActivity(browserIntent);
}
}
view.findViewById(R.id.button2).setOnClickListener(listener);
view.findViewById(R.id.button3).setOnClickListener(listener);
Upvotes: 2
Reputation: 366
Two return view
statements.
That is making below code useless. That is the error
Upvotes: 0