当前位置:网站首页>Kotlin realizes wechat interface switching (fragment exercise)

Kotlin realizes wechat interface switching (fragment exercise)

2022-07-07 10:25:00 Stubborn gawa


In order to imitate the real environment , Preconditions are configured “ WeChat ” Login interface of , The main interface is at login , One defect is that the keyboard is not recycled bug. So I began to check various blogs , It solves the function that clicking on the blank space can recycle the keyboard . And it is abstracted into a tool class ,KeyBoardUtils, Just when you want to recycle the keyboard , Click on the blank space .

1 Main login interface

<?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" android:layout_gravity="center" android:background="#B50A35" >

    <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" >
        <EditText android:id="@+id/textOfName" android:layout_marginTop="100dp" android:layout_width="300dp" android:layout_height="40dp" android:layout_gravity="center" android:hint=" Please enter a user name " android:background="@color/white" android:drawableLeft="@drawable/ic_baseline_person_24" android:drawablePadding="10dp" android:singleLine="true"/>
    </LinearLayout>

    <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_marginTop="10dp" android:gravity="center" >
        <EditText android:id="@+id/textOfPassWord" android:layout_width="278dp" android:layout_height="40dp" android:layout_gravity="center" android:background="@color/white" android:drawableLeft="@drawable/ic_baseline_lock_24" android:drawablePadding="10dp" android:hint=" Please input a password " android:inputType="textPassword" />

        <ImageView android:id="@+id/showPassword" android:layout_width="wrap_content" android:layout_height="match_parent" android:src="@drawable/ic_baseline_visibility_off_24" android:background="@color/white" android:onClick="showPassword" />

    </LinearLayout>

    <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:gravity="center" android:layout_gravity="center" >
        <TextView android:id="@+id/mess" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#DDC91F" android:gravity="center" />

        <TextView android:id="@+id/forgetPW" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#DDC91F" android:onClick="forgetPassWord" android:gravity="center" />
        <TextView android:id="@+id/register" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="#DDC91F" android:text=" First login ? Click registration " android:onClick="register" android:gravity="center" />

    </LinearLayout>

    <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:gravity="center">

        <Button android:id="@+id/surbtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="sureBtn1" android:text=" confirm "/>

        <Button android:id="@+id/btnCan" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="50dp" android:text=" Cancel "/>
    </LinearLayout>

</LinearLayout>

2 Login interface Activity, To handle the login interface , After successful login, you can jump to the wechat homepage

import android.content.Intent
import android.graphics.drawable.Drawable
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.view.MotionEvent
import android.view.MotionEvent.ACTION_DOWN
import android.view.View
import android.widget.EditText
import android.widget.ImageView

import android.widget.TextView
import androidx.annotation.CallSuper
import com.mykotlintest.util.KeyboardSetting
import com.mykotlintest.util.KeyboardUtils


class MainActivity : AppCompatActivity() {
    
        var count = 0;
        var showPassword = false
        //private lateinit var password:EditText
        lateinit var name:EditText
        override fun onCreate(savedInstanceState: Bundle?) {
    
                super.onCreate(savedInstanceState)
                setContentView(R.layout.activity_main)
                name =findViewById<EditText>(R.id.textOfName)
                name.setText(intent?.getStringExtra("username"))
        }

        fun sureBtn1(view: View) {
    
                var name =findViewById<TextView>(R.id.textOfName)
                var password = findViewById<EditText>(R.id.textOfPassWord)
                var message = findViewById<TextView>(R.id.mess)
                var forgetPW=findViewById<TextView>(R.id.forgetPW)
                /* *  Resources that require change , I hope to change from a locked state to an unlocked state , Then you can click the eye button at the back , Make the password display  * */
                var lockOpen = getDrawable(R.drawable.ic_baseline_lock_open_24)

                var text = "${name.text}"
                var text1 = "${password.text}"
                if (" Stubborn gava " == text && "hik12345" == text1) {
    
                        // message.setText(" The password or user name is $text+$text1")
                        // Set the display position , The first two parameters are the position of the upper left corner , The last two parameters are the position of the upper right corner 
                        lockOpen?.setBounds(0, 0, 40, 40)
                        password.setCompoundDrawables(lockOpen, null, null, null)
                        var intent = Intent(this@MainActivity, ThanksActivity::class.java)
                        intent.putExtra("name", text)
                        // Pass parameters to another interface 
                        startActivity(intent)
                } else {
    
                        count++
                        if (count < 10) {
    
                                message.setText(" Wrong password or user name , Do you have ${10 - count} Second chance ")
                                password.setText("")
                                forgetPW.setText(" Forget the password ? Click to retrieve ")
                        } else {
    
                                message.setText(" Locked , Please be there. 10 Try again in minutes ")
                        }
                }
        }

