无法替换活动中的片段

时间:2016-04-25 05:05:28

标签: android android-fragments navigation-drawer buttonclick

我的活动包含NavigationDrawer。当按下导航抽屉中的项目时,我需要更改该活动中的Fragments。我在替换片段时出错。

活动

package in.yusoft.yuride.yuride;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class HomeActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

    DrawerLayout drawer_layout;
    ListView drawer_list;
    ActionBarDrawerToggle drawer_toggle;
    ActionBar abar;
    Myadapter myAdapter;
    android.support.v4.app.FragmentManager fm;
    android.support.v4.app.FragmentTransaction ft;
    Fragment def_frag,about_us,cancel_ride,fares,profile,ride_history,ride_updates,success,your_places;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        def_frag=new Success();
        fm=getSupportFragmentManager();
        ft=fm.beginTransaction();
        ft.replace(R.id.home_fragment, new CancelRide());
        ft.commitAllowingStateLoss();;
        myAdapter=new Myadapter(this);
        drawer_layout = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer_layout.addDrawerListener(drawer_toggle);
        drawer_list = (ListView) findViewById(R.id.drawer_list);
        drawer_list.setAdapter(myAdapter);

        //Swtting drawer width
        int width = getResources().getDisplayMetrics().widthPixels/2;
        DrawerLayout.LayoutParams params = (android.support.v4.widget.DrawerLayout.LayoutParams) drawer_list.getLayoutParams();
        params.width = width;
        drawer_list.setLayoutParams(params);

        drawer_list.setOnItemClickListener(this);
        abar = getSupportActionBar();
        drawer_toggle = new ActionBarDrawerToggle(this, drawer_layout, R.string.app_name, R.string.app_name) {
            //** Called when a drawer has settled in a completely closed state. *//*
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                getActionBar().setTitle("Drawer Opened");
                invalidateOptionsMenu();
            }
            //** Called when a drawer has settled in a completely open state. *//*
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                getActionBar().setTitle("Drawer Closed");
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };
        drawer_toggle.syncState();
        if (abar != null)
        {
            abar.setHomeButtonEnabled(true);
            abar.setDisplayHomeAsUpEnabled(true);
        }
    }
    @Override
    public boolean onOptionsItemSelected(android.view.MenuItem item) {
        return drawer_toggle.onOptionsItemSelected(item);
    }
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Object o = drawer_list.getItemAtPosition(position);
        Toast.makeText(HomeActivity.this, ""+o.toString(), Toast.LENGTH_SHORT).show();
        ft=fm.beginTransaction();
        switch (position)
        {
            case 0:
                ft.replace(R.id.home_fragment,new Profile()).addToBackStack(null).commit();
                break;
            case 1:
                ft.replace(R.id.home_fragment,new RideHistory()).addToBackStack(null).commit();
                break;
            case  3:
                ft.replace(R.id.home_fragment,new Fares()).addToBackStack(null).commit();
                break;
            case 4:
                ft.replace(R.id.home_fragment,new YourPlaces()).addToBackStack(null).commit();
                break;
            case 6:
                ft.replace(R.id.home_fragment,new CancelRide()).addToBackStack(null).commit();
                break;
            case 7:
                ft.replace(R.id.home_fragment,new RideUpdates()).addToBackStack(null).commit();
                break;
            case 8:
                ft.replace(R.id.home_fragment,new AboutUs()).addToBackStack(null).commit();
                break;
        }
    }

    class Myadapter extends BaseAdapter
    {
        Context context;
        String[] drawer_items;
        public Myadapter(Context context)
        {
            this.context=context;
            drawer_items=context.getResources().getStringArray(R.array.drawer_items);
        }
        @Override
        public int getCount() {
            return drawer_items.length;
        }

        @Override
        public Object getItem(int position) {
            return drawer_items[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View row=null;
            if(convertView==null)
            {
                LayoutInflater inflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                row=inflater.inflate(R.layout.drawer_row,parent,false);
            }
            else
            {
                row=convertView;
            }
            ImageView drawer_icon= (ImageView) row.findViewById(R.id.drawer_icon);
            TextView drawer_text= (TextView) row.findViewById(R.id.drawer_text);
            drawer_text.setText(drawer_items[position]);
            drawer_icon.setImageResource(R.drawable.tick);
            return row;
        }
    }
}

XML

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/drawer_layout">
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/home_fragment">
    </FrameLayout>
    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="left"
        android:id="@+id/drawer_list"
        android:background="@color/blue_normal">
    </ListView>
</android.support.v4.widget.DrawerLayout>

我在执行此操作时遇到了跟随错误

FATAL EXCEPTION: main
Process: in.yusoft.yuride.yuride, PID: 2813
java.lang.RuntimeException: in.yusoft.yuride.yuride.HomeActivity@f1cb3b3 must implement OnFragmentInteractionListener
at in.yusoft.yuride.yuride.Profile.onAttach(Profile.java:83)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1019)
at android.support.v4.app.BackStackRecord.ensureFragmentsAreInitialized(BackStackRecord.java:1081)
at android.support.v4.app.BackStackRecord.beginTransition(BackStackRecord.java:1036)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:662)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:6066)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:770)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:660)

3 个答案:

答案 0 :(得分:1)

您可以实施FragmentDrawer.FragmentDrawerListener来解决产生的错误....您也可以这样做......

 //when navigation item is selected by user
    @Override
    public void onDrawerItemSelected(View view, int position) {
        displayView(position);
    }

    public void displayView(int position) {
        String title = getString(R.string.app_name);
        switch (position) {
            case 0:
                fragment = new fragment1();                   
                break;
            case 1:
                fragment = new fragment2();

                break;
            case 2:
                fragment = new fragment3();

                break;
            case 3:
                //and so on....                
            default:
                break;
        }
        if (fragment != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container_body, fragment).addToBackStack("fragBack");
            fragmentTransaction.commit();

        }
    }

答案 1 :(得分:1)

请尝试

case 4:
yourIntent = new Intent(HomeActivity.this, NextActivity.class);
          startActivity(yourIntent);
                break; 

答案 2 :(得分:0)

如果您自动生成了片段代码,那么它有一个默认的回调接口OnFragmentInteractionListener,您需要在活动中实现数据共享或其他目的。

请为您的活动中的每个片段实施YourFragmentName.OnFragmentInteractionListener。 希望这会奏效!!