【发布时间】:2020-04-13 12:05:57
【问题描述】:
我有两个 APK。第一个 APK 是加载第二个 APK 的主 APK。
MainActivity.java(第一个 APK): 对象 mainFragment 被 DexClassLoader 提前加载
setContentView(R.layout.activity_main);
LinearLayout fragContainer = findViewById(R.id.main_fragment);
LinearLayout ll = new LinearLayout(context);
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.setId(View.generateViewId());
getSupportFragmentManager().beginTransaction().add(ll.getId(), mainFragment, "mainFragment").commit();
fragContainer.addView(ll);
activity_main.xml(第一个 APK):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="@+id/main_fragment"
android:orientation="vertical"
/>
</LinearLayout>
MainFragment.java(第二个 APK):
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, viewGroup, false);
view.findViewById(R.id.emailSignInButton).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
return view;
}
fragment_main.xml(第二个 APK):
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="@string/sign_in"
android:layout_width="88dp"
android:layout_height="wrap_content"
android:id="@+id/emailSignInButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" android:layout_marginStart="32dp"
android:layout_marginEnd="32dp" android:layout_marginTop="8dp"
tools:ignore="MissingConstraints" />
</androidx.constraintlayout.widget.ConstraintLayout>
我不明白,为什么要排队
View view = inflater.inflate(R.layout.fragment_main, viewGroup, false);
view 始终为 NULL。我需要像 mainFragment 那样将 R.layout.fragment_main 加载到内存中吗?
【问题讨论】:
-
资源不存在。
DexClassLoader加载类,而不是资源。 -
尝试使用应用程序上下文,而不是 viewGroup 上下文,例如View.inflate(getApplicationContext(), R.layout.fragment_main, viewGroup) 或 LayoutInflater.from(getApplicationContext()).inflate(R.layout.fragment_main, viewGroup, false)
-
@VytautasBerankis 它没有帮助
标签: java android android-fragments layout dynamic-loading