在扩充类Fragment

时间:2017-03-09 21:09:42

标签: java android android-fragments

我有错误,我不知道如何解决 我需要添加一个片段,但它不会起作用 一切都发生在void firstTime(),错误显示它就在setContentView(R.layout.activity_main);上。

我真的不知道如何解决这个问题 我尝试了很多东西,但它不起作用。

请帮助我。

MainActivity类:

    public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private MapFragment mapsFragment;
    static MainActivity can;
    static FloatingActionButton fab;
    static FloatingActionButton show;
    private String encoded_string;
    private Bitmap bitmap;
    private String picturePath;
    View rootView;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    private void initializeMapsFragment() {
        FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction();
        mapsFragment = new MapFragment();
        SupportMapFragment supportMapFragment = mapsFragment;
        mTransaction.add(R.id.map, supportMapFragment);
        mTransaction.commitNow();
    }

    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        can = this;
        Log.d("--***** MAP  ", "::Loading Map");
        setContentView(R.layout.activity_main);
        initializeMapsFragment();
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        fab = (FloatingActionButton) findViewById(R.id.fab);
        show = (FloatingActionButton) findViewById(R.id.show);
        show.hide();
        fab.hide();
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                callPopup();

            }
        });

        show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                stats();

            }
        });
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                can, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();


        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(can);

        Button searchButton = (Button) findViewById(R.id.searchButton);

        searchButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                EditText searchView = (EditText) findViewById(R.id.searchView1);
                String text = searchView.getText().toString();

                Geocoder geocoder = new Geocoder(getBaseContext());
                List<Address> addresses = null;

                try {
                    // Getting a maximum of 3 Address that matches the input
                    // text
                    addresses = geocoder.getFromLocationName(text, 3);
                    if (addresses != null && !addresses.equals(""))
                        search(addresses);

                } catch (Exception e) {

                }

            }
        });

        client = new GoogleApiClient.Builder(can).addApi(AppIndex.API).build();
    }


    public void start(){
        setContentView(R.layout.activity_main);
        initializeMapsFragment();
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        fab = (FloatingActionButton) findViewById(R.id.fab);
        show = (FloatingActionButton) findViewById(R.id.show);
        show.hide();
        fab.hide();
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                callPopup();

            }
        });

        show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                stats();

            }
        });
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);

        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                can, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();


        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(can);


        Button searchButton = (Button) findViewById(R.id.searchButton);

        searchButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                EditText searchView = (EditText) findViewById(R.id.searchView1);
                String text = searchView.getText().toString();

                Geocoder geocoder = new Geocoder(getBaseContext());
                List<Address> addresses = null;

                try {
                    // Getting a maximum of 3 Address that matches the input
                    // text
                    addresses = geocoder.getFromLocationName(text, 3);
                    if (addresses != null && !addresses.equals(""))
                        search(addresses);

                } catch (Exception e) {

                }

            }
        });

        client = new GoogleApiClient.Builder(can).addApi(AppIndex.API).build();

    }

    protected void search(List<Address> addresses) {

        Address address = (Address) addresses.get(0);
        LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());

        MapFragment.mapView.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        MapFragment.mapView.animateCamera(CameraUpdateFactory.zoomTo(15));


    }

    @RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @RequiresApi(api = Build.VERSION_CODES.HONEYCOMB)
    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        FragmentManager fm = getFragmentManager();
        android.support.v4.app.FragmentManager sFm = getSupportFragmentManager();

        int id = item.getItemId();


        if (id == R.id.nav_camera) {

            if (!mapsFragment.isAdded())
                sFm.beginTransaction().add(R.id.map, mapsFragment).commit();
            else
                sFm.beginTransaction().show(mapsFragment).commit();
        } else if (id == R.id.nav_share) {

            Intent sharingIntent = new Intent(Intent.ACTION_SEND);
            sharingIntent.setType("text/plain");
            String shareBody = "Check this app out --> link.kys";
            sharingIntent.putExtra(Intent.EXTRA_SUBJECT, "Best Free Parking app");
            sharingIntent.putExtra(Intent.EXTRA_TEXT, shareBody);
            startActivity(Intent.createChooser(sharingIntent, "Share via"));

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public void firstTime() {


        setContentView(R.layout.firsttime);

        (findViewById(R.id.cancelBut))
                .setOnClickListener(new View.OnClickListener() {

                    public void onClick(View arg0) {

                        //View view = can.findViewById(android.R.id.content);
                        //Log.d("a", "" + ((ViewGroup)view).getChildCount() );
                        //((ViewGroup) view).removeView(view);
                        android.support.v4.app.FragmentManager sFm = getSupportFragmentManager();
                        sFm.beginTransaction().remove(mapsFragment).commitNow();
                        if(mapsFragment.isAdded()){

                            Log.d("--***** FRAGMENT  ", "::Still On");

                        }
                        start();
                    }

                });


    }
    public static void load(){

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(can);
        if (!prefs.getBoolean("firstTime", false)) {

            can.firstTime();

            //SharedPreferences.Editor editor = prefs.edit();
            //editor.putBoolean("firstTime", true);
            //editor.commit();
        }

    }

    private void stats() {

        setContentView(R.layout.stats);



        RatingBar ratingbar = (RatingBar) findViewById(R.id.ratingBar);
        ratingbar.setRating((float) 2.0);
        ratingbar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            public void onRatingChanged(RatingBar ratingBar, float rating,
                                        boolean fromUser) {

                ratingBar.setRating((float) 2.0);

            }
        });


        ((Button) findViewById(R.id.cancBut)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setContentView(R.layout.content_main);
            }
        });
    }

}

