试图与另一个替换一个片段 [英] Trying to replace one fragment with another

查看:125
本文介绍了试图与另一个替换一个片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以onItemClick方法来替换另一个片段。
这就是我想:

 公共无效onItemClick(适配器视图<>母公司,观景,INT位置,长的id){        TipoRestaurante rteActual =(TipoRestaurante)adapter.getItem(位置);
        弦乐味精=有elegido EL TIPO+ rteActual.getNombre_tipo();
        Toast.makeText(getActivity(),味精,Toast.LENGTH_LONG).show();        片段newFragment =新TabFragmentComer();
        FragmentTransaction交易= getFragmentManager()调用BeginTransaction()。
        transaction.replace(R.id.containerView,newFragment);
        transaction.addToBackStack(NULL);
        器transaction.commit();
    }

不过,我得到一个例外:

  09-28 23:51:02.310 14895-14895 / com.solinpromex.elpasojuarezexperience E / AndroidRuntime:致命异常:主要
    工艺:com.solinpromex.elpasojuarezexperience,PID:14895
    java.lang.IllegalArgumentException异常:(:ID / containerView com.solinpromex.elpasojuarezexperience)的片段TabFragmentComer {42909b40#1 ID = 0x7f0d009b}未找到ID 0x7f0d009b视图
            在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
            在android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
            在android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
            在android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
            在android.support.v4.app.FragmentManagerImpl $ 1.run(FragmentManager.java:458)
            在android.os.Handler.handleCallback(Handler.java:808)
            在android.os.Handler.dispatchMessage(Handler.java:103)
            在android.os.Looper.loop(Looper.java:193)
            在android.app.ActivityThread.main(ActivityThread.java:5299)
            在java.lang.reflect.Method.invokeNative(本机方法)
            在java.lang.reflect.Method.invoke(Method.java:515)
            在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:825)
            在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
            在dalvik.system.NativeStart.main(本机方法)

我抵达的当前片段从活动中,像这样的:

 如果(menu​​Item.getItemId()== R.id.nav_item_comer){
                     FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
                     。xfragmentTransaction.replace(R.id.containerView,新TabFragmentComerTiposRestaurante())提交();
                 }

任何帮助是值得欢迎的。

编辑:MainActivity XML布局:

 <的LinearLayout
    的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    的xmlns:程序=htt​​p://schemas.android.com/apk/res-auto
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    机器人:fitsSystemWindows =真
    机器人:方向=垂直>    < android.support.v7.widget.Toolbar
        的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
        机器人:layout_width =match_parent
        机器人:layout_height =WRAP_CONTENT
        机器人:背景=@彩色/ rojomodesto
        机器人:ID =@ + ID /工具栏
        机器人:主题=@风格/ ThemeOverlay.AppCompat.Dark.ActionBar
        应用:标题=埃尔帕索 - 华雷斯体验/>    < android.support.v4.widget.DrawerLayout
        的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
        的xmlns:程序=htt​​p://schemas.android.com/apk/res-auto
        机器人:layout_height =match_parent
        机器人:layout_width =match_parent
        机器人:ID =@ + ID / drawerLayout
        >    <的FrameLayout
        机器人:方向=垂直
        机器人:layout_width =match_parent
        机器人:layout_height =match_parent
        机器人:ID =@ + ID / containerView>
     < /&的FrameLayout GT;    < android.support.design.widget.NavigationView
        的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
        的xmlns:程序=htt​​p://schemas.android.com/apk/res-auto
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =match_parent
        机器人:layout_gravity =开始
        机器人:ID =@ + ID / shitstuff
        应用:itemTextColor =@彩色/黑白
        应用:菜单=@菜单/ drawermenu
        机器人:layout_marginTop = - 24dp
        />    < /android.support.v4.widget.DrawerLayout>    < / LinearLayout中>


解决方案

您片断应该有它的界面如下:

 公共类MyFragment扩展片段{    私人OnFragmentInteractionListener mListener;    公共MyFragment(){
    }
    @覆盖
    公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,
                             捆绑savedInstanceState){
        查看查看= ...;
        返回视图。
    }    公共无效onItemClick(适配器视图<>母公司,观景,INT位置,长的id){        TipoRestaurante rteActual =(TipoRestaurante)adapter.getItem(位置);
        弦乐味精=有elegido EL TIPO+ rteActual.getNombre_tipo();
        Toast.makeText(getActivity(),味精,Toast.LENGTH_LONG).show();        片段newFragment =新TabFragmentComer();        如果(mListener!= NULL){
            mListener.onFragmentInteraction(newFragment);
        }
    }    @覆盖
    公共无效onAttach(活动活动){
        super.onAttach(活动);
        尝试{
            mListener =(OnFragmentInteractionListener)活性;
        }赶上(抛出ClassCastException E){
            抛出新ClassCastException异常(activity.toString()
                    +必须实现OnFragmentInteractionListener);
        }
    }    @覆盖
    公共无效onDetach(){
        super.onDetach();
        mListener = NULL;
    }    公共接口OnFragmentInteractionListener {
        公共无效onFragmentInteraction(片段片段);
    }}

