简体   繁体   English

碎片,我在做什么错?

[英]Fragments, what am I doing wrong?

So I am doing what this tutorial says. 所以我正在做教程所说的。 I've got a MainActivity with a navigation drawer. 我有一个带有导航抽屉的MainActivity。

This is my MainActivity.java 这是我的MainActivity.java

package nl.broekhin.magizon;


import android.app.Activity;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import layout.LoginFragment;
import layout.RoosterFragment;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, 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(this);




        LoginFragment loginFragment = new LoginFragment();
        RoosterFragment roosterFragment = new RoosterFragment();

        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, loginFragment).commit();
    }



    public interface OnFragmentInteractionListener {
        //public void onFragmentMessage(String TAG, Object data);
    }

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

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

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

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

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

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

        }

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


}

This is my content_main.xml : 这是我的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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="nl.broekhin.magizon.MainActivity"
    tools:showIn="@layout/app_bar_main">

    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />


</RelativeLayout>

However, when I try to launch this, I get an error. 但是,当我尝试启动它时,出现错误。

java.lang.RuntimeException: Unable to start activity ComponentInfo{nl.broekhin.magizon/nl.broekhin.magizon.MainActivity}: java.lang.RuntimeException: nl.broekhin.magizon.MainActivity@3e4143c must implement OnFragmentInteractionListener java.lang.RuntimeException:无法启动活动ComponentInfo {nl.broekhin.magizon / nl.broekhin.magizon.MainActivity}:java.lang.RuntimeException:nl.broekhin.magizon.MainActivity@3e4143c必须实现OnFragmentInteractionListener

Have you added a piece of code somewhere which checks if MainActivity is instance of OnFragmentInteractionListener? 您是否在某处添加了一段代码来检查MainActivity是否是OnFragmentInteractionListener的实例?

If you want to communicate between Activity and Fragment, your activity needs to implement the interface Fragment defines to require. 如果要在Activity和Fragment之间进行通信,则您的活动需要实现Fragment定义所需的接口。

In your case in your MainActivity after your class definition: 在您的情况下,在您的类定义之后的MainActivity中:

Class MainActivity extends Activity {

you should make it implement your OnFragmentInteractionListener interface this way: 您应该通过以下方式使其实现OnFragmentInteractionListener接口:

Class MainActivity extends Activity implements OnFragmentInteractionListener {

After implementing the interface, you're required to implement the methods the interface defines, which you'll IDE will guide you how to do. 在实现接口之后,需要实现接口定义的方法,IDE将指导您如何做。

In your LoginFragment you are doing somewhere the following casting, 在您的LoginFragment中,您正在执行以下强制转换,

(OnFragmentInteractionListener)getActivity()

However your MainActivity doesn't implement the interface OnFragmentInteractionListener (even though you have defined it). 但是,您的MainActivity并没有实现OnFragmentInteractionListener接口(即使您已定义它)。 The solution is simple. 解决方案很简单。 Change, 更改,

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

to

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener,OnFragmentInteractionListener {

Can you post your login fragment? 您可以发布您的登录片段吗?

I guess the problem is that you're inflating the wrong layout file in your activity. 我想问题是您在活动中夸大了错误的布局文件。 Please check the inflated file. 请检查膨胀的文件。 In your activity it says R.layout.activity_main but you named your xml as content_main.xml 在您的活动中显示R.layout.activity_main,但您将xml命名为content_main.xml

I solved it! 我解决了!

Apparently, I had to use android.support.v4.app.Fragment; 显然,我不得不使用android.support.v4.app.Fragment; instead of android.app.Fragment; 而不是android.app.Fragment; . This is the code I got it to work with: 这是我可以使用的代码:

protected void setFragment(Fragment fragment) {
    android.support.v4.app.FragmentTransaction t = getSupportFragmentManager().beginTransaction();
    t.replace(R.id.fragment_container, fragment);
    t.commit();
}

And to set it (from the nav bar onNavigationItemSelected() , you do this: 并进行设置(从导航栏onNavigationItemSelected() ,您可以执行以下操作:

setFragment(new RoosterFragment());

I hope this helps others out with the same frustrating problem. 我希望这可以帮助其他人解决同样令人沮丧的问题。

我想您必须在活动中实现OnFragmentIntractionListner接口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM