[Android learning] 3. Use fragments to switch modules in the setting interface

Use dynamic fragment switching, ListView RecyclerView control and wifiManager to realize the basic setting page and wireless network page, summarize and deepen the exercise.

Design Interface Diagram

 

 Basic idea analysis

1. Firstly, the fixed part is displayed in the main layout, and the middle part is switched between dynamic fragments by introducing FrameLayout/layout.

2. The background image of the button, select the button to switch the effect.

3. Return key to return to the previous page.

code part

layout file

Main layout:

<?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"
    >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/background"
        android:orientation="vertical">
        //-------------设置那一行----------------//

        //------------------下划线一行-----------------------//

        <LinearLayout
            android:id="@+id/top_bar"
            android:layout_width="match_parent"
            android:layout_height="135dp"
            android:layout_marginTop="50dp"
            android:layout_weight="1"
            android:orientation="horizontal">

            //"《"那一行

            <Button
                android:id="@+id/Button_back"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_gravity="center"
                android:layout_weight="1"
                android:background="@null"
                android:gravity="center"
                android:text='&lt;'
                android:textColor="#181919"
                android:textSize="40dp" />

            //"设置"字符设定

            <TextView
                android:id="@+id/txt_top"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_gravity="center"
                android:layout_marginRight="150dp"
                android:layout_weight="7"
                android:gravity="center"
                android:text="设置"
                android:textColor="#181919"
                android:textSize="60dp" />

        </LinearLayout>

        <FrameLayout
            android:id="@+id/fg_content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_weight="5"
            android:background="@drawable/background"
            android:layout_margin="80dp"/>

        <View
            android:id="@+id/bottom_bar"
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginTop="10dp"
            android:layout_marginLeft="50dp"
            android:layout_marginRight="50dp"
            android:background="#181919" />

        //------------------输入源一行------------------------//

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="120dp"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="10dp"
            android:layout_weight="1"
            android:orientation="horizontal"
            android:layout_gravity="center"
            android:gravity="center">

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:background="@null"
                android:gravity="center"
                android:text="输入源"
                android:textColor="#181919"
                android:textSize="25dp" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:background="@null"
                android:gravity="center"
                android:text="投屏指南"
                android:textColor="#181919"
                android:textSize="25dp" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:background="@null"
                android:gravity="center"
                android:text="设置"
                android:textColor="#181919"
                android:textSize="25dp" />
        </LinearLayout>


    </LinearLayout>


</LinearLayout>

Focus: Set the difference between background selected and non-selected images. FrameLayout is added to the main layout to dynamically load fragments.

FirstFragment layout file

<?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="120dp"
    android:layout_gravity="center"
    android:background="@drawable/background"
    android:gravity="bottom"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/txt_device"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@drawable/tab_menu_bg"
        android:drawableTop="@drawable/tab_menu_device"
        android:gravity="center"
        android:text="已绑定设备"
        android:textColor="@drawable/tab_words_color"
        android:textSize="25dp" />

    <TextView
        android:id="@+id/txt_bluetooth"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:background="@drawable/tab_menu_bg"
        android:drawableTop="@drawable/tab_menu_bluetooth"
        android:gravity="center"
        android:text="蓝牙键鼠"
        android:textColor="@drawable/tab_words_color"
        android:textSize="25dp" />

    <TextView
        android:id="@+id/txt_network"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:background="@drawable/tab_menu_bg"
        android:drawableTop="@drawable/tab_menu_network"
        android:gravity="center"
        android:text="无线网络"
        android:textColor="@drawable/tab_words_color"
        android:textSize="25dp" />

    <TextView
        android:id="@+id/txt_updata"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:layout_weight="1"
        android:background="@drawable/tab_menu_bg"
        android:drawableTop="@drawable/tab_menu_updata"
        android:gravity="center"
        android:text="系统和更新"
        android:textColor="@drawable/tab_words_color"
        android:textSize="25dp" />


</LinearLayout>

focus point:

Insert pictures and text in TextView;

FirstFragment code:

package com.example.fragmenthomework;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import org.w3c.dom.Text;

public class FirstFragment extends Fragment implements View.OnClickListener{
    // UI Object
    private TextView txt_device;
    private TextView txt_bluetooth;
    private TextView txt_network;
    private TextView txt_updata;
    private Button button_back;
    private FrameLayout frameLayout;
    private View view;

