あなたの質問では、まだ断片について読む必要があることがわかります。 フラグメント
は、独自のライフサイクルを持ち、独自の入力イベントを受け取り、アクティビティの実行中に追加または削除することができるため、フラグメントからアクティビティに移動することはできません別のアクティビティで再利用できる「サブアクティビティ」のように)
フラグメントを置き換えて、同じアクティビティで別のフラグメントを使用することはできますが、 あなたはこのようにそれを行うことができます。
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/frgContainer"
android:layout_margin="20dp"
android:background="#00e6ff">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btn"
android:text="btn"
/>
</LinearLayout>
がされる2つの新しい活動を作成します。メインの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.hackeru.mydynamicfragment.Login">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="User Name"
android:id="@+id/txtLoginUser"
android:layout_marginLeft="20sp"
android:layout_marginRight="20sp"
android:layout_marginTop="80dp"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:id="@+id/txtLoginPass"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/btnLogin"
android:text="Login"
/>
</LinearLayout>
オーバーライドのonCreateあなたが作成したフラグメントと現在のレイアウトを置き換えるか、追加するためのメインでのonClick方法でフラグメント
public class Login extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_login,container,false);
}
4.useのfragmentTransactionの方法:
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager fragmentManager =getFragmentManager();
// we must handle the callback fragment process
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
Login loginFragment = new Login();
fragmentTransaction.add(R.id.frgContainer,loginFragment);
// fragmentTransaction.replace if there is another fragment you
// wish to replace
fragmentTransaction.commit();
}
これを読んでください:
フラグメント内でフラグメントトランザクションを実行しないでください。1つのインタフェースを記述し、それをアクティビティに実装し、フラグメントトランザクションを実行する必要があります。 –