        fun forgetPassWord(view: View) {
    
                var intent=Intent(this,ThankAgain::class.java)
                startActivity(intent)
        }

        fun showPassword(view: View) {
    
                var password = findViewById<EditText>(R.id.textOfPassWord)

                var eye = getDrawable(R.drawable.ic_baseline_remove_red_eye_24)
                var close = getDrawable(R.drawable.ic_baseline_visibility_off_24)

                var eyeSet=findViewById<ImageView>(R.id.showPassword)
                showPassword = !showPassword
                if (showPassword) {
    

                        password.transformationMethod = HideReturnsTransformationMethod.getInstance()
                        password.setSelection(password.text.length)
                        eyeSet.setImageDrawable(eye)
                        //message.setText(" Click on it. , At this time, it is clicked to display plaintext ")
                } else {
    
                        password.transformationMethod =PasswordTransformationMethod.getInstance()
                        //message.setText(" There is a click , Need to display ciphertext ")
                        password.setSelection(password.text.length)
                        eyeSet.setImageDrawable(close)
                }
        }


        // This is the first login to register interface jump 
        fun register(view: View) {
    
                startActivity(Intent(this,RegisterActivity::class.java))
        }

        // It realizes the defect of clicking on the blank space to recycle the keyboard , It can also be removed , Does not affect the overall logic , You can add tool classes 
        @CallSuper
        override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
    
                if (ev.action == MotionEvent.ACTION_DOWN) {
    
                        val view = currentFocus
                        
                        if (KeyboardUtils.isShouldHideKeyBord(view, ev)) {
    
                                KeyboardUtils.hintKeyBoards(view)
                        }
                }
                return super.dispatchTouchEvent(ev)
        }


