Fragment模板

Main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:id="@+id/container">


</FrameLayout>
package com.example.learnfragment;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (savedInstanceState == null) {
            getSupportFragmentManager()
                    .beginTransaction()
                    .add(R.id.container, new MainFragment())
                    .commit();
        }

    }
}
package com.example.learnfragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.fragment.app.Fragment;

/**
 * MainFragment 主Fragment
 * @author codingblock 2015/09/14
 *
 */
public class MainFragment extends Fragment {

    public MainFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        rootView.findViewById(R.id.btn_show_other).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                getFragmentManager()
                        .beginTransaction()
                        .addToBackStack(null)  //將當前fragment加入到返回棧中
                        .replace(R.id.container, new OtherFragment()).commit();
            }
        });
        return rootView;
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
         android:id="@+id/tv_show"
         android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="這是另一個Fragment" />

      <Button
          android:id="@+id/btn_back"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="返回" />

</LinearLayout>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章