添加片段

时间:2017-10-30 16:37:04

标签: java android android-fragments nullpointerexception

我尝试创建一个简单的颜色更改应用程序。在我的应用程序中,我创建了一个具有线性布局的片段,其中包含文本视图。我试图在我的应用程序中定期更改textview的颜色。为了在常规间隔中改变颜色,我使用了random()函数来创建0到255之间的随机数,并使用这些数字作为参数来创建随机颜色。我再次使用这些随机颜色来设置我的textview的背景,它以线性布局显示。

以下是我的代码:

MainActivity.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

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

<?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 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>

以下是我在构建代码时收到的错误消息。

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

2 个答案:

答案 0 :(得分:0)

R.id.container不是Fragment的ID,调用findFragmentById(R.id.container);将返回null。

要添加片段,请使用以下代码:

一种方法:

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 ();

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

另一种方法:

您也可以直接从活动的XML中使用片段。

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

然后您不必使用与FragmentManager

相关的代码

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

答案 1 :(得分:0)

如果您有一个片段,则无需使用replace()。你只需要使用add()。以下代码错误:

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

因为R.id.container不是片段而是FrameLayout。您的活动布局中没有片段,只有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>

它应该在哪里:

<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>

要解决此问题,您需要更改用于添加片段的代码:

Fragment newFragment = new ColorChangeFragment();

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

然后,您需要修复ColorChangeFragment类以扩展android.support.v4.app.Fragment。所以,把你的班级变成这样的东西:

...

import android.support.v4.app.Fragment;

public class ColorChangeFragment extends Fragment {

  ...

}
相关问题