Lets say I have a fragment MyFragment and I create myFragment1 and myFragment2. Both share the same xml layout which is just a image button. Using onClick, how can I make it so that clicking either button doesn't do the same thing?
For example, if I want myFragment1's button to go to Activity A, and I want myFragment2's button to go to Activity B.
Sample code below:
public class MyFragment extends Fragment implements View.OnClickListener{
ImageButton myButton;
View view;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_device, container, false);
myButton = (ImageButton) view.findViewById(R.id.myButton);
myButton.setOnClickListener(this);
return view;
}
@Override
public void onClick(View v){
//do something
}
}
From my MainActivity
:
public class MainActivity extends AppCompatActivity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
LinearLayout windowForMainActivity = (LinearLayout) findViewById(R.id.windowForMainActivity);
MyFragment myFragment1 = new MyFragment();
fragmentTransaction.add(windowForMainActivity.getId(),myFragment1);
MyFragment myFragment2 = new MyFragment();
fragmentTransaction.add(windowForMainActivity.getId(),myFragment2);
fragmentTransaction.commit();
}
}