我有一个活动,在那个活动里面我有片段
片段有OnClick方法,应该是
换到另一种观点。
我想要的是使用内部的onclick方法更改内部视图
分段并使用相同的活动
到目前为止,这只是我能做的事情。
Fragment mFragment = null;
Class fragmentClass;
fragmentClass = LoginSignup.class;
try {
mFragment = (Fragment) fragmentClass.newInstance();
} catch (Exception mE) {
Log.e(TAG, mE.toString());
}
FragmentManager mFragmentManager = getSupportFragmentManager();
mFragmentManager.beginTransaction().replace(R.id.frameLayout, mFragment).commit();
答案 0 :(得分:1)
使用以下方法
public static void openFragment(FragmentManager manager, Fragment targetFragment) {
try {
String fragmentName = targetFragment.getClass().getName();
manager.popBackStack();
manager.beginTransaction()
.replace(R.id.frameLayout, targetFragment, fragmentName)
.addToBackStack(fragmentName)
.commit();
} catch (Exception e) {
e.printStackTrace();
}
}
每次打开片段时都会调用此方法。你必须将两个参数传递给这个方法。 targetFragment 是您要打开的片段。
答案 1 :(得分:1)
我总是使用EventBus通知活动或实现接口来更改片段中的片段。
<强>接口强>
public interface LoginViewInterface {
void moveToLoginView();
void moveToInsertView();
}
<强>活动:强>
public class LoginActivity implements LoginViewInterface {
private FragmentManager manager;
private FragmentTransaction transaction;
private List<BaseFragment> fragmentList;
private LoginFragment loginFragment;
private InsertFragment insertFragment;
private void InitFragment(){
manager = getFragmentManager();
insertFragment = (LogModeFragment) manager.findFragmentById(R.id.login_insert);
loginFragment = (LoginFragment) manager.findFragmentById(R.id.login_login);
insertFragment.InitInterface(this);
loginFragment.InitInterface(this);
fragmentList = new ArrayList<>();
fragmentList.add(loginFragment);
fragmentList.add(insertFragment);
transaction = manager.beginTransaction().hide(fragmentList.get(0))
.hide(fragmentList.get(1));
transaction.show(fragmentList.get(0)). commitAllowingStateLoss();
}
@Override
public void moveToLoginView() {
transaction.hide(fragmentList.get(0));
transaction.show(fragmentList.get(1));
transaction.commitAllowingStateLoss();
}
@Override
public void moveToInsertView() {
transaction.hide(fragmentList.get(1));
transaction.show(fragmentList.get(0));
transaction.commitAllowingStateLoss();
}
}
<强>片段:强>
class InsertFragment extends BaseFragment{
LoginViewInterface dataInterface;
public void InitInterface(LoginViewInterface dataInterface) {
this.dataInterface = dataInterface;
}
private doChange(){
dataInterface.moveToInsertView();
}
}