【发布时间】:2021-10-10 20:50:47
【问题描述】:
我检查了一些问题并进行了我认为必要的更改,但每次我按下按钮替换片段时应用程序仍然崩溃。片段具有通常的代码,仅用于简单的布局。在启动时,Activity 将显示我首先添加的片段。
这是我的 MainActivity:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final FragmentLogin fl = new FragmentLogin();
final FragmentRegistration fr = new FragmentRegistration();
final android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
final android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragcon, fr);
fragmentTransaction.commit();
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(fl.isVisible())
{
fl.onActivityCreated(savedInstanceState);
fragmentTransaction.replace(R.id.fragcon, fr);
fragmentTransaction.commit();
}
else {
fl.onActivityCreated(savedInstanceState);
fragmentTransaction.replace(R.id.fragcon, fl);
fragmentTransaction.commit();
}
}
});
}
}
这是我的 activitymain.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.aditya.registrationnlogin.MainActivity">
<RelativeLayout
android:id="@+id/fragcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1.8"
android:layout_gravity="center_horizontal">
</RelativeLayout>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="SWITCH" />
</LinearLayout>
【问题讨论】:
标签: android android-layout android-fragments