0

NullPointerException在调用片段的方法时得到了一个。

在我的MainActivity 中:

  AddTab fragObj = (AddTab) getSupportFragmentManager().findFragmentById(R.layout.fragment_add);
 fragObj.receiveURL(sharedText);

receiveURL() 是我的 Fragment AddTab 中的一个方法。

pagerslidingtabstrip在我的应用程序中使用来创建选项卡,这Fragment是由它的PagerAdapter类创建的。

我不确定创建 Tab 的新实例是否正确,因为已经存在一个。我也不知道如何访问该实例。

我现在得到一个NullPointerException。谁能帮助我如何在片段中调用该方法?

编辑 :

AddTab.java:

public class AddTab extends Fragment implements View.OnClickListener {

...

}

片段添加.xml:

<FrameLayout 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="com.example.nikhil.amazon1.Add">


    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:text="@string/URL"
        android:hint="@string/hint"
        android:layout_marginTop="200dp"
        android:layout_gravity="center_horizontal|top" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/Track"
        android:id="@+id/button"
        android:layout_gravity="center" />

</FrameLayout>
4

1 回答 1

2

如果您使用<fragment>标签Fragment在布局中包含 a,则可以使用您在 xml 中findFragmentById分配的 id来使用 find。Fragment例子 :

<fragment
    ...
    android:id="@+id/fragment_id/>

AddTab fragObj = (AddTab)getSupportFragmentManager().findFragmentById(R.id.fragment_id);

如果您Fragment动态添加,请使用标签:

String TAG = "fragment tag";

FragmentTransaction ft;
ft.add(containerViewId, fragment, TAG);

AddTab fragObj = (AddTab)getSupportFragmentManager().findFragmentByTag(TAG);
于 2015-03-18T16:11:55.413 回答