Xml文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.robertas.parking.bestfreeparking.MainActivity"
    tools:showIn="@layout/app_bar_main">

    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.robertas.parking.test.MapsActivity"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_weight="0.68" />

    <EditText
        android:id="@+id/searchView1"
        android:inputType="textPersonName"
        android:layout_width="250dp"
        android:layout_height="34dp"
        android:layout_marginTop="14dp"
        android:hint="Search Location"
        android:ems="10"
        android:textColor="@android:color/black"
        android:background="@android:color/white"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true">
    </EditText>

    <Button
        android:id="@+id/searchButton"
        android:layout_width="wrap_content"
        android:layout_height="25dp"
        android:background="@drawable/places_ic_search"
        android:layout_alignBottom="@+id/searchView1"
        android:layout_alignRight="@+id/searchView1"
        android:layout_alignEnd="@+id/searchView1"
        android:layout_alignTop="@+id/searchView1"
        android:layout_marginLeft="216dp"
        android:layout_marginStart="216dp"
        android:layout_alignLeft="@+id/searchView1"
        android:layout_alignStart="@+id/searchView1" />

</RelativeLayout>

错误:

android.view.InflateException: Binary XML file line #12: Error inflating class fragment

日志:

03-10 20:21:45.036 31937-31937/com.robertas.parking.bestfreeparking D/AndroidRuntime: Shutting down VM
03-10 20:21:45.036 31937-31937/com.robertas.parking.bestfreeparking E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                      Process: com.robertas.parking.bestfreeparking, PID: 31937
                                                                                      android.view.InflateException: Binary XML file line #12: Error inflating class fragment
                                                                                          at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
                                                                                          at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
                                                                                          at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
                                                                                          at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
                                                                                          at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
                                                                                          at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
                                                                                          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.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284)
                                                                                          at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:143)
                                                                                          at com.robertas.parking.bestfreeparking.MainActivity.start(MainActivity.java:161)
                                                                                          at com.robertas.parking.bestfreeparking.MainActivity$8.onClick(MainActivity.java:356)
                                                                                          at android.view.View.performClick(View.java:4780)
                                                                                          at android.view.View$PerformClick.run(View.java:19866)
                                                                                          at android.os.Handler.handleCallback(Handler.java:739)
                                                                                          at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                          at android.os.Looper.loop(Looper.java:135)
                                                                                          at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                                          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:903)
                                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
                                                                                       Caused by: java.lang.IllegalArgumentException: Binary XML file line #12: Duplicate id 0x7f0f00e8, tag null, or parent id 0x7f0f00e7 with another fragment for com.google.android.gms.maps.SupportMapFragment
                                                                                          at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2427)
                                                                                          at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:120)
                                                                                          at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:378)
                                                                                          at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:33)
                                                                                          at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:77)
                                                                                          at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733)
                                                                                          at android.view.LayoutInflater.rInflate(LayoutInflater.java:806) 
                                                                                          at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916) 
                                                                                          at android.view.LayoutInflater.rInflate(LayoutInflater.java:802) 
                                                                                          at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916) 
                                                                                          at android.view.LayoutInflater.rInflate(LayoutInflater.java:802) 
                                                                                          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.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:284) 
                                                                                          at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:143) 
                                                                                          at com.robertas.parking.bestfreeparking.MainActivity.start(MainActivity.java:161) 
                                                                                          at com.robertas.parking.bestfreeparking.MainActivity$8.onClick(MainActivity.java:356) 
                                                                                          at android.view.View.performClick(View.java:4780) 
                                                                                          at android.view.View$PerformClick.run(View.java:19866) 
                                                                                          at android.os.Handler.handleCallback(Handler.java:739) 
                                                                                          at android.os.Handler.dispatchMessage(Handler.java:95) 
                                                                                          at android.os.Looper.loop(Looper.java:135) 
                                                                                          at android.app.ActivityThread.main(ActivityThread.java:5254) 
                                                                                          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:903) 
                                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698) 
