Android 開発学習は継続的に更新されます

Android開発

単一のアクティビティインターフェイス内の操作

コントロール 1 TextView コントロールが使用するもの

フロントエンドの html+css に似ています。

コントロール 2ボタンコントロールの使用

1 まずはAndroidのキー形式について

背景やデフォルトのボタン形式や押下後のボタンの形式など
ボタンのラベルを activity_main.xml ファイルに指定します

<Button
        android:id="@+id/btn"
        android:layout_width="200dp"
        android:layout_height="100dp"
        android:background="@drawable/btn_selector"
        android:text="我是一个按钮"
        />

背景色は色を指定するか、ドロワブルファイル配下にセレクターを作成し、ボタンの背景画像を指定するなどの方法があります。
ここに画像の説明を挿入

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <!--如果被按下的画,就显示这个图片-->
    <item android:drawable="@drawable/ic_baseline_elderly_24" android:state_pressed="true"/>
    <!--默认的就是显示这个图片-->
    <item android:drawable="@drawable/ic_baseline_emoji_people_24"/>
</selector>
2 ボタン監視イベントをバインドする

まずボタンのラベルに番号を付けてから、アクティビティ クラスでボタンを取得すると、ボタンをバインドしてイベントをリッスンできます。

protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //获取事件的按键id
        Button btn = findViewById(R.id.btn);
        //对这个按键进行绑定,如单击事件
        btn.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    

            }
        });
        //绑定一个长按的一个监听事件
        btn.setOnLongClickListener(new View.OnLongClickListener() {
    
    
            @Override
            public boolean onLongClick(View v) {
    
    
                return false;
            }
        });
        //绑定一个触摸事件
        btn.setOnTouchListener(new View.OnTouchListener() {
    
    
            @Override
            public boolean onTouch(View v, MotionEvent event) {
    
    
                return false;
            }
        });

    }

2 番目のメソッドでは、ボタン タグでバインディング onclick イベントを直接指定し、同じ名前のメソッドをメイン クラスに追加できます。

ここに画像の説明を挿入
ここに画像の説明を挿入

コントロール 3 EditText テキスト ボックスの設定

Web フォームにログインするときの text 属性と同様に、いくつかのデータを入力できます。使用されるラベルは
「EditText」です。
ここに画像の説明を挿入

コントロール 4 イメージビュー

ここに画像の説明を挿入

最も重要なことは、画像のズーム タイプです
ここに画像の説明を挿入
。多くの場合、画像のサイズは画像ビューのサイズと一致しません。画像の歪みや変形を防ぐために、次の自動塗りつぶしを使用できます。画像のサイズに応じて、対応する画像フレームと一致します。
ここに画像の説明を挿入

コントロール5ProgressBarの使用

このコントロールは、進行状況、更新された小さな円、または進行状況バーを表示します。ダウンロードやページの読み込みのプロセスを表示できます。
ここに画像の説明を挿入
1 小さな円を描くように負荷をかける

<!--显示进度,此时是一个小圈圈一直转-->
    <ProgressBar
        android:id="@+id/pb1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
    <!--来一个按钮来控制加载显示与消失-->
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="显示或者隐形加载界面"
        android:onClick="pb1Change"/>

リスナー イベントをメインの起動クラスに追加する

public class MainActivity extends AppCompatActivity {
    
    

    private ProgressBar pb1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pb1 = findViewById(R.id.pb1);
    }




    public void jumpToAnother(View view) {
    
    
        startActivity(new Intent(this,MainActivity2.class));
    }

    //按键来控制进度条的显示和隐藏
    public void pb1Change(View view) {
    
    
        //如果此时是隐藏的,就显示出来
        if(pb1.getVisibility()==View.GONE){
    
    
            pb1.setVisibility(View.VISIBLE);
        }else{
    
    
            pb1.setVisibility(View.GONE);
        }
    }
}

2 プログレスバーの形式でロードする

style=“?android:attr/progressBarStylehorizo​​ntal”

