hozdaman hozdaman - 4 months ago 10
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() {
@Override
public void onClick(View v) {
((PlanMeMainActivity) getActivity()).newActivityToLaunch(1);

}
});
return v;
}
}


my activity

public class PlanMeMainActivity extends FragmentActivity {

@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.planme_main_fragment);
}

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

startActivity(myIntent);
}
}


I listed the manifest as such:

<activity
android:name="com.pctoolman.planme.app.PlanMeMainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.pctoolman.planme.app.NewEventSetupActivity"
android:label="@string/setup">
</activity>

Answer

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);
    startActivity(myIntent);
}  

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
    startActivity(myIntent);
}  

Hope this helps.

Comments