您活动应该实现该接口:

  MyActivity延伸活动实现OnFragmentInteractionListener {
//你的活动方法...@覆盖
    公共无效onFragmentInteraction(片段片段){
         //在这里有一个片段,可以用交易改变
         FragmentTransaction交易= getFragmentManager()调用BeginTransaction()。        transaction.replace(R.id.containerView,片段);
        transaction.addToBackStack(NULL);
        器transaction.commit();
    }
}


要传递对象另一个片段:

如果该片段只是你在上面创建为newFragment您可以添加参数传递给它如下片段:

 片段newFragment =新TabFragmentComer();
捆绑ARGS =新包();
args.putInt(myIntLabel,2);
args.putString(myStringLabel,我的样本字符串);
//你可以你想要添加到包这样的
newFragment.setArguments(参数);

然后在你的片段onCreateView或onCreate方法,你可以得到这个包是这样的:

  ...
捆绑ARGS = getArguments();
INT敏= args.getInt(myIntLabel(INT设置defaultValue)); //返回2
INT的myString = args.getString(myStringLabel(字符串defaultString)); //返回我的样本字符串

如果你没有在这个片段创建的片段,你可以添加其他参数,该接口的方法捆绑ARGS 和捆绑包添加到您创建像你的片段这样的: fragment.setArguments(参数)

I need to replace a fragment with another at an onItemClick method. This is what I am trying:

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        TipoRestaurante rteActual = (TipoRestaurante) adapter.getItem(position);
        String msg = "Has elegido el tipo " + rteActual.getNombre_tipo();
        Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();

        Fragment newFragment = new TabFragmentComer();
        FragmentTransaction transaction = getFragmentManager().beginTransaction();


        transaction.replace(R.id.containerView, newFragment);
        transaction.addToBackStack(null);


        transaction.commit();


    }

But I am getting an exception:

09-28 23:51:02.310  14895-14895/com.solinpromex.elpasojuarezexperience E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.solinpromex.elpasojuarezexperience, PID: 14895
    java.lang.IllegalArgumentException: No view found for id 0x7f0d009b (com.solinpromex.elpasojuarezexperience:id/containerView) for fragment TabFragmentComer{42909b40 #1 id=0x7f0d009b}
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
            at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
            at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
            at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
            at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:458)
            at android.os.Handler.handleCallback(Handler.java:808)
            at android.os.Handler.dispatchMessage(Handler.java:103)
            at android.os.Looper.loop(Looper.java:193)
            at android.app.ActivityThread.main(ActivityThread.java:5299)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
            at dalvik.system.NativeStart.main(Native Method)

I am arriving to the current fragment from an activity, like this:

if (menuItem.getItemId() == R.id.nav_item_comer) {
                     FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
                     xfragmentTransaction.replace(R.id.containerView,new TabFragmentComerTiposRestaurante()).commit();
                 }

Any help is welcome

EDIT: MainActivity xml layout:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:orientation="vertical">

    <android.support.v7.widget.Toolbar
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/rojomodesto"
        android:id="@+id/toolbar"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:title="El Paso - Juárez Experience" />

    <android.support.v4.widget.DrawerLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:id="@+id/drawerLayout"
        >



    <FrameLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/containerView">
     </FrameLayout>



    <android.support.design.widget.NavigationView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:id="@+id/shitstuff"
        app:itemTextColor="@color/black"
        app:menu="@menu/drawermenu"
        android:layout_marginTop="-24dp"
        />



    </android.support.v4.widget.DrawerLayout>

    </LinearLayout>

解决方案

Your fragment should have an interface in it as follows:

public class MyFragment extends Fragment {

    private OnFragmentInteractionListener mListener;

    public MyFragment() {
    }


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

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        TipoRestaurante rteActual = (TipoRestaurante) adapter.getItem(position);
        String msg = "Has elegido el tipo " + rteActual.getNombre_tipo();
        Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();

        Fragment newFragment = new TabFragmentComer();    

        if(mListener != null){
            mListener.onFragmentInteraction(newFragment);
        }


    }

    @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;
    }

    public interface OnFragmentInteractionListener {
        public void onFragmentInteraction(Fragment fragment);
    }

}

Your activity should implement that interface:

MyActivity extends Activity implements OnFragmentInteractionListener{
//your activity methods...

@Override
    public void onFragmentInteraction(Fragment fragment) {
         //here you have that fragment and can change it with transactions
         FragmentTransaction transaction = getFragmentManager().beginTransaction();

        transaction.replace(R.id.containerView, fragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }
}


To pass objects to the other fragment:

If the fragment is just the fragment you are creating above as newFragment you can add arguments to it as follows:

Fragment newFragment = new TabFragmentComer();
Bundle args = new Bundle();
args.putInt("myIntLabel", 2);
args.putString("myStringLabel", "my sample string");
//and you can add all you want to that bundle like this
newFragment.setArguments(args);

Then in your fragment onCreateView or onCreate method you can get that bundle like this:

...
Bundle args = getArguments();
int myInt = args.getInt("myIntLabel", (int defaultValue)); // returns 2
int myString  = args.getString("myStringLabel", (String defaultString)); // returns "my sample string"

And if you are not creating your fragment in this fragment you can add another argument to that interface method as Bundle args and add that bundle to your fragment where you create like this: fragment.setArguments(args)

这篇关于试图与另一个替换一个片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