    //fragment Object
    private FirstFragment firstFragment;
    private SecondFragment secondFragment;
    private FragmentManager fManager;

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_setting,container,false);
        fManager = getFragmentManager();
        bindview();
        setSelected();
        return view;
    }
    //----------------------------UI组件初始化与事件绑定---------------------------//
    private void bindview(){
        txt_device = (TextView) view.findViewById(R.id.txt_device);
        txt_bluetooth = (TextView) view.findViewById(R.id.txt_bluetooth);
        txt_network = (TextView) view.findViewById(R.id.txt_network);
        txt_updata = (TextView) view.findViewById(R.id.txt_updata);
        button_back = (Button) view.findViewById(R.id.Button_back);
        frameLayout = (FrameLayout) view.findViewById(R.id.fg_content);

        txt_device.setOnClickListener(this);
        txt_bluetooth.setOnClickListener(this);
        txt_network.setOnClickListener(this);
        txt_updata.setOnClickListener(this);

    }
    //----------------------------设定初始值为未选中------------------------------//
    private void setSelected(){
        txt_device.setSelected(false);
        txt_bluetooth.setSelected(false);
        txt_network.setSelected(false);
        txt_updata.setSelected(false);
    }
    //--------------------------------设置点击事件--------------------------------//
    @Override
    public void onClick(View v) {
        FragmentTransaction fragmentTransaction = fManager.beginTransaction();
        switch (v.getId()){
            case R.id.txt_network:
                setSelected();
                txt_network.setSelected(true);
                if(secondFragment == null) {
                    secondFragment = new SecondFragment();
                    fragmentTransaction.add(R.id.fg_content,secondFragment);

                }else fragmentTransaction.show(secondFragment);
                break;
            case R.id.txt_bluetooth:
                setSelected();
                txt_bluetooth.setSelected(true);
                break;
            case R.id.txt_device:
                setSelected();
                txt_device.setSelected(true);
                break;
            case R.id.txt_updata:
                setSelected();
                txt_updata.setSelected(true);
                break;
        }
        fragmentTransaction.commit();
    }
}

Focus: Set the click event of textview! The method of dynamically loading fragments using fragmentManager! Only the wireless network function is written here, and other jumps will not be added for the time being!

SecondFragment layout file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@drawable/background"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    //------------------RecyclerView-------------------//
<!--    <androidx.recyclerview.widget.RecyclerView-->
<!--        android:id="@+id/recyclerlist_view"-->
<!--        android:layout_width="match_parent"-->
<!--        android:layout_height="match_parent"-->
<!--        android:layout_marginTop="40dp"/>-->
    //--------------------ListView----------------------//
    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center"/>
</LinearLayout>

Points of attention: Only ListView is used here, and the corresponding RecylcerView can remove the comments in Fragment and layout files!

SecondFragment activity code:

package com.example.fragmenthomework;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;

public class SecondFragment extends Fragment {
    private View view;
    private IntentFilter intentFilter;
    private ListView listView;
    private RecyclerView recyclerView;
    private List<ScanResult> scanResults;
    private WifiListAdapter wifiListAdapter;
    private WifiRecyclerListAdapter wifiRecyclerListAdapter;
    private WifiManager wifiManager;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_wireless, container, false);
        InitBroadcast();

        //-------------------ListView----------------------Config---------------------------------------------//
        wifiListAdapter = new WifiListAdapter(SecondFragment.this,R.layout.wifi_list_item,scanResults);
        listView = (ListView) view.findViewById(R.id.list_view);
        listView.setAdapter(wifiListAdapter);
        //-------------------RecyclerView------------------Config---------------------------------------------//
//        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerlist_view);
//        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
//        recyclerView.setLayoutManager(layoutManager);

        return view;
    }

    //-----------------------------对WIFI权限/Broadcast进行注册------------------------------//
    private void InitBroadcast(){
        String[] PERMS_INITIAL={Manifest.permission.ACCESS_FINE_LOCATION};
        requestPermissions(PERMS_INITIAL,127);
        IntentFilter filter =new IntentFilter();
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        getActivity().registerReceiver(mReceiver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().unregisterReceiver(mReceiver);
    }
    private void search(){
        if (!wifiManager.isWifiEnabled()) wifiManager.setWifiEnabled(true);
        wifiManager.startScan();
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            wifiManager = (WifiManager) getActivity().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            search();
            final String action = intent.getAction();
            if(intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION))
            {
//                Log.w("BBB", "SCAN_RESULTS_AVAILABLE_ACTION");
                List<ScanResult> scanResults = wifiManager.getScanResults();
//                Log.w("BBB","SIZE:"+scanResults.size() );
                List<ScanResult> list = new ArrayList<>();
                wifiListAdapter.clear();
                //----------------------------将重复的SSID删除掉------------------------------------------//
                for (int i = 0; i < scanResults.size(); i++) {
                    int position = getItemPosition(list, scanResults.get(i));
                    if (position != -1) {
                        //已在列表
                        //相同SSID热点,取信号强的
                        if (list.get(position).level < scanResults.get(i).level) {
                            list.remove(position);
                            list.add(position, scanResults.get(i));
                        }
                    } else {
                        list.add(scanResults.get(i));
                    }
                }
                wifiListAdapter.addAll(list);
//                wifiRecyclerListAdapter = new WifiRecyclerListAdapter(list);
//                recyclerView.setAdapter(wifiRecyclerListAdapter);
            }
            else if(action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)){
                Log.w("BBB", "WifiManager.WIFI_STATE_CHANGED_ACTION");
            }
        }
    };
    private int getItemPosition(List<ScanResult>list, ScanResult item) {
        for (int i = 0; i < list.size(); i++) {
            if (item.SSID.equals(list.get(i).SSID)) {
                return i;
            }
        }
        return -1;
    }

}

