我試圖加載片段警報對話框響應後,但當我嘗試加載logcat顯示「IllegalStateException:片段不附加到活動」。通常,IllegalStateException在您嘗試在碎片不再附加到活動後執行工作時出現。但在我的情況下,每件事情都很好,我不明白爲什麼片段不附加到一個活動。如何使用AlertDialog加載片段?
這是我的MainActivity:
使用這個類,我叫DilogCreate延伸DialogFragment。
public class MainActivity extends AppCompatActivity {
Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn= (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new DilogCreate(view.getContext(),R.string.tilte,R.string.no,R.string.yes);
}
});
}
這是我DilogCreate類:
對話響應的基礎上,決定片段可以加載與否,如果對話響應是的,我調用另一個活動的名稱Second.java這個類在我嘗試加載片段。
public class DilogCreate extends DialogFragment {
AlertDialog alertDialog;
public DilogCreate(final Context context, int tilte, int no, int yes) {
AlertDialog.Builder mAlertDilog = new AlertDialog.Builder(context);
mAlertDilog.setNegativeButton(yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Intent intent = new Intent(context, second.class);
startActivity(intent);
}
});
alertDialog = mAlertDilog.create();
alertDialog.show();
}
}
這是我的我的Second.java類:
這個類是因爲對話響應這一類我試圖加載片段下而出現。
public class Second extends AppCompatActivity {
FragmentManager fragmentManager;
FragmentTransaction fragmentTransaction;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loadFragment);
fragmentManager=getSupportFragmentManager();
fragmentTransaction=fragmentManager.beginTransaction();
Myfragment myfragment=new Myfragment();
fragmentTransaction.replace(R.id.cont,myfragment);
fragmentTransaction.commit();
}
}
這是MyFragment.java擴展片段:
public class Myfragment extends Fragment{
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.frag,container,false);
}
}
logcat的狀態:
java.lang.IllegalStateException: Fragment DilogCreate{8aea1d4} not attached to Activity
請幫我傢伙,我不知道爲什麼這個錯誤即將到來。
view.getContext()是一個活動場景等等都是相同 –
沒有保證您的視圖中使用的語境是一個Activity,我想你會在這裏傳遞Activity引用來傳遞給構建器。 – codemonger
他明白了。另外,爲什麼你將字符串傳遞給一個int參數? – klutch