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>

  • 7
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
使用Fragment实现底部导航栏的跳转,您需要执行以下步骤: 1. 在您的项目中创建一个BottomNavigationView对象,它将用于显示底部导航栏。 2. 创建多个Fragment类,每个类都代表底部导航栏的一个选项。 3. 在您的Activity类中,创建一个FragmentManager对象并使用beginTransaction()方法开始一个新的FragmentTransaction。 4. 在FragmentTransaction中,使用add()方法将您的第一个Fragment添加到Activity中。同时,将BottomNavigationView的setOnNavigationItemSelectedListener()方法定义为一个监听器,以便在用户点击底部导航栏时执行相应的操作。 5. 在监听器中,使用replace()方法切换到用户选择的Fragment。 以下是一个简单的示例代码,可以帮助您更好地理解如何使用Fragment实现底部导航栏的跳转: ``` public class MainActivity extends AppCompatActivity { private BottomNavigationView bottomNavigationView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bottomNavigationView = findViewById(R.id.bottom_navigation); // 设置默认选中项 bottomNavigationView.setSelectedItemId(R.id.navigation_home); // 设置监听器 bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { Fragment fragment; switch (menuItem.getItemId()) { case R.id.navigation_home: fragment = new HomeFragment(); break; case R.id.navigation_dashboard: fragment = new DashboardFragment(); break; case R.id.navigation_notifications: fragment = new NotificationsFragment(); break; default: return false; } getSupportFragmentManager() .beginTransaction() .replace(R.id.fragment_container, fragment) .commit(); return true; } }); } } ``` 在这个例子中,我们首先获取了一个BottomNavigationView对象,并将其与我们的布局文件关联。我们还设置了默认选中项并添加了一个监听器。 在监听器中,我们使用了一个switch语句来确定用户选择了哪个选项。然后我们创建了相应的Fragment,并使用replace()方法将其添加到Activity中。 请注意,我们使用了一个FrameLayout来承载我们的Fragment。您需要在布局文件中添加一个类似的视图,以便能够动态添加和删除Fragment。 希望这可以帮助您开始使用Fragment实现底部导航栏的跳转。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值