2.1 Tools for recycling keyboard ( It's a java file , But it can be well integrated into kotlin In file )

public class KeyboardUtils {
    
    // How to show the keyboard 
    public static void showKeyboard(View view) {
    
        InputMethodManager imm = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
    
            view.requestFocus();
            imm.showSoftInput(view, 0);
        }
    }

    /** *  Hide soft keyboard  * @param view */
    public static void hintKeyBoards(View view) {
    
        InputMethodManager manager = ((InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE));
        if (manager != null) {
    
            manager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    /** *  Determine whether it is necessary to hide  */
    public static boolean isShouldHideKeyBord(View v, MotionEvent ev) {
    
        if (v != null && (v instanceof EditText)) {
    
            int[] l = {
    0, 0};
            // Get the parent window coordinates of the current window 
            v.getLocationInWindow(l);
            int left = l[0];
            int top = l[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            return !(ev.getX() > left && ev.getX() < right && ev.getY() > top && ev.getY() < bottom);
        }
        return false;
    }
}

3 Prepare the layout of wechat homepage interface

<?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="wrap_content" android:background="@color/black" android:orientation="vertical">

        <TextView android:id="@+id/display" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/white" />


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

    <!-- Used for replacement fragment The interface of -->
    <FrameLayout android:id="@+id/content" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1">
    </FrameLayout>

    <!-- Bottom navigation bar -->
    <LinearLayout android:layout_width="match_parent" android:layout_height="70dp" android:background="@color/black">

        <!-- news -->
        <RelativeLayout android:id="@+id/messagePart" android:layout_marginTop="3dp" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1">

            <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_centerVertical="true" android:orientation="vertical">

                <ImageView android:id="@+id/messagePicture" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:background="@color/white" android:src="@drawable/ic_baseline_message_24" />

                <TextView android:id="@+id/messageText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text=" news " android:textColor="@color/white" android:textSize="15dp" />

            </LinearLayout>

        </RelativeLayout>


        <!-- Mail list -->

        <RelativeLayout android:id="@+id/addressPart" android:layout_marginTop="3dp" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@color/black">

            <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">

                <ImageView android:id="@+id/addressPicture" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:background="@color/white" android:src="@drawable/ic_baseline_group_24" />

                <TextView android:id="@+id/addressText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text=" Mail list " android:textColor="@color/white" android:textSize="15dp" />

            </LinearLayout>

        </RelativeLayout>

        <!-- Find out -->
        <RelativeLayout android:layout_marginTop="3dp" android:id="@+id/foundPart" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1">

            <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">

                <ImageView android:id="@+id/foundPicture" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:background="@color/white" android:src="@drawable/ic_baseline_widgets_24" />

                <TextView android:id="@+id/foundText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text=" Find out " android:textColor="@color/white" android:textSize="15dp" />
            </LinearLayout>

        </RelativeLayout>


        <!-- I -->

        <RelativeLayout android:layout_marginTop="3dp" android:id="@+id/mePart" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1">

            <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical">

                <ImageView android:id="@+id/mePicture" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:background="@color/white" android:src="@drawable/ic_baseline_perm_identity_24" />

                <TextView android:id="@+id/meText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text=" I " android:textColor="@color/white" android:textSize="15dp" />
            </LinearLayout>
        </RelativeLayout>

    </LinearLayout>
</LinearLayout>

Simply prepare several switching interfaces , Used to replace fragment

The first interface , The other interfaces only need to be differentiated from this interface , It's all the same way of thinking

<?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:background="@color/red" >
    <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text=" The first 1 A message interface " android:textSize="40dp" android:gravity="center" android:layout_gravity="center" />
</LinearLayout>

Main program of layout , Embedded in classes , To replace fragment operation


import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment

class MessageActivity : Fragment() {
    
        override fun onCreateView(
                inflater: LayoutInflater,
                container: ViewGroup?,
                savedInstanceState: Bundle?
        ): View? {
    
                return inflater.inflate(R.layout.message_fragment,container,false)
        }
}

4 The main interface program of wechat


import android.os.Bundle
import android.view.Window
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction

class ThanksActivity : AppCompatActivity() {
    
		// Used to get the name of the currently logged in person , Displayed on the home page , You can contact different activity The transmission of the data of 
        private lateinit var username: String
        // For all the fragment Of activity Declare variables 
        private  var messageActivity: MessageActivity? = null
        private  var addressActivity: AddressActivity?=null
        private  var foundActivity: FoundActivity?=null
        private  var myActivity: MyActivity?=null

        // Get all the elements on the homepage of wechat 
        private lateinit var messagePart:RelativeLayout
        private lateinit var messagePicture:ImageView
        private lateinit var messageText:TextView

        private lateinit var addressPart:RelativeLayout
        private lateinit var addressPicture:ImageView
        private lateinit var addressText:TextView

        private lateinit var foundPart:RelativeLayout
        private lateinit var foundPicture:ImageView
        private lateinit var foundText:TextView

        private lateinit var myPart:RelativeLayout
        private lateinit var myPicture:ImageView
        private lateinit var myText:TextView

        // The color restored before and after clicking 
        private  var touchColor=0
        private  var backColor=0
        // management 
        private lateinit var support:FragmentManager


        override fun onCreate(savedInstanceState: Bundle?) {
    
                super.onCreate(savedInstanceState)
                requestWindowFeature(Window.FEATURE_NO_TITLE)
                setContentView(R.layout.thanks_activity)

                initValues()
                support=supportFragmentManager
                changeFragmentAndColor(0)

                var display = findViewById<TextView>(R.id.display)
                var intent = intent
                username = intent.getStringExtra("name").toString()
                display.setText(""" Welcome to your username :【${
    intent.getStringExtra("name")}】 Users of """)
                // The first one is selected by default message

                // All current numbers have been initialized , Now we need to add a monitoring event to the case , If you click the corresponding place , You can change fragment
                messagePart.setOnClickListener {
    
                        changeFragmentAndColor(0)
                }
                addressPart.setOnClickListener {
    
                        changeFragmentAndColor(1)
                }
                foundPart.setOnClickListener {
    
                        changeFragmentAndColor(2)
                }
               myPart.setOnClickListener {
    
                        changeFragmentAndColor(3)
                }

        }
        fun initValues(){
    
                // The information section is initialized 
                messagePart=findViewById(R.id.messagePart)
                messagePicture=findViewById(R.id.messagePicture)
                messageText=findViewById(R.id.messageText)
                // Address book initialization 
                addressPart=findViewById(R.id.addressPart)
                addressPicture=findViewById(R.id.addressPicture)
                addressText=findViewById(R.id.addressText)
                // Found initialization 
                foundPart=findViewById(R.id.foundPart)
                foundPicture=findViewById(R.id.foundPicture)
                foundText=findViewById<TextView>(R.id.foundText)
                // My initialization 
                myPart=findViewById(R.id.mePart)
                myPicture=findViewById(R.id.mePicture)
                myText=findViewById<TextView>(R.id.meText)

                touchColor=getColor(R.color.green)
                backColor=getColor(R.color.white)

        }

        fun changeFragmentAndColor(num:Int){
    
                // Every time it starts to change fragment Before , First of all fragment Stop it , Change all the colors back 
                clearColor()
                // Then open fragment Conversion transactions , Pay attention to the use of timeless manage
                var transaction =support.beginTransaction()
                // Put the existing fragment To hide , Avoid multiple fragment Appear on an interface 
                hideAllFragments(transaction)
                // Start processing click events 
                when(num){
    
                        0->{
    
                                messagePicture.setBackgroundColor(touchColor)
                                messageText.setTextColor(touchColor)
                                // transformation activity
                                if(messageActivity==null){
    
                                        messageActivity= MessageActivity()
                                        transaction.add(R.id.content, messageActivity!!)
                                }else{
    
                                        transaction.show(messageActivity!!)
                                }

                        }
                        1->{
    
                                addressPicture.setBackgroundColor(touchColor)
                                addressText.setTextColor(touchColor)
                                // After changing the color , Load the page 
                                if(addressActivity==null){
    
                                        addressActivity=AddressActivity()
                                        transaction.add(R.id.content, addressActivity!!)
                                }else{
    
                                        transaction.show(addressActivity!!)
                                }

                        }
                        2->{
    
                                foundPicture.setBackgroundColor(touchColor)
                                foundText.setTextColor(touchColor)

                                if(foundActivity==null){
    
                                        foundActivity= FoundActivity()
                                        transaction.add(R.id.content,foundActivity!!)
                                }else{
    
                                        transaction.show(foundActivity!!)
                                }

                        }
                        3->{
    
                                myPicture.setBackgroundColor(touchColor)
                                myText.setTextColor(touchColor)
                                if(myActivity==null){
    
                                        myActivity=MyActivity()
                                        transaction.add(R.id.content,myActivity!!)
                                }else{
    
                                        transaction.show(myActivity!!)
                                }

                        }
                }
                transaction.commit()
        }
        
        // Change the color back to white 
        fun clearColor(){
    
                messagePicture.setBackgroundColor(backColor)
                messageText.setTextColor(backColor)

                addressPicture.setBackgroundColor(backColor)
                addressText.setTextColor(backColor)

                foundPicture.setBackgroundColor(backColor)
                foundText.setTextColor(backColor)

                myPicture.setBackgroundColor(backColor)
                myText.setTextColor(backColor)
        }
        
        // Will all fragment All hidden 
        fun hideAllFragments(transaction:FragmentTransaction ){
    
                if(messageActivity!=null){
    
                        transaction.hide(messageActivity!!)
                }
                if(addressActivity!=null){
    
                        transaction.hide(addressActivity!!)
                }
               if(foundActivity!=null){
    
                       transaction.hide(foundActivity!!)
               }
                if(myActivity!=null){
    
                        transaction.hide(myActivity!!)
                }
        }


}
原网站

版权声明
本文为[Stubborn gawa]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207070800575074.html