hozdaman hozdaman - 1 year ago 66
Android Question

Android Button Click issue

Hi I am having issues understanding why this doesn't work. I have a button and when you click on it it doesn't go to the new activity. I am trying to just have a simple button click that will go to another activity that has a fragment on top of it.

my code for the event click is as follows:

public class PlanMeMainFragment extends Fragment {

private Button mNewButton, mExistingButton;

mNewButton = (Button)v.findViewById(R.id.new_event_button);
mNewButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((PlanMeMainActivity) getActivity()).newActivityToLaunch(1);

return v;

my activity

public class PlanMeMainActivity extends FragmentActivity {

public void onCreate(Bundle savedInstanceState){

public void newActivityToLaunch(int i) {
Intent myIntent;
case 1: myIntent = new Intent(PlanMeMainActivity.this, NewEventSetupActivity.class);


I listed the manifest as such:

android:label="@string/app_name" >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />

Answer Source

Try something else, answer's @vdisawar gives me the idea:

in your Fragment:

// in your onClick method  
// call a method in your Activity 
((PlanMeMainActivity) getActivity()).newActivityToLaunch(); 

in your FragmentActivity:

// newActivityToLaunch method  
public void newActivityToLaunch() {
    Intent myIntent = new Intent(PlanMeMainActivity.this, NewEventSetupActivity.class);

With this tip, you will able to call different activities with the same method from different fragment, let see a simple example:

FragmentA wants to launch Activity1:

// call a method with an integer 
((MainActivity) getActivity()).newActivityToLaunch(1);  

in another fragment (FragmentB), this one wants to launch Activity2:

// call the same method with another integer 
((MainActivity) getActivity()).newActivityToLaunch(2);  

then in your FragmentActivity, the method is:

// newActivityToLaunch method  
public void newActivityToLaunch(int i) {
    // create a general intent
    Intent myIntent = null;
    // switch i received from fragments
    switch(i) {
        // received from FragmentA
        case 1: myIntent = new Intent(MainActivity.this, Activity1.class);
        // received from FragmentB
        case 2: myIntent = new Intent(MainActivity.this, Activity2.class);
    // start the activity

Hope this helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download