![](/img/trans.png)
[英]How can I access UI Elements of a fragment inside of a Custom Adapter From an Activity in Android
[英]how to access UI elements in parent activity from fragment
父活動布局
<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>
膨脹父活動 onCreate 函數中的片段
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;
}
我得到一個空指針異常
由於您想要活動的視圖,您將想要這樣做:
ProgressBar progressBar = (ProgressBar) getActivity().findViewById(R.id.ctrlActivityIndicator);
您調用getActivity()
來獲取 Activity 實例,然后像往常一樣使用findViewById()
(假設R.id.ctrlActivityIndicator
是 Activity 布局的一部分,您將不會獲得 NPE)。
這對我不起作用,我將 getActivity 的結果轉換為父活動。 請參閱下面的鏈接: 從片段調用父母的活動
您可以使用:
((ParentActivity)getActivity()).UI_COMPONENT_NAME
訪問父活動的 ui 組件。
UI_COMPONENT_NAME 是在 ParentActivity 中初始化的組件的名稱。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.