<!--以进度调的方式来显示-->
    <ProgressBar
        android:id="@+id/pb2"
        style="?android:attr/progressBarStyleHorizontal"
        android:max="100"
        android:layout_width="300dp"
        android:layout_height="wrap_content"/>
<!--模拟进度调在增加-->
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="每点击一下就增加10"
        android:onClick="pb2Add"/>

メイン起動クラスにロード処理を割り当てる

/*模拟下载过程,每点击一下就增加10个单位*/
    public void pb2Add(View view) {
    
    
        int progress = pb2.getProgress();
        progress+=10;
        pb2.setProgress(progress);

    }

3 進行状況バーに進行状況が不正確に表示され、毎回小さな円のようにロードされます。

<!--像小圈圈那样加载,但是不精确的显示-->
    <ProgressBar
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:max="100"
        android:indeterminate="true"/>

コントロール6 通知通知

ここに画像の説明を挿入
ここに画像の説明を挿入以下は、通知の内容にいくつかのフォームを設定する手順です。
ここに画像の説明を挿入
1まず、通知イベントの送信またはキャンセルをバインドする 2 つのボタンを作成します。

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="发送通知"
        android:background="@color/purple_200"
        android:onClick="sendNote"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="取消发送通知"
        android:textColor="@color/white"
        android:background="@color/black"
        android:onClick="cancelNote"/>

ここに画像の説明を挿入2 メインクラスで最初に通知管理を取得し、次に通知を取得します

ここに画像の説明を挿入

public class MainActivity extends AppCompatActivity {
    
    

    
    private NotificationManager manager;
    private Notification notification;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        

        //第一步先获取到通知管理对象
         manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

         //第二步,通过builder来链式的创建notification对象
        NotificationChannel channel = null;
        //是Android8版本之后推出的因此需要进行版本的判断
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
    
    
            //第一个参数就是id,第二个参数是通知的名字,可以随便设置,第三个参数是通知的等级,有很多的等级,具体可以参照本小节第二张图。
            channel = new NotificationChannel("hai", "测试通知", NotificationManager.IMPORTANCE_HIGH);
            manager.createNotificationChannel(channel);
        }

        //新建一个activity来点击通知时进行跳转到指定的界面或者app中
        Intent intent = new Intent(this, NotificationActivity.class);
        PendingIntent pendingIntend = PendingIntent.getActivity(this, 0, intent, 0);
//对通知的内容或者形式进行修饰
        notification = new NotificationCompat.Builder(this, "hai")
                .setContentTitle("正规通知(通知的姓名)")
                .setContentText("通知的内容,你的银行卡收入100元")
                //这里是通知的一个小图标的设定,不能是rgb图片
                .setSmallIcon(R.drawable.ic_baseline_person_24)
                //设置大图标的图片,但是因为是一个bitmap格式,所以需要将图片转成bitmap格式
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.yueyue))
                //设置小图标的颜色,
                .setColor(Color.parseColor("#ff0000"))
                //这个参数是指定点击到通知之后,跳转的界面或者app中,传入的是一个PendingIntent对象
                .setContentIntent(pendingIntend)
                //这个参数是当点击通知之后,就会将通知销毁
                .setAutoCancel(true)
                .build();

    }

    //发送通知的按钮
    public void sendNote(View view) {
    
    
        manager.notify(1,notification);
    }
    //点击次按钮可以将通知给取消掉,和setAutoCancel作用相同
    public void cancelNote(View view) {
    
    
        manager.cancel(1);
    }

次にジャンプ後のアクティビティを作成し、リストに登録します。
次に、次のインターフェイスである通知の送信ボタンをクリックします。

ここに画像の説明を挿入

コントロール 7 ツールバー ページ上部のナビゲーション バー

共通のプロパティ設定
ここに画像の説明を挿入

