我有一个片段,想要隐藏并显示一个按钮。我使用这段代码:
public class Tablo extends FragmentActivity{
Fragment fg ;
Button click ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tablo);
fg = getFragmentManager().findFragmentById(R.id.emojicons);
click = (Button) findViewbyId(R.id.Button1);
click.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentManager fm = getFragmentManager();
fm.beginTransaction()
.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
.show(fg)
.commit();
}
});
记录错误:
java.lang.NullPointerException: Attempt to write to field 'int android.app.Fragment.mNextAnim' on a null object reference
at android.app.BackStackRecord.run(BackStackRecord.java:809)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1467)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:452)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6145)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
Xml片段:
<fragment
android:id="@+id/emojicons"
android:layout_width="match_parent"
android:layout_height="220dp"
class="ir.m.sh.textsticker.PlusOneFragment"/>
我的片段:
Android Studio PLusOneFragment
怎么了?
我希望展示和隐藏这个片段并进行测试但是......
答案 0 :(得分:0)
我猜你的片段对象是null。 试试这样:
PLusOneFragment fg ;
Button click ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tablo);
if(savedInstanceState == null)
fg = new PLusOneFragment();
else
fg = getFragmentManager().findFragmentById(R.id.emojicons);
click = (Button) findViewbyId(R.id.Button1);
click.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentManager fm = getFragmentManager();
fm.beginTransaction()
.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
.show(fg)
.commit();
}
});
或者如果你想要,你可以使用Fragment对象而不是PLusOneFragment对象,然后在初始化它时你可以像这样初始化它: 片段fg; fg = new PLusOneFragment(); (其中savedInstanceState为null);