Android stuido底部導航欄使用Fragment實現切換

Android studio底部導航欄使用Fragment實現切換

大家好,我是DXZ,今天剛寫完一個使用Fragment實現切換功能的APP,很高興就和大家分享一下,APP還可以實現連接藍牙功能和語音功能,主要用來實現與藍牙模塊進行通信來獲取單片機上採集的數據和手機APP上發送數據控制單片機。再使用時首先進入搜索界面搜索藍牙設備,然後選擇自己需要連接的藍牙,連接成功後會進行語音提示,然後即可和單片機進行通信。下面展示出APP截圖和代碼。由於代碼太多,我只粘貼了一部分,需要的自己進行下載。

下面是一些APP截圖

在這裏插入圖片描述

在這裏插入圖片描述

在這裏插入圖片描述

代碼如下

MainActivity.java

package com.example.practise;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.RadioGroup;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentTransaction;


public class MainActivity extends FragmentActivity {

    private static final int LOCATION_PERMISSION = 1;
    private RadioGroup mRg_main;
    private int position;

    private List<BaseFragment> mBaseFragment;
    private Fragment mContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        initPeimission();
        initFragment();//需要先進行初始化然後再設置點擊事件監聽,否則會出現界面找不到導致程序崩潰
        setListener();


    }
    private void initPeimission() {
        if (ContextCompat.checkSelfPermission(MainActivity.this,
                Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION);
        } else {

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case LOCATION_PERMISSION:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "權限開啓成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "權限開啓失敗", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }
    private void initFragment() {
        mBaseFragment = new ArrayList<>();
        mBaseFragment.add(new CommonFrameFragment());
        mBaseFragment.add(new CustomFragment());
        mBaseFragment.add(new OtherFragment());
        mBaseFragment.add(new ThirdPartyFragment());
    }

    private void setListener(){
        mRg_main.setOnCheckedChangeListener(new MyOnCheckedChangeListener());
        mRg_main.check(R.id.rb_common_frame);
    }

    //界面初始化函數
    private void initView(){
        setContentView(R.layout.activity_main);
        mRg_main = (RadioGroup)findViewById(R.id.rg_main);
    }

    private class MyOnCheckedChangeListener implements RadioGroup.OnCheckedChangeListener {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            switch (i){
                case R.id.rb_common_frame:
                    position = 0;
                    break;
                case R.id.rb_thirdparty:
                    position = 1;
                    break;
                case R.id.rb_custom:
                    position = 2;
                    break;
                case R.id.rb_other:
                    position = 3;
                    break;
                default:
                    position = 0;
                    break;
            }

            BaseFragment to = getFragment();
            switchFrament(mContent,to);
        }
    }

    private void switchFrament(Fragment from, Fragment to) {
        if(from != to){
            mContent = to;
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            //才切換
            //判斷有沒有被添加
            if(!to.isAdded()){
                //to沒有被添加
                //from隱藏
                if(from != null){
                    ft.hide(from);
                }
                //添加to
                if(to != null){
                    ft.add(R.id.fl_content,to).commit();
                }
            }else{
                //to已經被添加
                // from隱藏
                if(from != null){
                    ft.hide(from);
                }
                //顯示to
                if(to != null){
                    ft.show(to).commit();
                }
            }
        }
    }

    private BaseFragment getFragment() {
        BaseFragment fragment = mBaseFragment.get(position);
        return fragment;
    }


}




CommonFrameFragment.java

package com.example.practise;

import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import static com.example.practise.CustomFragment.client;
import static com.example.practise.CustomFragment.isConnect;

public class CommonFrameFragment extends BaseFragment implements  TextToSpeech.OnInitListener {


    static public TextView statedevice;
    static  public  TextView devicename;
    private Button tempandhum;
    private Button light;
    private Button allshow;
    private Button allclear;
    static public TextToSpeech textToSpeech;

    @Override
    protected View initView() {
       View view = View.inflate(mContext,R.layout.commonview,null);

        statedevice = (TextView)view.findViewById(R.id.statedevice);
        devicename = (TextView)view.findViewById(R.id.devicename);

        tempandhum = (Button)view.findViewById(R.id.tempandhum);
        light = (Button)view.findViewById(R.id.light);
        allshow = (Button)view.findViewById(R.id.allshow);
        allclear = (Button)view.findViewById(R.id.allclear);


        textToSpeech = new TextToSpeech(mContext, this); // 參數Context,TextToSpeech.OnInitListener



        tempandhum.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View view) {
                 if (isConnect==false) {
                     textToSpeech.speak("未連接", TextToSpeech.QUEUE_FLUSH, null);
                 }
                 else {
                     client.send("0x01");
                 }
             }
         });


        light.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                    if (isConnect==false) {
                        textToSpeech.speak("未連接", TextToSpeech.QUEUE_FLUSH, null);
                    }
                    else {
                        client.send("0x02");
                    }
                }

        });

        allshow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isConnect==false) {
                    textToSpeech.speak("未連接", TextToSpeech.QUEUE_FLUSH, null);

                }
                else {
                    client.send("0x03");
                }
            }

        });


        allclear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isConnect==false) {
                    textToSpeech.speak("未連接", TextToSpeech.QUEUE_FLUSH, null);
                }
                else {
                    client.send("0x04");
                }
            }

        });
        return view;
    }

    @Override
    protected void initData() {
        super.initData();

    }



    @Override
    public void onInit(int i) {

    }
}

