我有一个带有嵌入在 FragmentActivity 中的按钮的片段。当我单击按钮时,我希望将片段替换为另一个片段。问题是:片段是我的活动的内部静态类,方法是非静态的。我通过创建我的 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 类。