Android Fragment

在 Activity 中添加 Fragment

向 Activity 中添加 Fragment,有两种方法:一种是直接在布局文件中添加,将 Fragment 作为
Activity 整个布局的一部分;另一种是当 Activity 运行时,将 Fragment 放入 Activity 布局中。

布局




代码

DetailFragment details = new DetailFragment(); //实例化DetailFragment的对象
FragmentTransaction ft = getFragmentManager()
.beginTransaction(); //获得一个FragmentTransaction的实例
ft.add(android.R.id.content, details); //添加一个显示详细内容的Fragment
ft.commit(); //提交事务

示例:

入口类

 
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

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

        ImageView i1 = findViewById(R.id.a1);
        ImageView i2 = findViewById(R.id.a2);
        ImageView i3 = findViewById(R.id.a3);
        i1.setOnClickListener(this);
        i2.setOnClickListener(this);
        i3.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        //获取fragment
         FragmentManager fm=getSupportFragmentManager();
        //开启一个事务
         FragmentTransaction ft=fm.beginTransaction();
        //初始化fragment
        Fragment f=null;

        switch (v.getId()){
            case R.id.a1:
                f=new WeChatFragment() ;
                Toast.makeText(getApplicationContext(), "a1", Toast.LENGTH_LONG).show();
                break;
            case R.id.a2:
                f=new MeFragment();
                break;
            case R.id.a3:
                f=new MsgFragment();
                break;
            default:
                break;
        }

        ft.replace(R.id.fragment, f);  //替换fragment
        ft.commit(); //提交事务


    }
}

主布局




    
    

        

        

        


    

Fragment碎片


import android.os.Bundle;

import androidx.fragment.app.Fragment;

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

public class MeFragment extends Fragment {


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_me, container, false);
    }
}

碎片布局




    
    

注意项

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
         //获取fragment
         FragmentManager fm=getSupportFragmentManager();
        //开启一个事务
         FragmentTransaction ft=fm.beginTransaction();
 android:background="@color/white"

你可能感兴趣的:(Android,android,android,studio)