java - 我正在尝试在 android 中制作可滑动的选项卡布局,但在操作栏中获取空值

标签 java android android-fragments tabs swipe

我正在尝试为 {profile} 和 {Child} 制作两个选项卡布局,它们也应该是可滑动的。我已经为它们创建了布局和 fragment ,并且在主 Activity 布局上,我放置了

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent">

在我的 Main Activity.java 类中,我的代码是

import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;


public class MainActivity extends AppCompatActivity implements ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;

// Tab titles
private String[] tabs = {"Profile", "Child"};

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

    // Initialization
    viewPager = (ViewPager) findViewById(R.id.pager);

    actionBar = (ActionBar) getSupportActionBar();

    mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

但是在actionBar中,我得到了空值,因此程序在此时使用空指针执行。由于什么原因,getActionBar 中可能会出现 null。

最佳答案

将您的 Activity 主题更改为@style/Theme.AppCompat 在布局中定义工具栏:

<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"
    tools:context=".MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:minHeight="?attr/actionBarSize"
        android:background="?attr/colorPrimary" />

    <android.support.v4.view.ViewPager
         android:id="@+id/pager"
         android:layout_width="match_parent"
         android:layout_height="match_parent">

</RelativeLayout>

并设置自定义操作栏:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit);

    Toolbar toolbar = (Toolbar) findViewById(toolbar);
    setSupportActionBar(toolbar);

    actionBar = (ActionBar) getSupportActionBar();
}

ActionBar 选项卡已弃用,自 API 21 起不再工作。您应该使用 PagerSlidingTabStrip图书馆。

关于java - 我正在尝试在 android 中制作可滑动的选项卡布局,但在操作栏中获取空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34784743/

相关文章:

android - 在 startIntentSenderForResult 之后未调用 OnActivityResult

android - 使 Android 源代码中的应用程序编译为系统/应用程序而不是数据/应用程序?

android - 使用 fragment 更改为横向时 map 行为会发生变化

android - 如何将 ArrayAdapter<String> 从 Activity 传递到 Fragment

java - 大括号阻止编译

java - Gson : StackOverflowError

android - 如何通过代码获取android设备(WIFI关闭)的MAC地址?

java - 如何暂停线程直到处理完数据?发送信号量?

java - 为什么init中会出现堆栈溢出错误

android - Activity 与 fragment 生命周期