Android fragments 尝试写入字段';intandroid.app.Fragment.mNextAnim';关于空对象引用
我正在尝试使用片段-用if和else更改片段。 我在尝试运行程序时遇到了这个错误: “尝试写入空对象引用上的字段'int android.app.Fragment.mNextAnim'” 我搜索了答案,发现mybe的sulotion要导入Fragmet.support.v4.app.Fragment 所以我试过了,但我不能改成这个 我该怎么做,还是换一种方式Android fragments 尝试写入字段';intandroid.app.Fragment.mNextAnim';关于空对象引用,android-fragments,Android Fragments,我正在尝试使用片段-用if和else更改片段。 我在尝试运行程序时遇到了这个错误: “尝试写入空对象引用上的字段'int android.app.Fragment.mNextAnim'” 我搜索了答案,发现mybe的sulotion要导入Fragmet.support.v4.app.Fragment 所以我试过了,但我不能改成这个 我该怎么做,还是换一种方式 import android.app.Fragment; import android.app.FragmentManager; impo
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(isInSingleFrragment()){
FragmentManager fm = getFragmentManager();
Fragment fragmentB = fm.findFragmentById(R.id.FragmetB);
FragmentTransaction ft=fm.beginTransaction();
ft.hide(fragmentB);
ft.commit();
Button switchbutton = (Button)findViewById(R.id.switchbutton);
switchbutton.setOnClickListener(this);
}
}
private boolean isInSingleFrragment() {
View layout = findViewById(R.id.singleLayout);
if (layout != null) {
return true;
} else {
return false;
}
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.switchbutton:
switchFragments();
break;
}
}
private void switchFragments() {
FragmentManager fm = getFragmentManager();
Fragment fragmentA = fm.findFragmentById(R.id.FragmetA);
Fragment fragmentB = fm.findFragmentById(R.id.FragmetB);
FragmentTransaction ft = fm.beginTransaction();
if(fragmentA.isVisible()){
ft.hide(fragmentA);
ft.show(fragmentB);
}else {
ft.hide(fragmentB);
ft.show(fragmentA);
}
ft.commit();
}
}
使用hide时,必须有一个片段used.add().hide();该错误告诉您没有片段在隐藏片段B之前添加null检查
if(isInSingleFrragment()){
FragmentManager fm = getFragmentManager();
Fragment fragmentB = fm.findFragmentById(R.id.FragmetB);
FragmentTransaction ft = fm.beginTransaction();
if (fragmentB != null) ft.hide(fragmentB); // check != null
ft.commit();
...
}