<androidx.appcompat.widget.Toolbar
        android:id="@+id/tb1"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/purple_200"
        app:navigationIcon="@drawable/ic_baseline_west_24"

        >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="微信"
            android:layout_gravity="center"
            android:gravity="center"
            android:textSize="30dp"
            android:textColor="@color/white"

            />

    </androidx.appcompat.widget.Toolbar>

次に、メイン クラスに移動して、ナビゲーション バーの戻るイベントと進むイベントをバインドします。小さなアイコンが押されると、それに応じて応答します。
ここに画像の説明を挿入

//先获取到标签,然后再对导航栏的监听事件进行绑定
Toolbar tb1 = findViewById(R.id.tb1);

        tb1.setNavigationOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                System.out.println("返回按钮被单机了");
            }
        });

コントロール 8AlertDialog 通知ダイアログ ボックス

通常、通知は上部に表示され、特定の内容を表示するにはプルダウンする必要があります。このアラートダイアログ ボックスでは、ロック画面の後にメッセージが表示された後のインターフェイスと同様に、通知の内容を画面に表示できます。alertDialog の単純なプロパティを使用して、
ここに画像の説明を挿入
通知ボックスに表示するレイアウトを定義します。

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">
    <ImageView
        android:layout_width="300px"
        android:layout_height="200px"
        android:src="@drawable/yueyue" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="天气很好,你那边边天气怎么样啊"
        android:textSize="20dp"
        android:textColor="@color/black"
        />
</LinearLayout>
public void alertNode(View view) {
    
    
        //先获取到builder
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        //准备自定义一个布局,来给view作为参数,自定义一个布局
        View view1 = getLayoutInflater().inflate(R.layout.notification_mian, null);
        //然后通过builder进行链式的设计
        builder.setIcon(R.mipmap.ic_launcher)
                //设置通知对话框的主题
                .setTitle("通知对话框")
                //通知的内容
                .setMessage("今天是5月16号,你那边天气怎么样啊?")

                .setPositiveButton("确定按钮", new DialogInterface.OnClickListener() {
    
    
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
    
    
                        System.out.println("确定按钮被点击");
                    }
                })
                .setPositiveButton("取消按钮", new DialogInterface.OnClickListener() {
    
    
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
    
    
                        System.out.println("取消按钮被点击");
                    }
                })
                .setNeutralButton("中间按钮", new DialogInterface.OnClickListener() {
    
    
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
    
    
                        System.out.println("中间按钮被点击");
                    }
                })
                //传入自定义的布局
                .setView(view1)
                .create()
                .show();
    }

ここに画像の説明を挿入

コントロール 8PopupWindow ボタンをクリックした後、他のアクティビティにジャンプせず、このインターフェイスでウィンドウを表示します。ウィンドウは新しいレイアウトとみなすことができます。

使い方とプロパティの概要
ここに画像の説明を挿入まず、使用するウィンドウの新しいレイアウトを作成します

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@mipmap/ic_launcher"
    android:orientation="vertical">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/purple_200"

        android:text="按钮1" />
    <Button
        android:id="@+id/button2"
        android:layout_marginTop="20px"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/purple_200"
        android:text="按钮2" />
</LinearLayout>

ここに画像の説明を挿入

ページ内にボタンを作成し、そのボタンのリッスンイベントを作成すると、ボタンがクリックされるとウィンドウが表示されます。

public void showWindow(View view) {
    
    
        //获取到窗口的布局,作为对象传入到窗口中
        View windowView = getLayoutInflater().inflate(R.layout.window_view, null);
        //获取到窗口内部的按钮,并且为其创建监听事件
        Button bt1 = windowView.findViewById(R.id.button1);
        Button bt2 = windowView.findViewById(R.id.button2);
        
        //设置窗口内的布局和窗口的大小,最后一个参数是当点击空白处时,会退出弹出的window
        PopupWindow window = new PopupWindow(windowView, ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT,true);
        //k而已设置窗口的背景图
        window.setBackgroundDrawable(getResources().getDrawable(R.drawable.yueyue));
        //指定展示窗口的位置,显示在按钮的下方,或者其他的构造方法进行窗口的偏移
        window.showAsDropDown(view);
        //创建监听事件
        bt1.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                System.out.println("按钮1被点击");
                //当点击后,让其退出,可以调用dismiss方法来退出窗口
                window.dismiss();
                
            }
        });
        bt1.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                System.out.println("按钮2被点击");
                window.dismiss();
            }
        });

    }

