gpt4 book ai didi

java - 如何实现 OnFragmentInteractionListener?

转载 作者:行者123 更新时间:2023-11-29 09:53:07 25 4
gpt4 key购买 nike

我已经查看了与此相关的其他问题,但我仍然不确定如何使用我正在做的事情来实现 OnFragmentInteractionListener。我正在登录 facebook,我想在我的主要 Activity 中实现 OnFragmentInteractionListener,但我不知道该怎么做,我需要帮助。这是 MainActivity:

package com.eren.valour;


import android.app.ActionBar;
import android.content.Context;
import android.net.Uri;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuItem;
import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.Toast;

import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;

import static com.eren.valour.R.id.*;

public class MainScreen extends ActionBarActivity {
private static final int FBSPLASH = 0;
private static final int FBSELECTION = 1;
private static final int FBFRAGMENT_COUNT = FBSELECTION + 1;
private Fragment[] fragments = new Fragment[FBFRAGMENT_COUNT];
ImageButton fblogin;
Session session = Session.getActiveSession();
private boolean isResumed = false;
private UiLifecycleHelper uiHelper;
private Session.StatusCallback callback =
new Session.StatusCallback() {
@Override
public void call(Session session,
SessionState state, Exception exception) {
onSessionStateChange(session, state, exception);
}
};


public void onFragmentInteraction(Uri uri) {

}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayShowCustomEnabled(true);
setTitle("Valour");
setContentView(R.layout.activity_main_screen);

uiHelper = new UiLifecycleHelper(this, callback);
uiHelper.onCreate(savedInstanceState);
FragmentManager fm = getSupportFragmentManager();
fragments[FBSPLASH] = fm.findFragmentById(R.id.splashFragment);
fragments[FBSELECTION] = fm.findFragmentById(R.id.selectionFragment);

FragmentTransaction transaction = fm.beginTransaction();
for (int i = 0; i < fragments.length; i++) {
transaction.hide(fragments[i]);
}
transaction.commit();
getScreenRes();
}

public void getScreenRes() {
DisplayMetrics display = this.getResources().getDisplayMetrics();
int screenwidth = display.widthPixels;
double buttonheight = screenwidth / 2.66666667;
int screenheight = (int) Math.round(buttonheight);

// ImageButton serviceList = (ImageButton) findViewById(R.id.addservice);
// ViewGroup.LayoutParams servicelist = serviceList.getLayoutParams();
// servicelist.width = screenwidth;
// servicelist.height = screenheight;


//Get screen dimensions and define button variables
ImageButton redditLogin = (ImageButton) findViewById(R.id.redditLogin);
ViewGroup.LayoutParams reddit = redditLogin.getLayoutParams();
reddit.width = screenwidth;
reddit.height = screenheight;

ImageButton fbLogin = (ImageButton) findViewById(R.id.facebookLogin);
ViewGroup.LayoutParams fb = fbLogin.getLayoutParams();
fb.width = screenwidth;
fb.height = screenheight;


ImageButton instaLogin = (ImageButton) findViewById(R.id.instagramLogin);
ViewGroup.LayoutParams insta = instaLogin.getLayoutParams();
insta.width = screenwidth;
insta.height = screenheight;

ImageButton twitLogin = (ImageButton) findViewById(R.id.twitterLogin);
ViewGroup.LayoutParams twit = twitLogin.getLayoutParams();
twit.width = screenwidth;
twit.height = screenheight;

// set button size
instaLogin.setLayoutParams(insta);
fbLogin.setLayoutParams(fb);
twitLogin.setLayoutParams(twit);
redditLogin.setLayoutParams(reddit);
}

public void facebookLogin(View v) {

if (session == null) {
session = new Session(getApplicationContext());
}
Session.setActiveSession(session);


}

public void instagramLogin(View v) {
serviceIncomplete();


}

public void redditLogin(View v) {
serviceIncomplete();


}

public void twitterLogin(View v) {
serviceIncomplete();


}

private void showFragment(int fragmentIndex, boolean addToBackStack) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction transaction = fm.beginTransaction();
for (int i = 0; i < fragments.length; i++) {
if (i == fragmentIndex) {
transaction.show(fragments[i]);
} else {
transaction.hide(fragments[i]);
}
}
if (addToBackStack) {
transaction.addToBackStack(null);
}
transaction.commit();
}

