我有一個Fragment,其中嵌入了FragmentActivity內部的按鈕。當我點擊按鈕時,我希望片段被替換爲另一片段。問題是:Fragment是我的Activity的內部靜態類,該方法是非靜態類。我通過創建Activity類的一個實例解決了這個問題,但是當我點擊片段內的按鈕時,應用程序崩潰了。用此片段內的偵聽器替換片段並在活動中使用方法
下面是代碼:
public class Stdp extends SherlockFragmentActivity implements ActionBar.OnNavigationListener {
public static class Bottomfrag extends SherlockFragment {
static Bottomfrag newInstance() {
Bottomfrag f = new Bottomfrag();
return f;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.bottom_choose, container, false);
View li = v.findViewById(R.id.layoutbottom);
li.setBackgroundColor(Color.parseColor("#FFBB33"));
View button = v.findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
Stdp t = new Stdp();
t.addFragmentToStack();
}
});
return v;
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stdp);
Context context = getSupportActionBar().getThemedContext();
ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(context, R.array.test_array, R.layout.sherlock_spinner_item);
list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
getSupportActionBar().setListNavigationCallbacks(list, this);
if (savedInstanceState == null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment bottom = new Bottomfrag();
ft.add(R.id.su1, bottom);
ft.commit();
}
}
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
// TODO Auto-generated method stub
return false;
}
public void addFragmentToStack() {
Fragment newFragment = Bottomfrag.newInstance();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.su1, newFragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
ft.addToBackStack(null);
ft.commit();
}
}
,我發現我的問題的解決方案。我唯一要做的就是將addFragmentToStack移動到Bottomfrag類。
什麼是logcat輸出...什麼是錯誤信息? – 2012-07-19 18:15:40
如果你的代碼仍然有'Stdp t = new Stdp();'那麼你肯定有***找不到你的問題的解決方案。只是說... – 2012-07-19 18:39:42
不,我刪除了那個實例。我在Google上找到了這個解決方案,同時搜索如何在靜態方法中引用非靜態方法。 我完全同意你的帖子,它在Android中沒用。 – Hadi 2012-07-19 18:42:41