我使用viewpager在三个不同的片段之间滑动,第三个是MapFragment。应用程序第一次加载正常,但是当我第二次刷回第一个片段时崩溃。
这是我的第一个片段的布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:id="@+id/fragment_one"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.nihardalal.tabview.Fragments.OneFragment"
>
<TextView
android:id="@+id/txtResponse"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="40px"
android:padding="20dp"
android:textSize="12sp"/>
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Find Me"
android:id="@+id/button"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="54dp" />
</RelativeLayout>
我的片段类的代码如下:
public class OneFragment extends Fragment {
private String text;
buttonClicker mCallback;
public OneFragment() {
}
public interface buttonClicker {
public void onButtonClicked();
}
@Override
public void setArguments(Bundle args) {
super.setArguments(args);
}
@Override
public void onCreate(Bundle savedInstancesState) {
super.onCreate(savedInstancesState);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (buttonClicker) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstancesState) {
View view = inflater.inflate(R.layout.fragment_one, container, false);
TextView txt = (TextView) view.findViewById(R.id.txtResponse);
txt.setText(MainActivity.response1);
Button btn = (Button) view.findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCallback.onButtonClicked();
}
}
);
return view;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
三个片段的布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.nihardalal.tabview.Fragments.ThreeFragment"
>
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
三个片段的代码:
public class ThreeFragment extends Fragment implements OnMapReadyCallback{
private SupportMapFragment mMapFragment;
private String address;
public ThreeFragment() {
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_three, container, false);
mMapFragment = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map));
mMapFragment.getMapAsync(this);
return view;
}
@Override
public void setArguments(Bundle args) {
this.address = args.getString("address");
}
@Override
public void onMapReady(GoogleMap map){
GoogleMap mMap = map;
// Add a marker in Sydney and move the camera new LatLng(18.94102, 72.82427)
LatLng place = new LatLng(18.94102, 72.82427);
mMap.addMarker(new MarkerOptions().position(place).title("Marker at Al-sabah"));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(place, 17));
}
public LatLng getLocationFromAddress(Context context, String strAddress) {
Geocoder coder = new Geocoder(context);
List<Address> address;
LatLng p1 = null;
try {
address = coder.getFromLocationName(strAddress, 5);
if (address == null) {
return null;
}
Address location = address.get(0);
location.getLatitude();
location.getLongitude();
p1 = new LatLng(location.getLatitude(), location.getLongitude() );
} catch (Exception ex) {
ex.printStackTrace();
}
return p1;
}
}
主要活动如下:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, OneFragment.buttonClicker{
private ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private String jsonResponse;
private MapFragment mMapFragment;
private OnMapReadyCallback mapReadyCallback;
public static String response1, response2;
private String address;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
makeJsonArrayRequest();
// mMapFragment = ((MapFragment) getFragmentManager().findFragmentById(R.id.map));
// mMapFragment.getMapAsync(this);
viewPager = (ViewPager) findViewById(R.id.viewpager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
private String loadJSONFromAsset() {
String json = null;
try {
InputStream is = this.getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
private void makeJsonArrayRequest() {
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray m_jArry = obj.getJSONArray("info");
for (int i = 0; i < m_jArry.length(); i++) {
jsonResponse = "";
JSONObject jo_inside = m_jArry.getJSONObject(i);
Log.d("Details-->", jo_inside.getString("name"));
JSONObject phone = jo_inside.getJSONObject("phone");
jsonResponse += "Name: " + jo_inside.getString("name") + "\n\n";
jsonResponse += "Email: " + jo_inside.getString("email") + "\n\n";
jsonResponse += "Home: " + phone.getString("home") + "\n\n";
jsonResponse += "Mobile: " + phone.getString("mobile") + "\n\n";
jsonResponse += "Address: " + jo_inside.getString("address") + "\n\n\n";
if (i == 0) {
address = jo_inside.getString("address");
MainActivity.response1 = jsonResponse;
} else {
MainActivity.response2 = jsonResponse;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void setupViewPager(ViewPager viewPager) {
Fragment oneFragment = new OneFragment();
Bundle oneArgs = new Bundle();
oneArgs.putString("text", response1);
oneFragment.setArguments(oneArgs);
Fragment twoFragment = new TwoFragment();
Bundle twoArgs = new Bundle();
twoArgs.putString("text", response2);
twoFragment.setArguments(twoArgs);
Fragment threeFragment = new ThreeFragment();
Bundle threeArgs = new Bundle();
threeArgs.putString("address", address);
adapter.addFragment(oneFragment, "ONE");
adapter.addFragment(twoFragment, "TWO");
adapter.addFragment(threeFragment, "THREE");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
@Override
public CharSequence getPageTitle(int position) {
return mFragmentTitleList.get(position);
}
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void onButtonClicked() {
viewPager.setCurrentItem(2);
}
我得到的错误如下:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.nihardalal.tabview, PID: 2867
android.view.InflateException: Binary XML file line #7: Binary XML file line #7: Error inflating class fragment
at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at com.example.nihardalal.tabview.Fragments.ThreeFragment.onCreateView(ThreeFragment.java:47)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.attachFragment(FragmentManager.java:1430)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:728)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1177)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
at android.support.v4.view.ViewPager$3.run(ViewPager.java:254)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:603)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.view.InflateException: Binary XML file line #7: Error inflating class fragment
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:782)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at com.example.nihardalal.tabview.Fragments.ThreeFragment.onCreateView(ThreeFragment.java:47)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.attachFragment(FragmentManager.java:1430)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:728)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1177)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
at android.support.v4.view.ViewPager$3.run(ViewPager.java:254)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:603)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.IllegalArgumentException: Binary XML file line #7: Duplicate id 0x7f0d00a1, tag null, or parent id 0xffffffff with another fragment for com.google.android.gms.maps.SupportMapFragment
at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2293)
at android.support.v4.view.LayoutInflaterCompatHC$FactoryWrapperHC.onCreateView(LayoutInflaterCompatHC.java:44)
at android.view.LayoutInflater$FactoryMerger.onCreateView(LayoutInflater.java:186)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:746)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
at com.example.nihardalal.tabview.Fragments.ThreeFragment.onCreateView(ThreeFragment.java:47)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
at android.support.v4.app.FragmentManagerImpl.attachFragment(FragmentManager.java:1430)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:728)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1177)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
at android.support.v4.view.ViewPager$3.run(ViewPager.java:254)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
at android.view.Choreographer.doCallbacks(Choreographer.java:670)
at android.view.Choreographer.doFrame(Choreographer.java:603)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
我是Android新手,我只是想学习如何使用GoogleMaps和ViewPager。帮助将不胜感激。
由于