レイアウト

基本的なコントロールを理解した後は、ページ上の要素の配置と形式を指定するレイアウトを理解する必要があります。

レイアウト 1_LinearLayout

基本操作
ここに画像の説明を挿入
ここに画像の説明を挿入

レイアウト 2 - RelativeLayout

主な機能は、追加したモジュールの位置を指定することです。指定しない場合、デフォルトで左上隅に配置されます。 共通の位置属性設定
ここに画像の説明を挿入

ここに画像の説明を挿入ここに画像の説明を挿入
ここに画像の説明を挿入

レイアウト3_FrameLayout

新しいレイアウトはそれぞれ、前のレイアウトの前に配置されます。
ここに画像の説明を挿入ここに画像の説明を挿入

4——TableLayoutフォーム表示

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:collapseColumns="1"
    >
    <TableRow >
        <Button
            android:id="@+id/button01"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="按钮1" 
        ></Button>
        <Button
            android:id="@+id/button02"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="按钮2"      
        ></Button>
        <!-- android:text="按钮2" --> 
        <Button
            android:id="@+id/button03"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="按钮3"      
        ></Button>
    </TableRow>

    <TableRow >
        <Button
            android:id="@+id/button04"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="按钮4"      
        ></Button>
        <Button
            android:id="@+id/button05"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="按钮5"      
        ></Button>
        <Button
            android:id="@+id/button06"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="按钮6"      
        ></Button>
    </TableRow>

    <TableRow >
        <Button
            android:id="@+id/button07"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="按钮7"      
        ></Button>
        <Button
            android:id="@+id/button08"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="按钮8"      
        ></Button>
        <Button
            android:id="@+id/button09"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="按钮9"      
        ></Button>
    </TableRow>    
</TableLayout>

GridLayout は上の表と同じですが、より柔軟です

ここに画像の説明を挿入

アクティビティ間を移動する

アクティビティがページであることは一応理解できましたが、複数のアクティビティページ間の相互ジャンプをどのように実現するかが問題です。
1 まず、アクティビティ インターフェイスを作成します。つまり、新しいクラスを作成し、AppCompatActivity を継承する必要があります。

public class MainActivity2 extends AppCompatActivity {
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        //重写父类的方法
        super.onCreate(savedInstanceState);
    }
}

2 メインクラスを作成した後、このクラスのレイアウト、つまり現在のインターフェイスに表示する必要があるコンテンツを作成する必要があります。 3 レイアウトを作成した後、メインクラスにレイアウトを導入する必要があり
ここに画像の説明を挿入ます

public class MainActivity2 extends AppCompatActivity {
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    
    
        //重写父类的方法
        super.onCreate(savedInstanceState);
        //引入布局
        setContentView(R.layout.activity_main2);
    }
}

4 新しいアクティビティを作成した後、コンポーネントをリスト (AndroidManifest.xml) に登録する必要があることに注意してください。
ここに画像の説明を挿入5 最初のインターフェイスでボタンを作成し、リスニング イベントをボタンにバインドし、クリックされると 2 番目のターゲット インターフェイスにジャンプします。

<Button
        android:id="@+id/btn"
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:background="@color/white"
        android:text="点我跳转到第二个activity"
        android:onClick="jumpToAnother"
        />

6メインスタートアップクラスでリスニングイベントを作成する

public void jumpToAnother(View view) {
    
    
//指定要跳转的界面
        startActivity(new Intent(this,MainActivity2.class));
    }

アニメーション: フレームごとのアニメーション、トゥイーン アニメーション、属性アニメーションの 3 種類があります。

