Android studio Fragment TabHost

标签 android fragment-tab-host

我想在单击按钮时在 activity_main 中显示一个 fragmentTabHost。当我单击它时,它显示“不幸的是 FragTabHost 已停止”。下面是代码。请帮助我!!

主要 Activity

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button=(Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TestFragment fragment=new TestFragment();
                FragmentManager fragmentManager=fragment.getFragmentManager();
                FragmentTransaction transaction=fragmentManager.beginTransaction();
                transaction.replace(R.id.relative,fragment);
                transaction.commit();


            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.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);
    }
}

Activity 主体

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:id="@+id/relative"
    tools:context=".MainActivity">


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:text="TabHost"/>

</RelativeLayout>

测试 fragment

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="0" />

    <FrameLayout
        android:id="@+id/realtabcontent"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

    <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:orientation="horizontal" />

</LinearLayout>

测试 fragment

package com.example.sabudaniel61.fragtabhost;

/**
 * Created by Sabudaniel61 on 2015-09-30.
 */

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class TestFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        FragmentTabHost tabHost = new FragmentTabHost(getActivity());
        inflater.inflate(R.layout.test_fragment, tabHost);
        tabHost.setup(getActivity(),
                getChildFragmentManager(), R.id.realtabcontent);

        tabHost.addTab(tabHost.newTabSpec("simple")
                .setIndicator("Simple"), DummySectionFragment.class, null);
        tabHost.addTab(tabHost.newTabSpec("contacts")
                .setIndicator("Contacts"), DummySectionFragment.class, null);
        return tabHost;
    }

    /**
     * A dummy fragment representing a section of the app,
     * but that simply displays dummy text.
     */
    public static class DummySectionFragment extends Fragment {
        private static int count = 0;
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_section_dummy,
                    container, false);
            ((TextView) rootView.findViewById(android.R.id.text1))
                    .setText("Dummy Section " + count++);
            return rootView;
        }
    }
}

fragment_section_dummy

 <TextView 
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@android:id/text1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textSize="24sp"
        android:padding="32dp"
        />

日志:

09-30 00:43:18.676  28335-28335/com.example.sabudaniel61.fragtabhost E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.sabudaniel61.fragtabhost, PID: 28335
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.v4.app.FragmentTransaction android.support.v4.app.FragmentManager.beginTransaction()' on a null object reference
            at com.example.sabudaniel61.fragtabhost.MainActivity$1.onClick(MainActivity.java:24)
            at android.view.View.performClick(View.java:4756)
            at android.view.View$PerformClick.run(View.java:19749)
            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:5221)
            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:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
09-30 00:48:19.063  28335-28335/com.example.sabudaniel61.fragtabhost I/Process﹕ Sending signal. PID: 28335 SIG: 9

最佳答案

您在 MainActivity 的第 24 行收到 NullPointerException

替换

FragmentManager fragmentManager=fragment.getFragmentManager();

FragmentManager fragmentManager=this.getSupportFragmentManager();

在 MainActivity 中。

关于Android studio Fragment TabHost,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32858085/

相关文章:

android Edittext提示问题

android - 我如何将变量从我的适配器传递到我在 Kotlin 中实例化的 fragment

android - 如何将按钮添加到 Fragment TabHost

android - 如何跨选项卡使用单个 fragment 中的 EditText?

java.lang.IllegalStateException : Can not perform this action after onSaveInstanceState while using FragmentTabHost 错误

android - 从 Android 应用程序连接到 MongoDB 的更好方法

java - 什么是 textview.setTextSize()?

android - 如何用两个不同的对象填充 ExpandableListView

android - Google Play 是否有一些 "Feature Graphic"生成器?

android - 将 fragment 添加到 Tab 主机