03-10 20:21:45.039 1499-1878/system_process W/ActivityManager:   Force finishing activity 1 com.robertas.parking.bestfreeparking/.MainActivity

                                                               [ 03-10 20:21:45.046  1499: 1878 D/         ]
                                                               HostConnection::get() New Host Connection established 0x7ffc98084ec0, tid 1878
03-10 20:21:45.051 1123-1123/? E/EGL_emulation: tid 1123: eglCreateSyncKHR(1299): error 0x3004 (EGL_BAD_ATTRIBUTE)
03-10 20:21:45.152 1499-1558/system_process I/OpenGLRenderer: Initialized EGL, version 1.4
03-10 20:21:45.194 1499-1558/system_process W/EGL_emulation: eglSurfaceAttrib not implemented
03-10 20:21:45.194 1499-1558/system_process W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x7ffca953fb40, error=EGL_SUCCESS
03-10 20:21:45.612 1499-1518/system_process W/ActivityManager: Activity pause timeout for ActivityRecord{38e88b4d u0 com.robertas.parking.bestfreeparking/.MainActivity t155 f}
03-10 20:21:45.645 1756-2040/com.google.android.googlequicksearchbox W/EGL_emulation: eglSurfaceAttrib not implemented
03-10 20:21:45.645 1756-2040/com.google.android.googlequicksearchbox W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xe1c93620, error=EGL_SUCCESS
03-10 20:21:46.616 1622-1622/com.android.systemui W/ResourceType: No package identifier when getting value for resource number 0x00000000
03-10 20:21:46.616 1622-1622/com.android.systemui W/PackageManager: Failure retrieving resources for com.robertas.parking.bestfreeparking: Resource ID #0x0
03-10 20:21:46.832 1756-1756/com.google.android.googlequicksearchbox I/Choreographer: Skipped 69 frames!  The application may be doing too much work on its main thread.
03-10 20:21:47.332 1756-2040/com.google.android.googlequicksearchbox W/OpenGLRenderer: Incorrectly called buildLayer on View: aep, destroying layer...
03-10 20:21:47.448 1499-1577/system_process W/AudioTrack: AUDIO_OUTPUT_FLAG_FAST denied by client
03-10 20:21:47.465 31937-31937/? I/Process: Sending signal. PID: 31937 SIG: 9
03-10 20:21:47.474 1499-14634/system_process I/WindowState: WIN DEATH: Window{394fad98 u0 com.robertas.parking.bestfreeparking/com.robertas.parking.bestfreeparking.MainActivity}
03-10 20:21:47.474 1499-1874/system_process I/ActivityManager: Process com.robertas.parking.bestfreeparking (pid 31937) has died
03-10 20:21:47.475 1499-1874/system_process W/ActivityManager: Scheduling restart of crashed service com.robertas.parking.bestfreeparking/com.android.tools.fd.runtime.InstantRunService in 1000ms
03-10 20:21:47.480 1123-1123/? W/SurfaceFlinger: couldn't log to binary event log: overflow.
03-10 20:21:47.521 1499-1558/system_process D/OpenGLRenderer: endAllStagingAnimators on 0x7ffc9dfec000 (RippleDrawable) with handle 0x7ffca9734500
03-10 20:21:47.525 1499-1753/system_process W/InputMethodManagerService: Got RemoteException sending setActive(false) notification to pid 31937 uid 10058
03-10 20:21:47.537 1956-32415/com.google.android.googlequicksearchbox:search I/HotwordRecognitionRnr: Starting hotword detection.
03-10 20:21:47.537 1956-32414/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_starting gzi@c6aa4d0
03-10 20:21:47.568 1135-1912/? E/audio_hw_generic: Error opening input stream format 1, channel_mask 0010, sample_rate 16000
03-10 20:21:47.569 1135-32418/? I/AudioFlinger: AudioFlinger's thread 0xf59c4000 ready to run
03-10 20:21:47.581 2146-32417/com.google.android.gms W/IcingInternalCorpora: getNumBytesRead when not calculated.
03-10 20:21:47.584 1956-32414/com.google.android.googlequicksearchbox:search I/MicrophoneInputStream: mic_started gzi@c6aa4d0
03-10 20:21:47.602 1956-1956/com.google.android.googlequicksearchbox:search I/HotwordWorker: onReady
03-10 20:21:47.629 2146-2248/com.google.android.gms W/Settings: Setting adb_enabled has moved from android.provider.Settings.Secure to android.provider.Settings.Global.
03-10 20:21:47.629 2146-2248/com.google.android.gms I/Icing: Usage reports 1 indexed 1 rejected 0 imm upload true
03-10 20:21:47.634 2146-2248/com.google.android.gms W/Icing: App history upload skipped 1 0 0
03-10 20:21:48.101 1135-1535/? W/AudioFlinger: write blocked for 469 msecs, 16 delayed writes, thread 0xf58ac000
03-10 20:21:48.503 32429-32429/? I/art: Not late-enabling -Xcheck:jni (already on)
03-10 20:21:48.507 1499-1518/system_process I/ActivityManager: Start proc 32429:com.robertas.parking.bestfreeparking/u0a58 for service com.robertas.parking.bestfreeparking/com.android.tools.fd.runtime.InstantRunService
03-10 20:21:48.775 32429-32429/com.robertas.parking.bestfreeparking I/FirebaseInitProvider: FirebaseApp initialization unsuccessful
03-10 20:21:48.777 32429-32429/com.robertas.parking.bestfreeparking I/InstantRun: Starting Instant Run Server for com.robertas.parking.bestfreeparking
03-10 20:21:48.777 1499-14635/system_process W/ActivityManager: getRunningAppProcesses: caller 10058 does not hold REAL_GET_TASKS; limiting output