フレームごとのアニメーションは、画像のグループをコレクションに追加するために使用され、画像をすばやく切り替えることができ、アニメーション効果を実現します。
ここに画像の説明を挿入
そうすれば、セレクター全体を直接画像として見なすことができ、背景画像としてページに直接追加して動的な効果を実現できます。これを使用する場合、セレクターを画像として使用するには、relativeLayout タグを使用する必要があることに注意してください。そしてメインクラスでそれを開始します。
ここに画像の説明を挿入

次に、メインのスタートアップクラスで起動します
ここに画像の説明を挿入

トゥイーンアニメーション:初期値と終了値、変更時間を設定ファイルに設定

Android はアニメーションを自動的に完了します。主要な属性は 4 つあります。アルファ透明度、回転回転、スケール ズーム、平行移動などです。使用するには、まず対応する xml ファイルを作成し、それを main メソッドにインポートします

ここに画像の説明を挿入

最初のタイプのアルファ タグは、透明度の変化を通じて動的な効果を表示します。

ここに画像の説明を挿入

2 番目のタイプの回転タグは、回転を通じて動的な効果を実現します。

ここに画像の説明を挿入

3 番目のタイプのスケール タグは、画像のサイズを調整することでダイナミックな効果を実現します。

ここに画像の説明を挿入

4 番目のタイプの翻訳タグは、翻訳を通じて動的な効果を実現します

ここに画像の説明を挿入
メインのスタートアップ クラスでアニメーションがどのように使用されるか。まず、リスニング イベントをターゲット画像にバインドし、リスニング イベントを使用してアニメーションを開始します。

ここに画像の説明を挿入

3 属性アニメーション: メインクラスでいくつかの属性パラメータを設定して表示プロセスを調整します。

ここに画像の説明を挿入
作成したobjectAnimatorオブジェクトにはイベント監視メソッドもあり、同時にアニメーションにリスナーをバインドし、アニメーションの開始や終了などのイベントが発生したときに何が起こるかを指定することができます。
ここに画像の説明を挿入

ViewPageは左右にスライドして異なるレイアウトの切り替えを実現します。

1 最初にさまざまなレイアウトを準備してから、アクティビティ構成ファイルで ViewPage を使用して、現在のインターフェイスに他の viewPage を追加する必要があることを伝えます。

<androidx.viewpager.widget.ViewPager
        android:id="@+id/vp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

2 メインクラス内のすべてのレイアウトレイアウトを取得し、コレクションに入れます

LayoutInflater inflater = getLayoutInflater().from(this);
        View view1 = inflater.inflate(R.layout.layout1, null);
        View view2 = inflater.inflate(R.layout.layout2, null);
        View view3 = inflater.inflate(R.layout.layout3, null);
        ArrayList<View> view = new ArrayList<>();
        view.add(view1);
        view.add(view2);
        view.add(view3);
        MyAdapter myAdapter = new MyAdapter(view);

3 作成したレイアウトを渡すには PagerAdpater を使用する必要があります レイアウトが複数あるため、コンストラクタとしてコレクションを作成してレイアウトを渡す必要があります PagerAdapter を継承する場合はメソッドを書き換えて追加する必要があります以下の図に示すように、メソッドを使用します。
ここに画像の説明を挿入

public class MyAdapter extends PagerAdapter {
    
    
    private List<View> list;
    public MyAdapter(List<View> list){
    
    
        this.list=list;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
    
    
        container.addView(list.get(position),0);
        return list.get(position);
    }

    @Override
    public int getCount() {
    
    
        return list.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
    
    
        return view==object;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
    
    
        container.removeView(list.get(position));
    }
}

最後に二人を結びつける

ViewPager vp = findViewById(R.id.vp);
        vp.setAdapter(myAdapter);

最後に、設定したアダプターを表示用の ViewPage に設定します。

ここに画像の説明を挿入上記を完了すると、左右にスライドする効果が得られます

