2 eiseno Eiseno 于 2013.01.24 13:47 提问

从fragment在父activity中我怎么能够访问UI elements

父activity布局

<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=".LockerCodeActivity" >

    <LinearLayout
        android:id="@+id/fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </LinearLayout>

    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:id="@+id/ctrlActivityIndicator"
        android:indeterminateOnly="true"
        android:keepScreenOn="false"
     />

    <TextView
        android:id="@+id/tv_results"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="" />

</RelativeLayout>

在父activity的onCreate方法中的fragment

FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    Fragment scannerFragment = new ScanFragment();
    fragmentTransaction.add(R.id.fragment_container, scannerFragment);
    fragmentTransaction.commit();

大概差不多就这样。现在我怎么样才能隐藏掉进度条?我现在是这样做的。

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_scan, container, false);

    ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.ctrlActivityIndicator);
    progressBar.setVisibility(View.INVISIBLE);
    return view;
    }

但是我得到了一个空指针异常

2个回答

cytown
cytown   2013.01.24 14:59
已采纳

这样:
fragment里面:

onAttach(Activity activity) {
    ProgressBar progressBar = (ProgressBar) activity.findViewById(R.id.ctrlActivityIndicator);
    progressBar.setVisibility(View.INVISIBLE);
}
Sueyexin
Sueyexin   2013.01.24 17:01

既然你想要activity's views,你可以这样:

ProgressBar progressBar = (ProgressBar) getActivity().findViewById(R.id.ctrlActivityIndicator);

调用getActivity()来获得activity instance,然后你用findViewById()(如果R.id.ctrlActivityIndicator是activity布局的一部分,你无法得到NPEs)

Csdn user default icon
上传中...
上传图片
插入图片