简体   繁体   English

添加片段时应用程序崩溃

[英]App crashes when adding a fragment

I tried to create a simple color change application.我尝试创建一个简单的颜色更改应用程序。 In my application I have created a fragment which has linear layout and inside which text view is present.在我的应用程序中,我创建了一个具有线性布局的片段,其中存在文本视图。 I am trying to change the color of textview in my application in a regular interval.我正在尝试定期更改应用程序中 textview 的颜色。 In order to change color in regular interval, I have used random() function to create a random number between 0 and 255 and use those numbers as a parameter to create random colors.为了定期更改颜色,我使用 random() 函数创建了 0 到 255 之间的随机数,并将这些数字用作参数来创建随机颜色。 I am again using those random colors to set the background of my textview which is present in linear layout.我再次使用这些随机颜色来设置线性布局中存在的文本视图的背景。

Below are my codes:以下是我的代码:

MainActivity.java主活动.java

package com.example.abcd.color_change;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

        FragmentManager fragment = getSupportFragmentManager();
        Fragment existingFragment = fragment.findFragmentById(R.id.container);
        fragment.beginTransaction().replace(R.id.linear1, existingFragment).commit();


    }
}

ColorChangeFragment.java颜色变化片段.java

package com.example.abcd.color_change;

import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by abcd on 10/7/17.
 */

public class ColorChangeFragment {
    private TextView mTextView;
    private Random rand = new Random();
    private int randNum = 0;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState){

        View v = inflater.inflate(R.layout.fragment,container, false);
        mTextView = (TextView) v.findViewById(R.id.textview);

        Timer timer = new Timer();

        //MyTimer mt = new MyTimer();
        /*timer.schedule(mt, 1000, 1000);*/
        timer.schedule(new TimerTask(){

            @Override
            public void run() {
                int r = rand.nextInt(255);
                int g = rand.nextInt(255);
                int b = rand.nextInt(255);
                int randomColor = Color.rgb(r,g,b);
                mTextView.setBackgroundColor(randomColor);
            }
        },5000,5000);
        return v;
    }

   /* class MyTimer extends TimerTask{

        @Override
        public void run() {
            runOnUiThread(new Runnable(){

                @Override
                public void run() {
                    Random rand = new Random();
                    mTextView.setBackgroundColor(Color.argb(255, rand.nextInt(256), rand.nextInt(256) ));
                }
            });
        }
    }*/


}

ActivityMain.xml ActivityMain.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</FrameLayout>

fragment.xml片段.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id ="@+id/linear1"
    android:background="@android:color/white">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id = "@+id/textview"/>

</LinearLayout>

Below is the error message I receive upon building the code.以下是我在构建代码时收到的错误消息。

10-30 12:56:21.393 21574-21574/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.example.abcd.color_change, PID: 21574
                                                   java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.abcd.color_change/com.example.abcd.color_change.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2762)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2848)
                                                       at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1552)
                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                       at android.os.Looper.loop(Looper.java:154)
                                                       at android.app.ActivityThread.main(ActivityThread.java:6334)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
                                                       at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:394)
                                                       at android.support.v4.app.BackStackRecord.replace(BackStackRecord.java:441)
                                                       at android.support.v4.app.BackStackRecord.replace(BackStackRecord.java:432)
                                                       at com.example.abcd.color_change.MainActivity.onCreate(MainActivity.java:17)
                                                       at android.app.Activity.performCreate(Activity.java:6743)
                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2715)
                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2848) 
                                                       at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1552) 
                                                       at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                       at android.os.Looper.loop(Looper.java:154) 
                                                       at android.app.ActivityThread.main(ActivityThread.java:6334) 
                                                       at java.lang.reflect.Method.invoke(Native Method) 
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
10-30 12:56:21.393 21574-21574/? D/AppTracker: App Event: crash

If you're having a single Fragment, you don't need to use replace() .如果您只有一个 Fragment,则不需要使用replace() You just need to use add().你只需要使用 add()。 The following code is wrong:下面的代码是错误的:

FragmentManager fragment = getSupportFragmentManager();
        Fragment existingFragment = fragment.findFragmentById(R.id.container);
        fragment.beginTransaction().replace(R.id.linear1, existingFragment).commit();

Because R.id.container is not a fragment but a FrameLayout .因为R.id.container不是片段而是FrameLayout There is no fragment in your activity layout but only a FrameLayout which is:您的活动布局中没有片段,只有一个 FrameLayout,它是:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</FrameLayout>

Where it should be:应该在哪里:

<LinearLayout>
    <fragment android:name="com.example.ColorChangeFragment"
            android:id="@+id/color_fragment"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent" />

</LinearLayout>

To solve the problem, you need to change the code for adding the fragment with:要解决该问题,您需要更改添加片段的代码:

Fragment newFragment = new ColorChangeFragment();

FragmentTransaction fragmentTransaction = this.getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.container, fragment);
fragmentTransaction.commit();

Then, you need to fix the ColorChangeFragment class to extend the android.support.v4.app.Fragment .然后,您需要修复ColorChangeFragment类以扩展android.support.v4.app.Fragment So, change your class to something like this:所以,把你的班级改成这样:

...

import android.support.v4.app.Fragment;

public class ColorChangeFragment extends Fragment {

  ...

}

R.id.container is not an id of a Fragment and calling findFragmentById(R.id.container); R.id.container不是Fragment的 id 并调用findFragmentById(R.id.container); will return null.将返回空值。

To add a fragment, use the following code:要添加片段,请使用以下代码:

One method:一种方法:

Fragment newFragment = new ColorChangeFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the container view with this fragment,
// and add the transaction to the back stack
transaction.replace (R.id.container , newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit ();

Fragment Transaction tutorial: https://developer.android.com/guide/components/fragments.html#Transactions片段交易教程: https : //developer.android.com/guide/components/fragments.html#Transactions

Another method:另一种方法:

You can also use fragment directly from the XML of your activity.您还可以直接从活动的 XML 中使用片段。

<FrameLayout>
    <fragment
        android:name="com.example.abcd.color_change.ColorChangeFragment"
        ...
    />
</FrameLayout/>

Then you don't have to use code related to FragmentManager那你就不用使用FragmentManager相关的代码了

Check the tutorial here: https://developer.android.com/training/basics/fragments/creating.html在此处查看教程: https : //developer.android.com/training/basics/fragments/creating.html

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

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