android TabHost 對象報錯

 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TabHost.setup()' on a null object reference
        at com.example.ceshi.MainActivity.onCreate(MainActivity.java:31)

 

沒有解決

 

MainActivity:

package com.example.ceshi;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.GridView;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.ViewSwitcher;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TabHost t = (TabHost) findViewById(android.R.id.tabhost);
        t.setup();
        LayoutInflater i = LayoutInflater.from(this);
        i.inflate(R.layout.tab1,t.getTabContentView());
        i.inflate(R.layout.tab2,t.getTabContentView());
        t.addTab(t.newTabSpec("tab1").setIndicator("競選表情").setContent(R.id.left));
        t.addTab(t.newTabSpec("tab2").setIndicator("愛你").setContent(R.id.right));
    }
}

 

佈局文件:

<?xml version="1.0" encoding="utf-8"?>
<TabHost 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"
    tools:context=".MainActivity"
    android:id="@+id/tabhost">
  <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:orientation="vertical">
    <TabWidget
        android:id="@android:id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    </TabWidget>
    <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </FrameLayout>
  </LinearLayout>

</TabHost>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章