focus point:

Use WIFIManager in combination with broadcasting to perform WIFI search function; insert into ListView space through ListViewAdapter.

listViewAdapter code:

package com.example.fragmenthomework;

import android.net.wifi.ScanResult;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.List;


public class WifiListAdapter extends ArrayAdapter<ScanResult> {

    private final LayoutInflater mInflater;
    private int mResource;

    public WifiListAdapter(SecondFragment context, int resource, List<ScanResult> scanResults) {
        super(context.getActivity(), resource);
        mInflater = LayoutInflater.from(context.getActivity());
        mResource = resource;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view;
        ViewHolder viewHolder;
        if (convertView == null) {
            view = LayoutInflater.from(getContext()).inflate(mResource, parent, false);
            viewHolder = new ViewHolder();
            viewHolder.wifiName = (TextView) view.findViewById(R.id.wifi_name);
            viewHolder.wifiSignal = (TextView) view.findViewById(R.id.wifi_signal);
            viewHolder.wifiencrypt = (TextView) view.findViewById(R.id.wifi_pass);
            view.setTag(viewHolder);
        } else {
            view = convertView;
            viewHolder = (ViewHolder) view.getTag();
        }

        //-----------------通过读取ScanResults对ListView中的文本进行赋值/判断信号强弱------------------//
        ScanResult scanResult = getItem(position);
        viewHolder.wifiName.setText(scanResult.SSID);
        int level = scanResult.level;
        if (level <= 0 && level >= -50) viewHolder.wifiSignal.setText("信号很好");
        else if (level < -50 && level >= -70) viewHolder.wifiSignal.setText("信号较好");
        else if (level < -70 && level >= -80) viewHolder.wifiSignal.setText("信号一般");
        else if (level < -80 && level >= -100) viewHolder.wifiSignal.setText("信号较差");
        else viewHolder.wifiSignal.setText("信号很差");
        //----------------------------通过读取ScanResults判断是否加密------------------------------//
        String capabilities = scanResult.capabilities;
        if (capabilities.contains("WPA") || capabilities.contains("wpa") ||
                capabilities.contains("WEP") || capabilities.contains("wep")) {
            viewHolder.wifiencrypt.setBackgroundResource(R.drawable.wifi_encryption_ic_222x);
        } else viewHolder.wifiencrypt.setBackgroundResource(R.drawable.wifi_no_encryption_ic_222x);

        return view;
    }

    //----------------------------------ViewHolder创建对实例进行缓存--------------------------//
    class ViewHolder {
        TextView wifiencrypt;
        TextView wifiName;
        TextView wifiSignal;
    }
}

Concern: The getView method of ListViewAdpter passes the encrypted WIFIname signal scanned in ScanList to it.

MainActivity code:

package com.example.fragmenthomework;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

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

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;

import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    //UI object
    private Button button_back;

    //Fragment object
    private SecondFragment secondFragment;
    private FirstFragment firstFragment;
    private FragmentManager fManager;
    //Broadcast object


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) actionBar.hide();
        setContentView(R.layout.activity_main);
        bindviews();
        InitFragment();
    }

    //-------------------------------点击事件绑定---------------------------------//
    private void bindviews() {
        button_back = (Button) findViewById(R.id.Button_back);

        button_back.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        FragmentTransaction fragmentTransaction = fManager.beginTransaction();
        switch (v.getId()) {
            case R.id.Button_back:
                if (firstFragment == null) {
                    InitFragment();
                } else fragmentTransaction.show(firstFragment);
                if (secondFragment != null) fragmentTransaction.hide(secondFragment);
                break;
        }
        fragmentTransaction.commit();
    }

    //------------------------------对FrameLayout进行初始化-----------------------//
    private void InitFragment() {
        fManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fManager.beginTransaction();
        fragmentTransaction.replace(R.id.fg_content, new FirstFragment());
        fragmentTransaction.commit();
    }
}

There are many shortcomings in learning for newcomers, thank you for your advice!

Guess you like

Origin blog.csdn.net/qq_43542689/article/details/127213088