我嘗試了很多不同的方法來實現向左滑動並向右滑動,它們都不適用於我。 我想要兩個片段通過滑動來改變位置。我嘗試了從這裏和其他來源複製的onFling和onTouch方法,但是應用程序沒有響應或碰撞。我在MainActivity中編寫了包含這些片段的實現代碼,但是當我在片段上設置onTouch監聽器時,它給了我NullPointerException,但是我不知道是否可以將OnTouchListener添加到MainActivity本身? 總之,這裏是我寫的最後時刻的代碼,它給我一個錯誤:向右或向左滑動
嘗試寫入到字段「android.app.FragmentManagerImpl android.app.Fragment.mFragmentManager」上的空對象引用
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
public class MainActivity extends ActionBarActivity {
private FragmentManager mFragmentManager;
private Fragment_1to6 f1to6;
private Fragment_7to12 f7to12;
private buttonsFragment mButtonsFragment;
private FrameLayout relative1;
private RelativeLayout relative2;
float x1, x2;
float y1, y2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFragmentManager = getFragmentManager();
relative1 = (FrameLayout) findViewById(R.id.fragment_container);
relative2 = (RelativeLayout) findViewById(R.id.fragment_7to12);
if (!isInTwoPaneMode()) {
mButtonsFragment = (buttonsFragment) mFragmentManager.findFragmentById(R.id.fragment_buttons);
FragmentTransaction ft = mFragmentManager.beginTransaction();
ft.replace(R.id.fragment_container, new Fragment_1to6());
ft.addToBackStack(null);
ft.commit();
relative1.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
x1 = event.getX();
y1 = event.getY();
break;
}
case MotionEvent.ACTION_UP: {
x2 = event.getX();
y2 = event.getY();
// right to left
if (x1 > x2) {
changeToSecondFrag();
mFragmentManager.executePendingTransactions();
return true;
} if (x1 < x2) {
changeToFirstFrag();
mFragmentManager.executePendingTransactions();
return true;
} break;
}
}
return true;
}
});
} else {
mButtonsFragment = (buttonsFragment) mFragmentManager.findFragmentById(R.id.fragment_buttons);
f1to6 = (Fragment_1to6) mFragmentManager.findFragmentById(R.id.fragment_1to6);
f7to12 = (Fragment_7to12) mFragmentManager.findFragmentById(R.id.fragment_7to12);
}
}
private boolean isInTwoPaneMode(){
return findViewById(R.id.fragment_container) == null;
}
public void changeToSecondFrag(){
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_container, f7to12);
ft.addToBackStack(null);
ft.commit();
} public void changeToFirstFrag(){
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_container, f1to6);
ft.addToBackStack(null);
ft.commit();
}
}
我只想要第二個和第三個片段交換位置,但第一個始終保留在Activity中。所以我覺得尋呼機適配器不適合這個 –