CustomFragment.java

package com.example.practise;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;

import static com.example.practise.CommonFrameFragment.devicename;
import static com.example.practise.CommonFrameFragment.statedevice;
import static com.example.practise.CommonFrameFragment.textToSpeech;

public class CustomFragment extends BaseFragment {
    private static final int LOCATION_PERMISSION = 1;
    private static final int REQUEST_DISCOVERABLE = 2;

    private ListView listView;


    private List<String> listDevice;

    private ArrayAdapter<String> mAdapter;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothReceiver receiver;
    static public  BlueToothTool client;


    static public boolean isConnect=false;//藍牙是否連接成功
    @Override
    protected View initView() {
        View view = View.inflate(mContext,R.layout.bluetooth,null);


        listView = (ListView) view.findViewById(R.id.listview);


        EnableBluetooth();
        return view;
    }

    @Override
    protected void initData() {
        super.initData();

        listDevice = new ArrayList<>();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String str = listDevice.get(position);
                String macAdress = str.split("\\|")[1];
                BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(macAdress);
                client = new BlueToothTool(device, handler);
                try {
                    client.connect();
                } catch (Exception e) {
                    Log.e("TAG", e.toString());
                }
            }
        });




    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        switch (requestCode) {
            case REQUEST_DISCOVERABLE:
                if (resultCode == Activity.RESULT_CANCELED) {
                    Toast.makeText(mContext, "藍牙未開啓", Toast.LENGTH_SHORT).show();
                    textToSpeech.speak("藍牙未開啓", TextToSpeech.QUEUE_FLUSH, null);
                    EnableBluetooth();
                } else {
                    Toast.makeText(mContext, "藍牙開啓成功", Toast.LENGTH_SHORT).show();
                    textToSpeech.speak("藍牙開啓成功", TextToSpeech.QUEUE_FLUSH, null);
                    mBluetoothAdapter.startDiscovery();
                }
                break;
            default:
                break;
        }
    }
    private void EnableBluetooth() {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Intent enable = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        enable.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
        startActivityForResult(enable, REQUEST_DISCOVERABLE);

    }


    private class BluetoothReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String str = device.getName() + "|" + device.getAddress();
                if (listDevice.indexOf(str) == -1) {  //防止重複添加
                    listDevice.add(str);
                }
                if (mAdapter != null) {
                    mAdapter.notifyDataSetChanged();
                }
                showDevices();
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {

            }
        }

    }

    private void showDevices() {
        mAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1,
                listDevice);
        listView.setAdapter(mAdapter);
    }

    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case BlueToothTool.CONNECT_FAILED:
                    Toast.makeText(mContext, "連接失敗", Toast.LENGTH_SHORT).show();
                    textToSpeech.speak("連接失敗", TextToSpeech.QUEUE_FLUSH, null);
                    break;
                case BlueToothTool.CONNECT_SUCCESS:
                    Toast.makeText(mContext, "連接成功", Toast.LENGTH_SHORT).show();
                    textToSpeech.speak("連接成功", TextToSpeech.QUEUE_FLUSH, null);
                    statedevice.setText("已連接");
                    devicename.setText(client.getAddress());
                    client.receive();
                    isConnect=true;
                    break;
                case BlueToothTool.READ_FAILED:
                    Toast.makeText(mContext, "讀取失敗", Toast.LENGTH_SHORT).show();
                    break;
                case BlueToothTool.WRITE_FAILED:
                    Toast.makeText(mContext, "發送失敗", Toast.LENGTH_SHORT).show();
                    break;
                case BlueToothTool.PIPEI_SUCCESS:
                    Toast.makeText(mContext, "正在連接", Toast.LENGTH_SHORT).show();
                    textToSpeech.speak("正在連接", TextToSpeech.QUEUE_FLUSH, null);
                    break;
                case BlueToothTool.PIPEI_FAILED:
                    Toast.makeText(mContext, "連接失敗", Toast.LENGTH_SHORT).show();

                    break;
                case BlueToothTool.DATA:

                    break;


            }
        }
    };
    @Override
    public void onResume() {  //註冊廣播接收器
        super.onResume();
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        receiver = new BluetoothReceiver();
        mContext.registerReceiver(receiver,filter);
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        mContext.registerReceiver(receiver,filter);
    }

    @Override
    public void onDestroy() {  //註銷廣播接收器,關閉藍牙
        mContext.unregisterReceiver(receiver);
        mBluetoothAdapter.disable();
        super.onDestroy();
    }
    Runnable mRunnable = new Runnable() {
        @Override
        public void run() {
             try {
                 client.receive();
             }catch (Exception e){

             }
        }
    };
}



OtherFragment.java

package com.example.practise;

import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

public class OtherFragment extends BaseFragment {
    private TextView textView;

