Android的Fragment错误,commit 执行了一次,执行第二次报错 ?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android的Fragment错误,commit 执行了一次,执行第二次报错 ?相关的知识,希望对你有一定的参考价值。

我动态创建Fragment 使用FragmentTransaction的commit 方法后,再次执行这个方法居然就报错了, 请问大神这是怎么回事 ?
这是我的代码

这是报错:

请问这是怎么回事? 求大神指点 谢谢
上面的代码图片错了 是这个 不好意思

onClick了里面要重新ft=fm.beginTransaction();追问

谢谢大神, 我知道了 那我再问你个问题 为啥动态创建后布局位置发生变化了?
不用Fragment 直接引用xml文件 布局就好好的,没有乱, 大神在帮帮我这个问题吧 谢谢

追答

布局位置变化?什么意思?

参考技术A 英文意思already call,正如事务应该不能重复提交吧,transaction不能重复调用啊,要重新实例transaction,没啥好解释的吧追问

谢谢大神, 我知道了 那我再问你个问题 为啥动态创建后布局位置发生变化了?
不用Fragment 直接引用xml文件 布局就好好的,没有乱, 大神在帮帮我这个问题吧 谢谢

追答

你可以开eclipse里的一个UI调试器 或者在真机上开启那个开发者啥的边界看,然后对比你的xml

为啥此错误显示“不兼容的类型”。 “必需:android.support.v4.app.Fragment”?

【中文标题】为啥此错误显示“不兼容的类型”。 “必需:android.support.v4.app.Fragment”?【英文标题】:Why is this Error showing "Incompatible Types." "Required: android.support.v4.app.Fragment"?为什么此错误显示“不兼容的类型”。 “必需:android.support.v4.app.Fragment”? 【发布时间】:2015-07-17 05:40:32 【问题描述】:

所以我的问题是我的 Android 应用程序 Fragments fragment=new SlideShow(); 在开关中,这对 NavDrawer 起作用,这些人有同样的问题,但这些解决方案都没有解决我的问题 Solution 1 和 Solution 2 也 Solution 3

您可能会在代码中看到一些我没有看到的内容。我将显示错误!

我尝试添加导入以及切换工具和扩展,但没有任何效果,也没有人遇到与 mien 相同的问题。

错误:

Error:(176, 26) error: incompatible types: SlideShow cannot be converted to Fragment

Incompatible Types. Required: android.support.v4.app.Fragment Found: com.adobe.SlideShow

我的代码片段:

MainActivity.java

package com.abode;

import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;

/**
* Created by Ryan Tarson on 3/23/2015.
*/
public class MainActivity extends ActionBarActivity


    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    // nav drawer title
    private CharSequence mDrawerTitle;
    // used to store app title
    private CharSequence mTitle;
    // slide menu items
    private String[] navMenuTitles;
    private TypedArray navMenuIcons;

    //old code
    private ArrayList<NavDrawerItem> navDrawerItems;

    private NavDrawerListAdapter adapter;
    LayoutInflater inflater;

    //experiment code

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.drawer_main);



        mTitle = mDrawerTitle = getTitle();


        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);


        navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);
        navDrawerItems = new ArrayList<NavDrawerItem>();

        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuIcons.getResourceId(7, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[8], navMenuIcons.getResourceId(8, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[9], navMenuIcons.getResourceId(9, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[10], navMenuIcons.getResourceId(10, -1)));

        navMenuIcons.recycle();

        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        adapter = new NavDrawerListAdapter(getApplicationContext(),navDrawerItems);

        mDrawerList.setAdapter(adapter);
        // enabling action bar app icon and behaving it as toggle button
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setLogo(R.drawable.logo);
       // getSupportActionBar().setDisplayUseLogoEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.side_bar, R.string.app_name, R.string.app_name) 
            public void onDrawerClosed(View view) 
                getSupportActionBar().setTitle(mTitle);
                // calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();

            

            public void onDrawerOpened(View drawerView) 
                getSupportActionBar().setTitle(mDrawerTitle);
                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();
            
        ;
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) 
            // on first time display view for first nav item
            selectItem(0);
        
    


    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    

    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
       /* int id = item.getItemId();
        if (id == R.id.action_settings)
        
            return true;
        */
        switch (item.getItemId()) 

            case android.R.id.home: 
                if (mDrawerLayout.isDrawerOpen(mDrawerList)) 
                    mDrawerLayout.closeDrawer(mDrawerList);
                 else 
                    mDrawerLayout.openDrawer(mDrawerList);
                
                break;
            

            case R.id.action_settings:

        
        return super.onOptionsItemSelected(item);
    

    private class DrawerItemClickListener implements ListView.OnItemClickListener 
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) 
            selectItem(position);
        
    

    @Override
    protected void onPostCreate(Bundle savedInstanceState) 
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    

    @Override
    public void onConfigurationChanged(Configuration newConfig) 
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggles
        mDrawerToggle.onConfigurationChanged(newConfig);
    
    private void selectItem(int position)
    

        Fragment fragment = null;
        switch (position)
        
            case 0:
                fragment=new SlideShow();


                break;

            case 1:
                fragment=new Beauty();


                break;

            default:
                break;
        
        if (fragment != null) 
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.content, fragment).commit();

            // update selected item and title, then close the drawer
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
//            setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
         else 
            // error in creating fragment
            Log.e("MainActivity", "Error in creating fragment/Assigned designated page.");
        
        // mDrawerLayout.closeDrawer(mDrawerList);
    
    @Override
    public void setTitle(CharSequence title) 
        mTitle = title;
        getSupportActionBar().setTitle(mTitle);
    