フラグメントの使用

フラグメントは、独自のライフサイクルを持つことができる小さなアクティビティとして直感的に理解でき、フラグメントをアクティビティ内に配置して表示したり、アクティビティと同じ操作を実行したりできます。

1 フラグメントに表示するレイアウトを作成する
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textv"
        android:layout_width="match_parent"
        android:layout_height="30dp"
        android:textColor="@color/purple_200"
        android:text="今天是什么日子"
        android:layout_gravity="center"
        android:gravity="center"/>
    <Button
        android:id="@+id/lovewho"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="点我显示日期"/>

</LinearLayout>
2 フラグメント レイアウトを作成した後、レイアウト内のいくつかの要素を取得するフラグメント クラスを作成し、レイアウト内の要素を変更して取得します
public class BlankFragment1 extends Fragment {
    
    
    private View root;
    private TextView textView;
    private Button btn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    
    
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    
    
        // Inflate the layout for this fragment
        if(root==null){
    
    
            root = inflater.inflate(R.layout.fragment1, container, false);

        }
        textView = root.findViewById(R.id.textv);

        btn =root.findViewById(R.id.lovewho);
        btn.setOnClickListener(new View.OnClickListener() {
    
    
            @Override
            public void onClick(View v) {
    
    
                textView.setText("2022年5月20日,是和爱的人在一起的日子");
            }
        });
        return root;
    }
}
3 表示したい対象のアクティビティにfragmentタグを追加し、このフラグメントに対応するクラスが表示を完了できる場合のみ
<fragment android:name="com.njupt.helloandroid.BlankFragment1"
        android:id="@+id/frag1"
        android:layout_width="match_parent"
        android:layout_height="80dp"/>

上記はフラグメントの静的な表示です。複数のフラグメントを切り替えたい場合は、

フラグメントを動的に切り替える必要があります。手順は次のとおりです。

まず、表示したいアクティビティ内にfragmentLayoutを作成します。フラグメントを切り替える必要があるため、さらにフラグメントを用意し、メインアクティビティ内に表示したいフラグメントを配置するスペースを空けて、以下のようにメインアクティビティに追加する必要があります。

<FrameLayout
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="@color/purple_500"
        android:id="@+id/fragmentch">//这个id就是在主程序中获取并且将其替换的标志
    </FrameLayout>

2 番目の部分は、メイン クラスのボタンの監視イベントを取得することで、ボタンが切り替わると、異なるフラグメントが表示されます。

//准备对动态的fragment进行操作
        Button chang1 = findViewById(R.id.chang1);
        chang1.setOnClickListener(this);
        Button chang2 = findViewById(R.id.chang2);
        chang2.setOnClickListener(this);

        //准备两个fragment进行切换
    }
    @Override
    public void onClick(View v) {
    
    
        switch(v.getId()){
    
    
            case R.id.chang1:
                changeFragment(new BlankFragment());
                //传入不同的准备的fragment类即可关联到不同的fragment页面
            case R.id.chang2:
                changeFragment(new BlankFragment2());

        }

    }
    //将fragment看成一个事务
    public void changeFragment(Fragment fragment){
    
    
    //有一个fragment事务来控制事务的替换,删除和添加的操作
        FragmentManager fragManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragManager.beginTransaction();
        fragmentTransaction.replace(R.id.fragmentch,fragment);
        fragmentTransaction.addToBackStack(null);//这里是为了在返回时可以返回之前的那个fragment,
        fragmentTransaction.commit();

    }
ActivityとFragment==Bundleクラス間の通信を実現する方法

データはバンドルを介して保存され、データを保存したバンドルがフラグメントに渡され、
ここに画像の説明を挿入
ここに画像の説明を挿入
フラグメントは送信されたデータを取得します。
ここに画像の説明を挿入

フラグメントのライフサイクル

ここに画像の説明を挿入

おすすめ

転載: blog.csdn.net/m0_56184347/article/details/124780828