2 个答案:

答案 0 :(得分:0)

确保在build.gradle文件中编译com.google.android.gms.maps。如果它不存在,请将其添加到依赖项中:

dependencies {
        <other dependencies>
        compile 'com.google.android.gms:play-services-maps:10.2.0'
    }

请记住在java文件中导入它:

import com.google.android.gms.maps.SupportMapFragment;

关于工具:上下文,它应该是.MainActivity

答案 1 :(得分:0)

  

所有事情都发生在firstTime()void中,错误显示它在线setContentView(R.layout.activity_main);。

你不能这样做。

start()firstTime()不是您的活动/应用的入口点 onCreate()是您只能致电setContentView(R.layout.activity_main)的地方。

即便如此,“加载”任何活动的static方法都无效。

public static void load(){

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(can);
    if (!prefs.getBoolean("firstTime", false)) {

        can.firstTime(); // This doesn't work like this

    }

}

特别是如果你在其他课程的其他地方MainActivity.load()

阅读您的错误,请参阅start() - &gt; setContentView()导致问题......

  at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:143)
  at com.robertas.parking.bestfreeparking.MainActivity.start(MainActivity.java:161)
  at com.robertas.parking.bestfreeparking.MainActivity$8.onClick(MainActivity.java:356)
  at android.view.View.performClick(View.java:4780)

真正的错误消息

  

将id为0x7f0f00e8,标记为null或父ID为0x7f0f00e7与com.google.android.gms.maps.SupportMapFragment

的另一个片段重复

意味着片段"@+id/maps"已经添加到Activity类的FragmentManger中,因此它已被复制。

理想情况下,活动不应在setContentView之外调用onCreate

原因=您致电setContentView,因此完全从根视图中删除MapFragment(和其他视图),因此 1) FragmentManger无法找到以前添加的任何内容, 2)您之前使用findViewById的任何视图(可能)都不再存在。

如果您想“替换”某些Activity的内容,那么您应该使用Fragments + FrameLayout + FragmentTransaction.replace()方法调用。