这里是“主页”页面,case 0; 是主页选项卡! SlideShow.java

package com.abode;

import android.app.Activity;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.app.Activity;
import android.content.Context;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.Gallery.LayoutParams;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;
/**
 * Created by Ryan on 5/5/2015.
 */
public class SlideShow extends Activity implements
        AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory  
    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.homeslideshow);

        mSwitcher = (ImageSwitcher) findViewById(R.id.switcher);
        mSwitcher.setFactory(this);
        mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.fade_in));
        mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
                android.R.anim.fade_out));

        Gallery g = (Gallery) findViewById(R.id.gallery);
        g.setAdapter(new ImageAdapter(this));
        g.setOnItemSelectedListener(this);
    

    public void onItemSelected(AdapterView<?> parent, View v, int position, long id) 
        mSwitcher.setImageResource(mImageIds[position]);
    

    public void onNothingSelected(AdapterView<?> parent) 
    

    public View makeView() 
        ImageView i = new ImageView(this);
        i.setBackgroundColor(0xFF000000);
        i.setScaleType(ImageView.ScaleType.FIT_CENTER);
        i.setLayoutParams(new ImageSwitcher.LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.MATCH_PARENT));
        return i;
    

    private ImageSwitcher mSwitcher;

    public class ImageAdapter extends BaseAdapter 
        public ImageAdapter(Context c) 
            mContext = c;
        

        public int getCount() 
            return mThumbIds.length;
        

        public Object getItem(int position) 
            return position;
        

        public long getItemId(int position) 
            return position;
        

        public View getView(int position, View convertView, ViewGroup parent) 
            ImageView i = new ImageView(mContext);

            i.setImageResource(mThumbIds[position]);
            i.setAdjustViewBounds(true);
            i.setLayoutParams(new Gallery.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            i.setBackgroundResource(R.drawable.onebig);
            return i;
        

        private Context mContext;

    

    private Integer[] mThumbIds = 
        R.drawable.test, R.drawable.onebig,
    ;

    private Integer[] mImageIds = 
        R.drawable.test, R.drawable.onebig,
    ;


【问题讨论】:

一个片段和一个活动,尽管它们看起来相同并且做的事情几乎相同,但它们是两个不同的实体,您不能将一个活动实例化为一个片段。如果你希望 SlideShow 是一个片段,它应该扩展 Fragment 而不是 Activity 但是SlideShowActivity,你想怎么弄成Fragment呢? 在不支持的android中也有Fragment。这是旧的片段类。新的可能是您需要的。取决于您的应用程序以及您支持的 spi 级别 @YaWang HAHAHA LOL 谢谢! 与论坛网站不同,我们不使用“谢谢”、“感谢任何帮助”或Stack Overflow 上的签名。请参阅“Should 'Hi', 'thanks,' taglines, and salutations be removed from posts?。顺便说一句,这是“提前致谢”,而不是“致谢”。 【参考方案1】:

幻灯片是一个活动而不是一个片段。您要么需要将其重新创建为片段,要么使用意图切换到它。你可以这样做:

case 0:
   Intent intent = new Intent(this, Slideshow.class);
   startActivity(intent);
   return;

【讨论】:

以上是关于Android的Fragment错误,commit 执行了一次,执行第二次报错 ?的主要内容,如果未能解决你的问题,请参考以下文章

android的Fragment切换时如何保存状态?

android的Fragment切换时如何保存状态?

Android开发-Crimina

android多个fragment返回键层层返回

android 多个Fragment切换时的注意事项

Android 怎么将fragment 动态地添加到布局中的任意位置?