jjzjj

android - 调用 findViewById() 获取 fragment View 时出现 NullPointerException

coder 2023-12-15 原文

我正在尝试设置一个 FragmentStatePagerAdapter 以在我的一个 fragment 上创建一个类似于 this example 的可滚动选项卡界面.在我的 Activity 的 onCreate 中:

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

     setVersionString();
     setupActionBar();
     setupNavigationDrawer();
     setupFragments();
}

我将内容 View 设置为以下布局(R.layout.base):

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".BaseActivity" >

    <!-- The main content view -->
    <FrameLayout
        android:id="@+id/main_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!-- The navigation drawer -->
    <ListView
        android:id="@+id/nav_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#FFF" />

</android.support.v4.widget.DrawerLayout>

然后我调用以下函数:

private void setupFragments() {
    // Check that the activity is using the correct layout
    if (findViewById(R.id.main_frame) != null) {
        // Initialize the first fragment
        MainFragment firstFrag = new MainFragment();

        // Pass any extras from an intent to the Fragment
        firstFrag.setArguments(getIntent().getExtras());

        // Add the first Fragment to the screen
        getSupportFragmentManager().beginTransaction()
            .add(R.id.main_frame, firstFrag).commit();

        tabsAdapter = firstFrag.getAdapter();
        Log.d("Base.LOG", "tabsAdapter = " + tabsAdapter);
        tabsAdapter.addTab(DummyFragment.class, null);
    }
}

尝试将 FragmentStatePagerAdapter 设置为 fragment 布局 (R.layout.main) 中 View 的适配器:

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

    <android.support.v4.view.PagerTitleStrip
        android:id="@+id/pager_title_strip"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:background="#33b5e5"
        android:textColor="#fff"
        android:paddingTop="4dp"
        android:paddingBottom="4dp" />
</android.support.v4.view.ViewPager>

我的 fragment 的代码看起来是这样的:

private View mView;
private TabbedPagerAdapter mTabPageAdapter;
private ViewPager mTabPager;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    Log.d("Main.LOG", "onCreate called");
    mView = inflater.inflate(R.layout.main, container, false);
    Log.d("Main.LOG", "Layout inflated");
    setupTabs();
    Log.d("Main.LOG", "Tabs setup");

    return mView;
}

@Override
public void onResume() {
    super.onResume();
    Log.d("Main.LOG", "onResume called");
}

/** Set up the ViewPager and Adapter to handle the primary tabs */
private void setupTabs() {
    // Initialize the adapter
    mTabPageAdapter = new TabbedPagerAdapter(getActivity(),
            getActivity().getSupportFragmentManager());

    // Initialize the view pager
    mTabPager = (ViewPager) mView.findViewById(R.id.main_page);
    Log.d("Main.LOG", "mTabPager = " + mTabPager);
    Log.d("Main.LOG", "mTabPageAdapter = " + mTabPageAdapter);
    mTabPager.setAdapter(mTabPageAdapter);
}

/* Accessor for TabbedPagerAdapter */
public TabbedPagerAdapter getAdapter() {
    return mTabPageAdapter;
}

当我尝试添加带有 NullPointerException 的选项卡时,应用程序强制关闭。日志中的调试消息显示:

D/Base.LOG(27173): tabsAdapter = null

显示在 fragment 的任何调试消息之前。在尝试访问任何 View 或子类之前,如何确保布局已膨胀?

最佳答案

根据我的评论

public class MainFragment extends Fragment
{
    private MainInterface mInterface = null;
    //make sure to set the above somehow

    public interface MainInterface{
        public void onFragmentReady(.....);
    }

    ... //Do regular stuff here

    public void onResume()
    {
        //Do what you need to do in onResume
        if(mInterface != null)
        {
            mInteface.onFragmentReady();
        }
    }
}

这应该让您知道 fragment 何时准备就绪,然后您可以调用 getTabAdapter。

