再次运行代码中的异常android

时间:2014-08-19 08:35:05

标签: android exception android-fragments

public class MainActivity extends FragmentActivity {

    ImageView iview1;
    LayoutParams params;
    FragmentManager fmgr;
    FragmentTransaction ftr;
    FirstFragment ff;
    LinearLayout layout;
    ArrayList<Fragment> FArray;
    int counter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        counter=0;
        FArray=new ArrayList<Fragment>();
        iview1=(ImageView)findViewById(R.id.iview);
        iview1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                showFF();

            }
        });
        layout=(LinearLayout) findViewById(R.id.frag);
        fmgr = getSupportFragmentManager();
        ftr=fmgr.beginTransaction();

        params=(LayoutParams) layout.getLayoutParams();

        //showF();
    }

    public void showFF(){
        FArray.add(new FirstFragment());
        ftr.add(R.id.frag, FArray.get(counter));
        if (true){//showing==false){
            params.weight=1;
            iview1.setLayoutParams(params);
            layout.setLayoutParams(params);
            ftr.commit();
        }
        counter++;

    }
}

这段代码第一次正确执行,但是当我再次点击iview1时。我得到Exception - &gt; Force Close。 为什么呢?

1 个答案:

答案 0 :(得分:0)

代码中的一个问题是,每次要beginTransaction commit更改时,您都需要致电Fragment

因此,请尝试在您的函数中添加beginTransaction,如下所示:

public void showFF(){
    ftr=fmgr.beginTransaction();
    FArray.add(new FirstFragment());
    ftr.add(R.id.frag, FArray.get(counter));
    if (true){//showing==false){
        params.weight=1;
        iview1.setLayoutParams(params);
        layout.setLayoutParams(params);
        ftr.commit();
    }
    counter++;
}

如果您仍有异常,请发布Logcat并尝试interpret