У меня трудности с загрузкой компонентов пользовательского интерфейса внутри фрагмента во время экрана spla sh. Поскольку это мое первое android приложение, и я не знаю много об идеальных шаблонах проектирования, в настоящее время приложение реализовано следующим образом. MainActivity - это операция spla sh для отображения экрана spla sh. DrawerLayoutActivity содержит фрагмент, в котором фрагменты загружаются по мере необходимости. Теперь при запуске HomeFragment загружается в DrawerLayoutActivity . HomeFragment содержит TabLayout , который будет иметь три фрагмента в качестве вкладок. Эти вкладки имеют ListView с компонентами пользовательского интерфейса, которые должны быть загружены изначально. Благодаря реализации экрана spla sh из учебных пособий мне удалось реализовать экран spla sh, но он загружает только DrawerLayoutActivity и не загружает фрагменты вкладок в HomeFragment при отображении экрана spla sh. Я хочу, чтобы хотя бы первый фрагмент HomeFragment был загружен во время экрана spla sh.
Я открыт для любых предложений или советов ..
Вот код ..
AndroidManifest. xml
<activity android:name=".MainActivity" android:theme="@style/SplashTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
MainActivity. java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, DrawerLayoutActivity.class);
startActivity(intent);
finish();
}
}
activity_drawer_layout. xml
<?xml version="1.0" encoding="UTF-8"?>
<androidx.drawerlayout.widget.DrawerLayout 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:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.navigation.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />
</androidx.drawerlayout.widget.DrawerLayout>
app_bar_main. xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 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"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
<include layout="@layout/content_main" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
content_main. xml
<?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"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/app_bar_main">
<fragment
android:id="@+id/nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
DrawerLayoutActivity. java
public class DrawerLayoutActivity extends AppCompatActivity{
[...]
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer_layout);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
drawerLayout = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.app_name,R.string.app_name);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
HomeFragment homeFragment = new HomeFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.nav_host_fragment,homeFragment);
fragmentTransaction.commit();
}
[...]
}
HomeFragment. java
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_home, container, false);
tabLayout= root.findViewById(R.id.timelineTabs);
viewPager = root.findViewById(R.id.viewPager);
tabLayout.addTab(tabLayout.newTab().setText("Journal Entries"));
tabLayout.addTab(tabLayout.newTab().setText("Account Entries"));
tabLayout.addTab(tabLayout.newTab().setText("Expense Entries"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setOnTabSelectedListener(this);
myPagerAdapter = new MyPagerAdapter(getActivity().getSupportFragmentManager(),tabLayout.getTabCount());
viewPager.setAdapter(myPagerAdapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
[...]
}
frag_home. xml
<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.tabs.TabLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorPrimary"
android:id="@+id/timelineTabs"
app:tabSelectedTextColor="#fff"
app:tabIndicatorColor="#fff">
</com.google.android.material.tabs.TabLayout>
<androidx.viewpager.widget.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/timelineTabs"
android:id="@+id/viewPager" />
<include layout="@layout/layout_fab_submenu"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
/>
</RelativeLayout>
MyPagerAdapter. java
public class MyPagerAdapter extends FragmentStatePagerAdapter {
public MyPagerAdapter(FragmentManager supportFragmentManager, int tabCount) {
super(supportFragmentManager);
this.tabCount=tabCount;
}
@Override
public Fragment getItem(int position) {
switch (position){
case 0:
if(entriesTab==null) {
entriesTab = new EntriesTab();
}
return entriesTab;
case 1:
if(accEntriesTab==null) {
accEntriesTab = new AccEntriesTab();
}
return accEntriesTab;
case 2:
if(expEntriesTab==null) {
expEntriesTab = new ExpEntriesTab();
}
return expEntriesTab;
}
return null;
}
@Override
public int getCount() {
return tabCount;
}
}
EntriesTab. java
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View entriesView = inflater.inflate(R.layout.fragment_home_entries, container, false);
recyclerView=entriesView.findViewById(R.id.recycler_view);
feedboxesList = new ArrayList<>();
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
adapter = new RecyclerViewAdapter(getContext(), feedboxesList);
liveJournalEntries = [ ... ] // firebase listener
recyclerView.setAdapter(adapter);
return entriesView;
}
Код успешно работает в текущей настройке.
Любая альтернативная стратегия более эффективной реализации этой вещи также была бы очень полезна.