android - 从 Activity 访问 Fragment 的 View

标签 android android-fragments nullpointerexception fragment findviewbyid

我有一个包含 fragment 的 Activity ,它通过在 onCreate 中执行此操作来添加它(来自 Google 示例):

    // Check that the activity is using the layout version with
    // the fragment_container FrameLayout
    if (findViewById(R.id.fragment_container) != null) {

        // However, if we're being restored from a previous state,
        // then we don't need to do anything and should return or else
        // we could end up with overlapping fragments.
        if (savedInstanceState != null) {
            return;
        }

        // Create a new Fragment to be placed in the activity layout
        RecordFragment firstFragment = new RecordFragment();

        // In case this activity was started with special instructions from an
        // Intent, pass the Intent's extras to the fragment as arguments
        firstFragment.setArguments(getIntent().getExtras());

        // Add the fragment to the 'fragment_container' FrameLayout
        getSupportFragmentManager().beginTransaction()
                .add(R.id.fragment_container, firstFragment).commit();

这是 Activity 布局:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />

这是 fragment :

public class RecordFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_record, container, false);
}

还有fragment_record.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.controlcenter.RecordActivity$PlaceholderFragment" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Information:"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <EditText
        android:id="@+id/action_info"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:ems="10" />

    <ImageView
        android:id="@+id/arrow_button"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:src="@drawable/ic_action_forward" />

</LinearLayout>

在 fragment 中有一个箭头按钮。我希望该 Activity 向按钮添加一个监听器,这样当单击该按钮时,该 fragment 将滑出,另一个 fragment 将滑入。 我无法访问该按钮,我正在尝试使用

firstFragment.getView().findViewById(R.id.arrow_button)

尽管我重载了 onCreateView() 方法,但 getView 似乎返回 null。

最佳答案

简单的答案是你不知道。将 fragment 的 View 视为 fragment 内部的内容。相反,通过您定义的接口(interface)将 Activity 设置为 Fragment 的监听器,然后在 Fragment 中设置单击监听器以调用 Fragment 的监听器。

public class MyFragment extends Fragment {
    public interface MyListener {
        public void onAction();
    }

    private MyListener mListener;
    public void setListener(MyListener listener) {
        mListener = listener;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_record, container, false);

        root.findViewById(R.id.arrow_button).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mListener != null) {
                    mListener.onAction();
                }
            }
        });
        return root;
    }
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof MyListener) {
            mListener = (MyListener) activity;
        } else {
            // Maybe throw an exception if you want to be strict
        }
    }
}

你的 Activity 类需要这个:

public class MyActivity extends Activity implements MyFragment.MyListener {
    public void onAction() {
        // TODO whatever you need to do when the button is clicked
    }
}

关于android - 从 Activity 访问 Fragment 的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24659641/

相关文章:

android - 客户端还没有准备好。等待进程上线更新版本的 Android Studio

java - 当构建目标使用新 API 级别 21 时,Android 项目 fragment 转换抛出异常

android - fragment 何时不附加到 Activity 而仅附加到上下文?

JavaFX 对象在启动后始终为空

Android Webrtc JNI 错误(应用错误): local reference table overflow (max=512)

android - 验证在无效文本输入上显示的 AlertDialog

java - 带/不带 baseObservable 的 android viewmodel

android - map fragment 在 Android 4.4 kitkat 中不起作用

android - NullPointerException:尝试在空对象引用上调用虚方法 enableForegroundDispatch(...)

android - 查看 -> getParent() 在 Android 2.3 中工作正常,但在 Android 4+ 中抛出 NullPointerException