我有一个实现NavigationView.OnNavigationItemSelectedListener的活动A,它将它连接到片段1、2、3。片段1具有一个viewPager和一个pagerAdapter,后者将其连接到片段4、5、6。
我运行这个,当活动A运行片段1时我得到一个错误,它说";找不到碎片id…的视图&";。我查了一下,但想不通。有人能告诉我如何解决这个问题吗?感谢
片段1是TimeFragment
活动A是AdminAddNewMerchantActivity
pagerAdapter是DetailsPageAdapter
下面我有代码:
TimeFragment.java
package com.vision.lateoclocktt.ui.time;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import androidx.fragment.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.google.android.material.tabs.TabItem;
import com.google.android.material.tabs.TabLayout;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.StorageTask;
import com.vision.lateoclocktt.DetailsPageAdapter;
import com.vision.lateoclocktt.R;
import com.vision.lateoclocktt.ui.orders.OrdersAdminViewModel;
/**
* A simple {@link Fragment} subclass.
* Use the {@link TimeFragment} factory method to
* create an instance of this fragment.
*/
public class TimeFragment extends Fragment {
private Uri imageUri, imageUri2;
private static final int GalleryPick = 1, GalleryPickBanner = 2;
private StorageTask uploadTask, uploadTask2;
private OrdersAdminViewModel ordersAdminViewModel;
private RecyclerView orderList;
private DatabaseReference ordersRef;
private String downloadImageUrl, downloadImageUrl2;
private TabLayout tabLayout;
private TabItem tabDetails, tabAddress, tabPrice, tabStart, tabEnd;
private ViewPager viewPager;
DetailsPageAdapter pagerAdapter;
private ImageView inputImage, inputBanner;
private StorageReference storageBannerPictureRef,merchantImageReference;
Button saveMechantAddress;
private String myUrl = "";
private RelativeLayout rLayout;
private String currentFragment, currentNavFragment;
private final String CURRENT_FRAG = "current fragment";
private String NAV_FRAG = "navigation fragment";
SharedPreferences sharedPreferences;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.fragment_time, container, false);
tabLayout = root.findViewById(R.id.timeTabLayout);
tabDetails = root.findViewById(R.id.t_merchant_details);
tabAddress = root.findViewById(R.id.t_merchant_address);
tabPrice = root.findViewById(R.id.t_merchant_price);
tabStart = root.findViewById(R.id.t_start_time);
viewPager = root.findViewById(R.id.time_viewPager);
pagerAdapter = new DetailsPageAdapter(getChildFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(pagerAdapter);
//viewPager.onRestoreInstanceState(new );
storageBannerPictureRef = FirebaseStorage.getInstance().getReference().child("Merchant Banner Images");
merchantImageReference = FirebaseStorage.getInstance().getReference().child("Mechant Images");
currentNavFragment = "Details";
sharedPreferences = getActivity().getSharedPreferences("root_preferences", Context.MODE_PRIVATE);
//SharedPreferences sharedPreferences = getSharedPreferences("root_preferences", MODE_PRIVATE);
currentFragment = sharedPreferences.getString(CURRENT_FRAG, "time");
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(NAV_FRAG, currentNavFragment);
editor.commit();
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("tab", tab.getPosition());
editor.commit();
viewPager.setCurrentItem(tab.getPosition());
if(tab.getPosition() == 0) {
pagerAdapter.notifyDataSetChanged();
}
else if(tab.getPosition() == 1)
{
pagerAdapter.notifyDataSetChanged();
}
else if(tab.getPosition() == 2)
{
pagerAdapter.notifyDataSetChanged();
}
else if(tab.getPosition() == 3)
{
pagerAdapter.notifyDataSetChanged();
}
else if(tab.getPosition() == 4)
{
pagerAdapter.notifyDataSetChanged();
}
else if(tab.getPosition() == 5)
{
pagerAdapter.notifyDataSetChanged();
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
//tabLayout.setTabTextColors(Color.parseColor("#000000"), Color.parseColor("#ffffff"));
return root;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if(currentFragment.equals("Find Food Admin"))
{
TabLayout.Tab tab1 = tabLayout.getTabAt(sharedPreferences.getInt("tab",0));
tab1.select();
}
else if(currentFragment.equals("Maps Merchant"))
{
TabLayout.Tab tab1 = tabLayout.getTabAt(sharedPreferences.getInt("tab",0));
tab1.select();
}
else if(currentFragment.equals("Price"))
{
TabLayout.Tab tab1 = tabLayout.getTabAt(sharedPreferences.getInt("tab",0));
tab1.select();
}
else if(currentFragment.equals("Start"))
{
TabLayout.Tab tab1 = tabLayout.getTabAt(sharedPreferences.getInt("tab",0));
tab1.select();
}
else if(currentFragment.equals("Options"))
{
TabLayout.Tab tab1 = tabLayout.getTabAt(sharedPreferences.getInt("tab",0));
tab1.select();
}
else if(currentFragment.equals("Brief"))
{
TabLayout.Tab tab1 = tabLayout.getTabAt(sharedPreferences.getInt("tab",0));
tab1.select();
}
}
private void openGallery(int galleryNumber) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("`image/*");
//startActivityForResult(Intent.createChooser(galleryIntent, "Select Picture"), galleryNumber);
startActivityForResult(galleryIntent, galleryNumber);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onResume() {
super.onResume();
}
}
管理员添加新商户活动.java
package com.vision.lateoclocktt.Admin;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
//import android.support.v7.widget.Toolbar;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.android.material.navigation.NavigationView;
import com.vision.lateoclocktt.Buyers.MainActivity;
import com.vision.lateoclocktt.Prevalent.Prevalent;
import com.vision.lateoclocktt.R;
import com.vision.lateoclocktt.Sellers.SettingsMerchantActivity;
import com.vision.lateoclocktt.ui.cart.CartFragment;
import com.vision.lateoclocktt.ui.favorites.FavoritesFragment;
import com.vision.lateoclocktt.ui.findFood.FindFoodFragment;
import com.vision.lateoclocktt.ui.map.MapsUserFragment;
import com.vision.lateoclocktt.ui.orders.OrdersAdminFragment;
import com.vision.lateoclocktt.ui.receipts.ReceiptsFragment;
import com.vision.lateoclocktt.ui.time.TimeFragment;
import com.vision.lateoclocktt.ui.userview.UserViewFragment;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import io.paperdb.Paper;
public class AdminAddNewMerchantActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawer;
NavigationView navigationView;
private String currentActivity;
private final String CURRENT_ACT = "current activity";
private String NAV_FRAG = "navigation fragment";
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_add_new_merchant);
currentActivity = "adminaddnewmerchant";
sharedPreferences = getSharedPreferences("root_preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(CURRENT_ACT, currentActivity);
editor.commit();
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar_admin);
setSupportActionBar(toolbar);
toolbar.setTitle("Home");
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_baseline_menu_24));
drawer = findViewById(R.id.container_admin);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = findViewById(R.id.nav_view_admin);
BottomNavigationView navView = findViewById(R.id.bot_nav_view_admin);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
R.id.navigation_merchant_details_admin, R.id.navigation_user_view, R.id.navigation_orders_admin)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_admin_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navView, navController);
View headerView = navigationView.getHeaderView(0);
TextView name = (TextView)headerView.findViewById(R.id.username);
TextView email = headerView.findViewById(R.id.email);
name.setText(sharedPreferences.getString("name", ""));
email.setText(sharedPreferences.getString("email", ""));
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
switch (item.getItemId()) {
case R.id.navigation_settings:
Intent settingsIntent = new Intent(AdminAddNewMerchantActivity.this, SettingsMerchantActivity.class);
startActivity(settingsIntent);
break;
case R.id.navigation_logout:
currentActivity = "main";
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.putString(CURRENT_ACT,currentActivity);
editor.commit();
Intent logoutIntent = new Intent(AdminAddNewMerchantActivity.this, MainActivity.class);
Paper.book().write(Prevalent.RememberMeMerchant, "false");
Paper.book().write(Prevalent.emailKey, "UserEmail");
Paper.book().write(Prevalent.passwordKey, "UserPassword");
logoutIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//logoutIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(logoutIntent);
finish();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
if(!sharedPreferences.getString(NAV_FRAG, "").equals("")){
if(sharedPreferences.getString(NAV_FRAG, "").equals("Details"))
{
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, new TimeFragment()).commit();
navView.setSelectedItemId(R.id.navigation_merchant_details_admin);
}
else if(sharedPreferences.getString(NAV_FRAG, "").equals("Userview"))
{
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, new UserViewFragment()).commit();
navView.setSelectedItemId(R.id.navigation_user_view);
}
else if(sharedPreferences.getString(NAV_FRAG, "").equals("Orders"))
{
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_fragment, new OrdersAdminFragment()).commit();
navView.setSelectedItemId(R.id.navigation_orders_admin);
}
}
}
@Override
public void onBackPressed()
{
if(drawer.isDrawerOpen(GravityCompat.START))
{
drawer.closeDrawer(GravityCompat.START);
}
else{
super.onBackPressed();
}
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_merchant_details_admin:
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_admin_fragment, new TimeFragment()).commit();
break;
case R.id.navigation_user_view:
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_admin_fragment, new UserViewFragment()).commit();
break;
case R.id.navigation_orders_admin:
getSupportFragmentManager().beginTransaction().replace(R.id.nav_host_admin_fragment, new OrdersAdminFragment()).commit();
break;
}
return true;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
}
}
DetailsPageAdapter.java
package com.vision.lateoclocktt;
import com.vision.lateoclocktt.ui.brief.BriefFragment;
import com.vision.lateoclocktt.ui.findFood.FindFoodAdminFragment;
import com.vision.lateoclocktt.ui.map.MapsMerchantFragment;
import com.vision.lateoclocktt.ui.options.OptionsFragment;
import com.vision.lateoclocktt.ui.price.PriceFragment;
import com.vision.lateoclocktt.ui.time.StartFragment;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
public class DetailsPageAdapter extends FragmentPagerAdapter {
private int numberOfTabs;
public FragmentManager mfm;
public DetailsPageAdapter(@NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
this.mfm = fm;
this.numberOfTabs = behavior;
}
@NonNull
@Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new FindFoodAdminFragment();
case 1:
return new MapsMerchantFragment();
case 2:
return new PriceFragment();
case 3:
return new StartFragment();
case 4:
return new OptionsFragment();
case 5:
return new BriefFragment();
default:
return null;
}
}
@Override
public int getCount() {
return numberOfTabs;
}
@Override
public int getItemPosition(@NonNull Object object) {
return POSITION_NONE;
}
}
错误:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.vision.lateoclocktt, PID: 4500
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.vision.lateoclocktt/com.vision.lateoclocktt.Admin.AdminAddNewMerchantActivity}: java.lang.IllegalArgumentException: No view found for id 0x7f0a01a2 (com.vision.lateoclocktt:id/nav_host_fragment) for fragment TimeFragment{fa4480} (b1d4c74f-3fd0-4e61-9d0b-89212a0bd27a) id=0x7f0a01a2}
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2665)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f0a01a2 (com.vision.lateoclocktt:id/nav_host_fragment) for fragment TimeFragment{fa4480} (b1d4c74f-3fd0-4e61-9d0b-89212a0bd27a) id=0x7f0a01a2}
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:315)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1187)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1356)
at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1434)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1497)
at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:447)
at androidx.fragment.app.FragmentManager.executeOps(FragmentManager.java:2169)
at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1992)
at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1947)
at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1849)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2629)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2577)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:247)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:541)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:210)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1248)
at android.app.Activity.performStart(Activity.java:6696)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2628)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
我睡了一会儿才明白。在AdminAddNewMerchantActivity.java中,我将R.id.nav_host_fragment更改为R.id.nav_host_admin_fragment,结果成功了!视图nav_host_fragment确实不存在。我从另一个文件复制了它,希望它能正常工作,但没有正确阅读错误消息。