    @Override
    protected View initView() {

        textView = new TextView(mContext);
        textView.setTextSize(20);
        textView.setGravity(Gravity.CENTER);
        textView.setTextColor(Color.RED);
        return textView;
    }

    @Override
    protected void initData() {
        super.initData();
        textView.setText("其他頁面");
    }
}

ThirdPartyFragment.java

package com.example.practise;

import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.TextView;

public class ThirdPartyFragment extends BaseFragment {
    private TextView textView;
    private TextView body;

    @Override
    protected View initView() {
     View view = View.inflate(mContext,R.layout.user,null);
        body = (TextView)view.findViewById(R.id.body);
        body.setMovementMethod(ScrollingMovementMethod.getInstance());
        return view;
    }

    @Override
    protected void initData() {
        super.initData();

    }
}

BaseFragment.java

package com.example.practise;


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

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public abstract class BaseFragment extends Fragment {
    /**
     * 上下文
     */
    protected Context mContext;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return initView();
    }

    /**
     * 強制子類重寫,實現子類特有的ui
     * @return
     */
    protected abstract View initView();

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

        initData();
    }

    /**
     * 當孩子需要初始化數據,或者聯網請求綁定數據,展示數據的 等等可以重寫該方法
     */
    protected void initData() {

    }
}


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=".MainActivity">

    <include layout="@layout/titlebar"></include>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:id="@+id/fl_content"
        ></FrameLayout>

    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ff005b"
        android:id="@+id/rg_main"
        android:gravity="center_vertical"
        android:orientation="horizontal"
        android:padding="5dp"
        >
    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/rb_common_frame"
        style="@style/bottomstyle"
        android:drawableTop="@drawable/rb_common_frame_drawable_selector"
        android:text="顯示"
        ></RadioButton>

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/bottomstyle"
            android:drawableTop="@drawable/rb_thirdparty_drawable_selector"
            android:id="@+id/rb_thirdparty"
            android:text="搜索"
            ></RadioButton>

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/bottomstyle"
            android:drawableTop="@drawable/rb_custom_drawable_selector"
            android:id="@+id/rb_custom"
            android:text="設置"
            ></RadioButton>

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/bottomstyle"
            android:drawableTop="@drawable/rb_other_drawable_selector"
            android:id="@+id/rb_other"
            android:text="使用"
            ></RadioButton>
    </RadioGroup>
</LinearLayout>

CommonView.XML

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

    >

    <Button
        android:id="@+id/tempandhum"
        android:layout_width="55dp"
        android:layout_height="55dp"
        android:layout_marginLeft="40dp"
        android:layout_marginTop="430dp"
        android:background="@drawable/button_selector"
        android:text="顯示溫溼"
        android:textColor="#ff005b"
        android:textSize="19sp"></Button>

    <Button
        android:id="@+id/light"
        android:layout_width="55dp"
        android:layout_height="55dp"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="430dp"
        android:layout_toRightOf="@+id/tempandhum"
        android:background="@drawable/button_selector"
        android:text="顯示光強"
        android:textColor="#ff005b"
        android:textSize="19sp"></Button>

    <Button
        android:id="@+id/allshow"
        android:layout_width="55dp"
        android:layout_height="55dp"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="430dp"
        android:layout_toRightOf="@+id/light"
        android:background="@drawable/button_selector"
        android:text="全部顯示"
        android:textColor="#ff005b"
        android:textSize="19sp"></Button>

    <Button
        android:id="@+id/allclear"
        android:layout_width="55dp"
        android:layout_height="55dp"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="430dp"
        android:layout_toRightOf="@+id/allshow"
        android:background="@drawable/button_selector"
        android:text="全部關閉 "
        android:textColor="#ff005b"
        android:textSize="19sp"></Button>

    <com.example.practise.Cheek
        android:id="@+id/cheek"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></com.example.practise.Cheek>

    <com.example.practise.TempertaureDataView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></com.example.practise.TempertaureDataView>

    <com.example.practise.HumidityDataView
        android:id="@+id/HumidityDataView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></com.example.practise.HumidityDataView>

    <com.example.practise.LightDataView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></com.example.practise.LightDataView>

    <TextView
        android:id="@+id/state"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="32dp"
        android:layout_marginTop="380dp"
        android:text="狀態:"
        android:textColor="#ff005b"
        android:textSize="19sp"></TextView>

    <TextView
        android:id="@+id/statedevice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/state"
        android:layout_toRightOf="@+id/state"
        android:text="未連接"
        android:textColor="#ff005b"
        android:textSize="19sp"></TextView>

    <TextView
        android:id="@+id/device"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/statedevice"
        android:layout_marginLeft="20dp"
        android:layout_toRightOf="@+id/statedevice"
        android:text="設備:"
        android:textColor="#ff005b"
        android:textSize="19sp"></TextView>

    <TextView
        android:id="@+id/devicename"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@+id/device"
        android:layout_toRightOf="@+id/device"
        android:text="請連接藍牙設備"
        android:textColor="#ff005b"
        android:textSize="19sp"
        ></TextView>
</RelativeLayout>

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