如何从片段中的活动(而不是父)调用方法?

时间:2018-03-14 08:48:15

标签: android android-fragmentactivity method-call

我找到了这个 Call an activity method from a fragment  但它没有帮助。我得到了类型转换错误。碎片新手。请帮忙。

这是我的片段,我想在点击按钮时调用该方法

   public class Fragment1 extends Fragment {
    View view;
    public CardView stepEnableUi, enablewaterui, stepCountingUi, countingwaterUI;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate ( R.layout.fragment_fragment1, container, false );
        initialization ( );
        return view;
    }

    public void initialization() {
        final Button enablestep = view.findViewById ( R.id.stepsenable );
        final Button enablewater = view.findViewById ( R.id.waterenable );
        stepEnableUi = view.findViewById ( R.id.stepenableui );
        enablewaterui = view.findViewById ( R.id.waterenableui );
        stepCountingUi = view.findViewById ( R.id.stepcountingUI );
        countingwaterUI = view.findViewById ( R.id.watercountingUI );

        enablestep.setOnClickListener ( new View.OnClickListener ( ) {
            @Override
            public void onClick(View v) {
               ((StepCounter)getActivity ()).connectGoogle ( );
            }
        } );

这是我活动中的方法

public class StepCounter extends AppCompatActivity implements OnDataPointListener,
    GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {
private static final int REQUEST_OAUTH = 1;
private static final String AUTH_PENDING = "auth_state_pending";
private boolean authInProgress = false;
Button historyView;
private GoogleApiClient mApiClient;
TextView stepsonbar, steps, min, km, cal;
private ResultCallback<Status> mSubscribeResultCallback;
private ResultCallback<Status> mCancelSubscriptionResultCallback;
private ResultCallback<ListSubscriptionsResult> mListSubscriptionsResultCallback;
FragmentManager fm = getSupportFragmentManager();
FitChart fitChart;



  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView( R.layout.activity_step_counter);
        initialize();

    if (savedInstanceState != null) {
        authInProgress = savedInstanceState.getBoolean(AUTH_PENDING);
    }
    initCallbacks();

    mApiClient = new GoogleApiClient.Builder(this)
            .addApi(Fitness.SENSORS_API)
            .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ_WRITE))
            .addApi(Fitness.RECORDING_API)
            .addScope(new Scope(Scopes.FITNESS_ACTIVITY_READ))
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .enableAutoManage(this, 0, this)
            .build();

}
public void initialize(){
    steps=findViewById(R.id.steps);
    stepsonbar=findViewById(R.id.stepsonbar);
    min = findViewById(R.id.min);
    km = findViewById(R.id.km);
    cal = findViewById(R.id.cal);
    fitChart=findViewById ( R.id.fitchart );
    fitChart.setMinValue ( 0f );
    fitChart.setMaxValue ( 50000f );
    historyView=findViewById ( R.id.buttonweekdata );
    historyView.setOnClickListener ( new View.OnClickListener ( ) {
        @Override
        public void onClick(View v) {
            Intent i=new Intent ( StepCounter.this,HistoryWalking.class );
            startActivity ( i );
        }
    } );
}

@Override
protected void onStart() {
    super.onStart();
}

public void connectGoogle(){
    mApiClient.connect();
}
@Override
public void onActivityResult(int requestCode,int resultCode, Intent data) {
    if( requestCode == REQUEST_OAUTH ) {

        authInProgress = false;
        if( resultCode == RESULT_OK ) {

            if( !mApiClient.isConnecting() && !mApiClient.isConnected() ) {
                mApiClient.connect();
                Fragment1 fragment = (Fragment1) fm.findFragmentById(R.id.homescreen);
                fragment.showStepCounter();

            }
        } else if( resultCode == RESULT_CANCELED ) {
            Log.e( "GoogleFit", "RESULT_CANCELED" );
        }
    } else {
        Log.e("GoogleFit", "requestCode NOT request_oauth");
    }
}

这是我的logcat

03-14 13:45:49.259 29247-29247/com.satyajit.priceiq3 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                       Process: com.satyajit.priceiq3, PID: 29247
                                                                       java.lang.ClassCastException: com.satyajit.priceiq3.MainActivity cannot be cast to com.satyajit.priceiq3.Activities.StepCounter
                                                                           at com.satyajit.priceiq3.Fragments.Fragment1$1.onClick(Fragment1.java:46)
                                                                           at android.view.View.performClick(View.java:6303)
                                                                           at android.view.View$PerformClick.run(View.java:24828)
                                                                           at android.os.Handler.handleCallback(Handler.java:789)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:98)
                                                                           at android.os.Looper.loop(Looper.java:164)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:6809)
                                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                                           at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
03-14 13:45:49.261 29247-29247/com.satyajit.priceiq3 D/AppTracker: App Event: crash

2 个答案:

答案 0 :(得分:0)

  1. 首先,您需要在带有标记的Activity中提交片段。

    getSupportFragmentManager()
                .beginTransaction()   
                .replace(frame, fragment, "YOUR FRAGMENT NAME")
                .commit(); 
    
  2. 现在,您可以通过标记找到您的片段。

    Fragment fragment = getSupportFragmentManager().findFragmentByTag("YOUR FRAGMENT NAME");
    
  3. 投放片段

    if(fragment instanceof YourFragment) {
    
       YoutFragment yourFragment = (YoutFragment)fragment;
    
       yourFragemtn.yourMethod();
    
    }
    

答案 1 :(得分:0)

由于StepCounter类不是片段Fragment1的父Activity,请尝试以下

StepCounter mStepCounter=new StepCounter();
mStepCounter.connectGoogle();

确保正确初始化这些方法中的值