当前位置: 首页 > 知识库问答 >
问题:

如何从片段访问父活动中的UI元素

干弘深
2023-03-14

家长活动布局

<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>
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;
    }

共有1个答案

戚阳文
2023-03-14

因为您想要活动的视图,所以您需要这样做:

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

调用getActivity()来获取活动实例,然后像往常一样使用findviewbyid()(如果r.id.ctrlActivityIndicator是活动布局的一部分,则不会获得NPEs)。

 类似资料:
  • 问题内容: 我有一个带有Viewpager片段的Android活动。在活动的onCreate方法中,我将服务绑定到该服务,该服务始终在后台运行。 在片段中,在特定条件下,我需要在处理该条件的服务中调用一个函数。访问服务并调用其功能的正确方法是什么? MainActivity.java 这是我的服务。我连接到服务器,并不断收听更新。 SocketListener.java 这是我需要调用的片段。 问

  • 这是我的场景: 我在我的活动中有ViewPager,其中包含6个片段。我用手指滑动来禁用分页,所以每当我想滑动时,我使用相关的按钮和: 在每一个swipe片段中(swipe完成后),我希望向服务器发送一个GET请求,并获取一些数据并在该片段中显示它。因为这样做: 答:Daniel Nugent的代码运行良好,除了在发送GET请求时显示ProgressDialog之外,我使用了: 这段代码也返回Nu

  • 问题内容: 我要在我的下一个Android项目中使用Retrofit 2.1.0。我想使用设计模式,因此为每个REST调用创建单独的类,即 IBalanceService.java BalanceRestClient.java BalanceActivity.java 如何通过onResponse()更新活动/片段中的UI? 附加信息: 最小SDK:19个 目标SDK:23个 使用OkHttp和g

  • 问题内容: 我托管了5个片段,在每个片段上我都需要填写一些字段。 我想从中获取这些字段的值。我尝试了类似的东西: AddActivity.java FragPagerAdapter.java OtherFragment.java 公共类OtherFragment扩展Fragment {Button btn; 更新 的问题我总是得到EditText(而其他字段要获得)的问题等于null如果它们位于片

  • //使用startActivity(intent)也不起作用//无论我做什么,应用程序都会崩溃