关于android - 调用 findViewById() 获取 fragment View 时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18623970/

有关android - 调用 findViewById() 获取 fragment View 时出现 NullPointerException的更多相关文章

  1. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  2. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

    我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

  3. ruby - 简单获取法拉第超时 - 2

    有没有办法在这个简单的get方法中添加超时选项?我正在使用法拉第3.3。Faraday.get(url)四处寻找,我只能先发起连接后应用超时选项,然后应用超时选项。或者有什么简单的方法?这就是我现在正在做的:conn=Faraday.newresponse=conn.getdo|req|req.urlurlreq.options.timeout=2#2secondsend 最佳答案 试试这个:conn=Faraday.newdo|conn|conn.options.timeout=20endresponse=conn.get(url

  4. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  5. ruby - 从 Ruby 中的主机名获取 IP 地址 - 2

    我有一个存储主机名的Ruby数组server_names。如果我打印出来,它看起来像这样:["hostname.abc.com","hostname2.abc.com","hostname3.abc.com"]相当标准。我想要做的是获取这些服务器的IP(可能将它们存储在另一个变量中)。看起来IPSocket类可以做到这一点,但我不确定如何使用IPSocket类遍历它。如果它只是尝试像这样打印出IP:server_names.eachdo|name|IPSocket::getaddress(name)pnameend它提示我没有提供服务器名称。这是语法问题还是我没有正确使用类?输出:ge

  6. ruby - 获取模块中定义的所有常量的值 - 2

    我想获取模块中定义的所有常量的值:moduleLettersA='apple'.freezeB='boy'.freezeendconstants给了我常量的名字:Letters.constants(false)#=>[:A,:B]如何获取它们的值的数组,即["apple","boy"]? 最佳答案 为了做到这一点,请使用mapLetters.constants(false).map&Letters.method(:const_get)这将返回["a","b"]第二种方式:Letters.constants(false).map{|c

  7. ruby-on-rails - 获取 inf-ruby 以使用 ruby​​ 版本管理器 (rvm) - 2

    我安装了ruby​​版本管理器,并将RVM安装的ruby​​实现设置为默认值,这样'哪个ruby'显示'~/.rvm/ruby-1.8.6-p383/bin/ruby'但是当我在emacs中打开inf-ruby缓冲区时,它使用安装在/usr/bin中的ruby​​。有没有办法让emacs像shell一样尊重ruby​​的路径?谢谢! 最佳答案 我创建了一个emacs扩展来将rvm集成到emacs中。如果您有兴趣,可以在这里获取:http://github.com/senny/rvm.el

  8. c# - 如何在 ruby​​ 中调用 C# dll? - 2

    如何在ruby​​中调用C#dll? 最佳答案 我能想到几种可能性:为您的DLL编写(或找人编写)一个COM包装器,如果它还没有,则使用Ruby的WIN32OLE库来调用它;看看RubyCLR,其中一位作者是JohnLam,他继续在Microsoft从事IronRuby方面的工作。(估计不会再维护了,可能不支持.Net2.0以上的版本);正如其他地方已经提到的,看看使用IronRuby,如果这是您的技术选择。有一个主题是here.请注意,最后一篇文章实际上来自JohnLam(看起来像是2009年3月),他似乎很自在地断言RubyCL

  9. Ruby 从大范围中获取第 n 个项目 - 2

    假设我有这个范围:("aaaaa".."zzzzz")如何在不事先/每次生成整个项目的情况下从范围中获取第N个项目? 最佳答案 一种快速简便的方法:("aaaaa".."zzzzz").first(42).last#==>"aaabp"如果出于某种原因你不得不一遍又一遍地这样做,或者如果你需要避免为前N个元素构建中间数组,你可以这样写:moduleEnumerabledefskip(n)returnto_enum:skip,nunlessblock_given?each_with_indexdo|item,index|yieldit

  10. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

随机推荐