private void onSessionStateChange(Session session, SessionState state, Exception exception) {
// Only make changes if the activity is visible
if (isResumed) {
FragmentManager manager = getSupportFragmentManager();
// Get the number of entries in the back stack
int backStackSize = manager.getBackStackEntryCount();
// Clear the back stack
for (int i = 0; i < backStackSize; i++) {
manager.popBackStack();
}
if (state.isOpened()) {
// If the session state is open:
// Show the authenticated fragment
showFragment(FBSELECTION, false);
} else if (state.isClosed()) {
// If the session state is closed:
// Show the login fragment
showFragment(FBSPLASH, false);
}
}
}

@Override
protected void onResumeFragments() {
super.onResumeFragments();
Session session = Session.getActiveSession();

if (session != null && session.isOpened()) {
// if the session is already open,
// try to show the selection fragment
showFragment(FBSELECTION, false);
} else {
// otherwise present the splash screen
// and ask the person to login.
showFragment(FBSPLASH, false);
}
}

//show toast if service is not finished.
public void serviceIncomplete() {
Context context = getApplicationContext();
CharSequence text = "Coming Soon!";
int duration = Toast.LENGTH_LONG;

Toast toast = Toast.makeText(context, text, duration);
toast.show();
}

public void firstTime() {
startActivity(new Intent(getApplicationContext(), FirstTimeLogin.class));
}


@Override
public void onResume() {
super.onResume();
uiHelper.onResume();
isResumed = true;
}

@Override
public void onPause() {
super.onPause();
uiHelper.onPause();
isResumed = false;
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
uiHelper.onActivityResult(requestCode, resultCode, data);
}

@Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}

@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
uiHelper.onSaveInstanceState(outState);
}

}

这是 fragment :

package com.eren.valour;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link FacebookLoginDialogueFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link FacebookLoginDialogueFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class FacebookLoginDialogueFragment extends android.support.v4.app.Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

public FacebookLoginDialogueFragment() {
// Required empty public constructor
}

/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment FacebookLoginDialogueFragment.
*/
// TODO: Rename and change types and number of parameters
public static FacebookLoginDialogueFragment newInstance(String param1, String param2) {
FacebookLoginDialogueFragment fragment = new FacebookLoginDialogueFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}

@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_facebook_login_dialogue,
container, false);
return view;
}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}

@Override
public void onDetach() {
super.onDetach();
mListener = null;
}

/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}

}

我遇到了这个错误

03-27 03:45:57.880    2139-2139/com.eren.valour E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.eren.valour, PID: 2139
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.eren.valour/com.eren.valour.MainScreen}: android.view.InflateException: Binary XML file line #20: Error inflating class fragment
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: android.view.InflateException: Binary XML file line #20: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
at android.support.v7.app.ActionBarActivityDelegateBase.setContentView(ActionBarActivityDelegateBase.java:228)
at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:102)
at com.eren.valour.MainScreen.onCreate(MainScreen.java:55)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.ClassCastException: com.eren.valour.MainScreen@7e027fd must implement OnFragmentInteractionListener
at com.eren.valour.FacebookLoginDialogueFragment.onAttach(FacebookLoginDialogueFragment.java:85)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:903)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1206)
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2159)
at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:297)
at android.support.v7.app.ActionBarActivity.onCreateView(ActionBarActivity.java:547)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:727)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
            at android.support.v7.app.ActionBarActivityDelegateBase.setContentView(ActionBarActivityDelegateBase.java:228)
            at android.support.v7.app.ActionBarActivity.setContentView(ActionBarActivity.java:102)
            at com.eren.valour.MainScreen.onCreate(MainScreen.java:55)
            at android.app.Activity.performCreate(Activity.java:5933)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

最佳答案

重写方法 onAttach(Activity activity) 现在已在 android.app.Fragment 中弃用,代码应升级为 onAttach(Context context)

这意味着您无需实现此监听器,只需使用以下内容即可:

代替:

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}

使用

@Override
public void onAttach(Context context) {
super.onAttach(context);
}

关于java - 如何实现 OnFragmentInteractionListener?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29292942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com