在活动上显示不同的片段?

时间:2018-03-29 21:05:56

标签: android android-fragments

问题:当我按下显示片段上的按钮时,如何使活动更改片段?

我有一个活动(HomeActivity),里面是以下代码:

public class HomeActivity extends AppCompatActivity
    implements WelcomeFragment.OnFragmentInteractionListener{

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

    WelcomeFragment welcomeFragment = new WelcomeFragment();
    Bundle myBundle = getIntent().getExtras();
    welcomeFragment.signedUsername = myBundle.getString("username");

    this.pushFragment(welcomeFragment, false);
}

void pushFragment(Fragment newFragment, boolean addToStack) {
    // Create a FragmentTransaction from FragmentManager via activity
    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction transaction = manager.beginTransaction();
    // Replace whatever is in the fragment_container view with this fragment
    transaction.replace(R.id.loginFragmentContainer, newFragment);
    if (addToStack) {
        // Add the transaction to the back stack
        transaction.addToBackStack(null);
    }
    //Commit the transaction
    transaction.commit();
}

@Override
public void onFragmentInteraction(Uri uri) {

}

}

在欢迎片段上,我有4个按钮。我希望每个按钮都带我到一个不同的片段进行数据计算。任何有关如何实现这一目标的提示将不胜感激。

WelcomeFragment代码:

public class WelcomeFragment extends 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;

String signedUsername;
TextView textWelcome;

private OnFragmentInteractionListener mListener;

public WelcomeFragment() {
    // 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 WelcomeFragment.
 */
// TODO: Rename and change types and number of parameters
public static WelcomeFragment newInstance(String param1, String param2) {
    WelcomeFragment fragment = new WelcomeFragment();
    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) {
    // Inflate the layout for this fragment
    View view =  inflater.inflate(R.layout.fragment_welcome, container, false);

    textWelcome = view.findViewById(R.id.textWelcomeMessage);
    textWelcome.setText("Welcome " + signedUsername + "!");

    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(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

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

public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    void onFragmentInteraction(Uri uri);
}

}

2 个答案:

答案 0 :(得分:1)

除了糟糕的用户体验之外,这个问题的答案只需与您的Activity进行沟通即可。

有几种方法可以做到这一点,例如使用event bus,RxJava或传统的回调。

回调看起来如下:

将界面放入Fragment

interface ChangeFragmentCallback {
    void changeFragment(int which);
}

让你的Fragment使用构造函数或setter方法接受回调。我们将使用构造函数:

Fragment(ChangeFragmentCallback callback) {
    this.callback = callback;
}

Activity中,无论何时实例化此片段,都要传递回调:

new Fragment(new Fragment.ChangeFragmentCallback() {
    @Override                                                           
    public void changeFragment(int which) {
        // Put code to change the fragment here.                                                                                      
    }                                                                   
});

然后,只要您想告诉Activity Fragment应该更改(例如点击某个按钮时),只需致电callback.changeFragment()

你也可以使用ViewPager来保存所有Fragment,然后告诉适配器ViewPager交换页面。

最后,所有Fragment都有getActivity()方法。您可以调用此方法并将返回值强制转换为Activity,然后调用您喜欢的任何方法:

((HomeActivity)getActivity()).pushFragment();

答案 1 :(得分:0)

创建像ParentActivityForFragment这样的另一个活动,而不是使用Bundle / Intent调用From Home Activity,其中包含需要像屏幕和所需的任何其他数据一样膨胀的数据。既然你有活动处理片段膨胀,你现在可以控制父对片段或活动的作用。