溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Android切近實(shí)戰(zhàn)(二)

發(fā)布時(shí)間:2020-06-12 17:27:24 來(lái)源:網(wǎng)絡(luò) 閱讀:1012 作者:BruceAndLee 欄目:移動(dòng)開發(fā)

上篇文章我們的那個(gè)登陸界面比較簡(jiǎn)陋,這篇文章稍微對(duì)這塊進(jìn)行了修改,如下

Android切近實(shí)戰(zhàn)(二)

看到那個(gè)文本框中的圖片和文本框中的文字了嗎

<EditText android:id="@+id/txtUserName"
            android:hint="@string/hintInputUserNo"
            android:layout_width="fill_parent"
            android:drawableLeft="@drawable/user"
            android:layout_height="wrap_content"
            android:singleLine="true">
            </EditText>

圖片就是上面代碼中的drawableLeft這個(gè)屬性來(lái)設(shè)置,而文字則是通過(guò)android:hint來(lái)設(shè)置

其文字是設(shè)置在string.xml中

Android切近實(shí)戰(zhàn)(二)

內(nèi)容如下

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">個(gè)人理財(cái)</string>
    <string name="app_LoginName">用戶登錄</string>
    <string name="labUserName">用戶名:</string>
    <string name="labPwd">密    碼:</string>
    <string name="labRePwd">重復(fù)密碼:</string>
    <string name="labRole">角色:</string>
    <string name="labAdmin">管理員</string>
    <string name="btnLoginText">登  錄</string>
    <string name="hintInputUserNo">請(qǐng)輸入您的用戶名</string>
    <string name="hintInputUserPwd">請(qǐng)輸入您的密碼</string>
    <string name="hintInputUserRePwd">請(qǐng)?jiān)俅屋斎肽拿艽a</string>
    <string name="labColrLogin">#fff000</string>
    <string name="btnCancelText">取消</string>
    <string name="btnSure">確定</string>
    <string name="btnUserReg">用戶注冊(cè)</string>
    <string name="btnSysCode">系統(tǒng)參數(shù)</string>
    <string name="btnDataBackup">數(shù)據(jù)備份</string>
    <string name="labWelCome">歡迎您,</string>
    <string name="chkDisplayPwd">顯示密碼</string>
    <string name="WarningMsgTitle">提示</string>
    <string name="UserNoIsEmpty">用戶名不能為空!</string>
    <string name="UserPWdIsEmpty">密碼不能為空!</string>
    <string name="UserRepwdIsNotCorrect">重復(fù)密碼和密碼不一致!</string>
    <string name="SaveSuccess">保存成功!</string>
    <string name="PwdLengthIsNotCorrect">密碼長(zhǎng)度必須介于6到15位!</string>
</resources>

OK,通過(guò)設(shè)置android:hint="@string/hintInputUserNo"就可以實(shí)現(xiàn)水印效果。


OK,今天來(lái)看一下登錄成功的界面以及功能

Android切近實(shí)戰(zhàn)(二)

首先是登錄成功后,會(huì)將登錄用戶的用戶名傳遞給上面的界面。

public class index extends Activity {
    TextView labUser;
    ImageButton imgBtnUserRegister;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.index);
        labUser = (TextView) this.findViewById(R.id.labUser);
        imgBtnUserRegister=(ImageButton)this.findViewById(R.id.imgBtnUserRegister);
        imgBtnUserRegister.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(index.this,userregister.class);
                startActivityForResult(intent, 0);
            }
        });
        Init();
    }
    private void Init() {
        Bundle bundle = getIntent().getExtras();
        String userNo = bundle.getString("userNo");
        labUser.setText(userNo);
    }
}

在初始化Init方法中,接收到登陸界面?zhèn)鬟f過(guò)來(lái)的userNo,顯示在TextView中。Index界面的代碼如下

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:padding="5dp" android:orientation="vertical">
    <LinearLayout android:orientation="horizontal"
        android:layout_width="fill_parent" android:layout_height="wrap_content">
        <TextView android:id="@+id/labWelCome" android:layout_width="wrap_content"
            android:text="@string/labWelCome" android:layout_height="fill_parent"
            android:textColor="@color/yellow">
        </TextView>
        <TextView android:id="@+id/labUser" android:layout_width="wrap_content"
            android:layout_height="fill_parent" android:textColor="@color/red"
            android:textStyle="bold"></TextView>
    </LinearLayout>
    <View android:layout_height="1px" android:background="#FFFFFF"
        android:layout_width="fill_parent" android:paddingBottom="10dp"></View>
    <TableLayout android:id="@+id/tabMain"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:stretchColumns="*" android:padding="3dip">
        <TableRow>
            <ImageButton android:id="@+id/imgBtnUserRegister"
                android:src="@drawable/userregister" />
            <ImageButton android:id="@+id/p_w_picpathBtnSystemCode"
                android:src="@drawable/main_system_code" />
        </TableRow>
        <TableRow>
            <ImageButton android:id="@+id/imgBtnUserInfo"
                android:src="@drawable/main_user_info" />
            <ImageButton android:id="@+id/p_w_picpathBtnModifyPwd"
                android:src="@drawable/main_modify_pwd" />
        </TableRow>
        <TableRow>
            <ImageButton android:id="@+id/imgBtnEnter"
android:src="@drawable/main_enter_mng" />
            <ImageButton android:id="@+id/imgBtnQuit" android:src="@drawable/main_quit_mng" />
        </TableRow>
    </TableLayout>
</LinearLayout>

本界面采用TabelLayout布局。我們點(diǎn)擊imgBtnUserRegister按鈕,跳轉(zhuǎn)到用戶注冊(cè)界面

Android切近實(shí)戰(zhàn)(二)

Intent intent = new Intent();
                intent.setClass(index.this,userregister.class);
                startActivityForResult(intent, 0);

界面UI代碼如下

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:padding="5dp" android:orientation="vertical">
    <TableLayout android:id="@+id/tabMain"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:padding="3dip" android:stretchColumns="1">
        <TableRow>
            <TextView android:text="@string/labUserName"
                android:textSize="8pt" android:gravity="right" />
            <EditText android:id="@+id/txtUserName" android:maxLength="25"
                android:hint="@string/hintInputUserNo" android:singleLine="true"></EditText>
        </TableRow>
        <TableRow>
            <TextView android:text="@string/labPwd" android:textSize="8pt"
                android:gravity="right" />
            <EditText android:id="@+id/txtPwd" android:maxLength="50"
                android:singleLine="true" android:hint="@string/hintInputUserPwd"
                android:password="true"></EditText>
        </TableRow>
        <TableRow>
            <TextView android:text="@string/labRePwd" android:textSize="8pt"
                android:gravity="right" />
            <EditText android:id="@+id/txtRePwd" android:singleLine="true"
                android:hint="@string/hintInputUserRePwd" android:password="true"></EditText>
        </TableRow>
        <TableRow>
            <TextView android:text="@string/labRole" android:textSize="8pt"
                android:gravity="right" />
            <CheckBox android:id="@+id/chkRole" android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:checked="false"
                android:text="@string/labAdmin" android:textColor="@color/yellow"
                android:textSize="8pt"></CheckBox>
        </TableRow>
    </TableLayout>
    <LinearLayout android:orientation="horizontal"
        android:gravity="center_horizontal" android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <Button android:id="@+id/btnSure" android:layout_width="110dp"
            android:layout_height="45dp" android:layout_gravity="center_horizontal"
            android:text="@string/btnSure" android:textStyle="bold"
            android:textColor="@color/blue"></Button>
        <Button android:id="@+id/btnCancel" android:layout_width="110dp"
            android:layout_gravity="center_horizontal" android:layout_height="45dp"
            android:text="@string/btnCancelText" android:textStyle="bold"
            android:textColor="@color/blue"></Button>
    </LinearLayout>
</LinearLayout>

點(diǎn)擊確定按鈕,注冊(cè)用戶。

btnSure.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                String userName = txtUserName.getText().toString().trim();
                String pwd = txtPwd.getText().toString().trim();
                String rePwd = txtRePwd.getText().toString().trim();
                String isAdmin = chkRole.isChecked() ? "1" : "0";
                if (!CheckInput(userName, pwd, rePwd))
                    return;
                SoapObject response = GetServerResponse(userName, pwd, isAdmin);
                Boolean isSuccess = Boolean.valueOf(response.getProperty(
                        "IsSuccess").toString());
                if (isSuccess) {
                    ShowMessage(R.string.SaveSuccess);
                } else {
                    String errorMsg = response.getProperty("ErrorMessage")
                            .toString();
                    new AlertDialog.Builder(owner).setTitle(
                            R.string.WarningMsgTitle).setMessage(errorMsg)
                            .setIcon(R.drawable.info).setPositiveButton("確定",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(
                                                DialogInterface dialoginterface,
                                                int i) {
                                            txtUserName.setText("");
                                            txtPwd.setText("");
                                            txtRePwd.setText("");
                                            chkRole.setChecked(false);
                                        }
                                    }).show();
                }
            }
        });

首先先Check輸入的用戶名和密碼等

private Boolean CheckInput(String userName, String pwd, String rePwd) {
        if (userName == null || userName.equals("")) {
            new AlertDialog.Builder(this).setTitle(R.string.WarningMsgTitle)
                    .setMessage(R.string.UserNoIsEmpty)
                    .setIcon(R.drawable.info).setPositiveButton("確定",
                            new DialogInterface.OnClickListener() {
                                public void onClick(
                                        DialogInterface dialoginterface, int i) {
                                    txtUserName.requestFocus();
                                }
                            }).show();
            return false;
        } 此處省略部分代碼

如下都是一些Check。

Android切近實(shí)戰(zhàn)(二)Android切近實(shí)戰(zhàn)(二)

Android切近實(shí)戰(zhàn)(二)Android切近實(shí)戰(zhàn)(二)

Android切近實(shí)戰(zhàn)(二)

OK,到此一個(gè)用戶就注冊(cè)成功了。我們先看一下.net webservice端。

namespace GRLC.WebService
{
    /// <summary>
    /// UserInfoMng 的摘要說(shuō)明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允許使用 ASP.NET AJAX 從腳本中調(diào)用此 Web 服務(wù),請(qǐng)取消注釋以下行。
    // [System.Web.Script.Services.ScriptService]
    public class UserInfoMng : System.Web.Services.WebService
    {
        [WebMethod]
        public CommonResponse UserInfoAdd(UserEntity userInfo)
        {
            return UserInfoBiz.GetInstance().AddUserInfo(userInfo);
        }
    }
}

下面是Biz層代碼

namespace GRLC.Biz
{
    public class UserInfoBiz
    {
        static UserInfoBiz userInfoBiz = new UserInfoBiz();
        private UserInfoBiz()
        { }
        public static UserInfoBiz GetInstance()
        {
            return userInfoBiz;
        }
        const string moduleName = "UserInfoModule";
        private string GetMessageByName(string msgName)
        {
            return CommonFunction.GetMessageByModuleAndName(moduleName, msgName);
        }
        private string AddFaild
        {
            get
            {
                return this.GetMessageByName("AddFailed");
            }
        }
        private string UserHasExists
        {
            get
            {
                return this.GetMessageByName("UserHasExists");
            }
        }
        public CommonResponse AddUserInfo(UserEntity userEntity)
        {
            if (UserInfoMngDAL.GetInstance().IsUserInfoExists(userEntity.UseNo))
            {
                return new CommonResponse() { IsSuccess = false, ErrorMessage = UserHasExists };
            }
            User user = new User();
            user.UseNo = userEntity.UseNo;
            user.Pwd = Cryptor.Encrypt(userEntity.Pwd);
            user.IsAdmin = userEntity.IsAdmin;
            int suc = UserInfoMngDAL.GetInstance().AddUserInfo(user);
            if (suc > 0)
            {
                return new CommonResponse() { IsSuccess = true };
            }
            return new CommonResponse() { IsSuccess = false, ErrorMessage = AddFaild };
        }
    }
}

其中UserInfoMngDAL的定義如下

namespace GRLC.DAL
{
    public class UserInfoMngDAL
    {
        static UserInfoMngDAL userInfoMngDAL = new UserInfoMngDAL();
        private UserInfoMngDAL()
        { }
        public static UserInfoMngDAL GetInstance()
        {
            return userInfoMngDAL;
        }
        public int AddUserInfo(User user)
        {
            using(BonusEntities bonusEntities=new BonusEntities())
            {
                bonusEntities.User.Add(user);
                return bonusEntities.SaveChanges();
            }
        }
        public bool IsUserInfoExists(string userNo)
        {
            using (BonusEntities bonusEntities = new BonusEntities())
            {
                return bonusEntities.User.Any(u => u.UseNo == userNo);
            }
        }
    }
}

其中UserEntity的定義如下

namespace GRLC.Model.DTO
{
    public class UserEntity
    {
        public string UseNo { get; set; }
        public string Pwd { get; set; }
        public string IsAdmin { get; set; }
    }
}

到時(shí)候這個(gè)實(shí)體需要和Android那邊傳遞的實(shí)體保持一致

Android切近實(shí)戰(zhàn)(二)

Ok,我們接下來(lái)看看Android是如何調(diào)用的。

private SoapObject GetServerResponse(String userName, String pwd,
            String isAdmin) {
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
        UserEntity userEntity = new UserEntity();
        userEntity.setProperty(0, userName);
        userEntity.setProperty(1, pwd);
        userEntity.setProperty(2, isAdmin);
        PropertyInfo pi = new PropertyInfo();
        pi.setName("userInfo");
        pi.setValue(userEntity);
        pi.setType(userEntity.getClass());
        request.addProperty(pi);// 將自定參數(shù)加入請(qǐng)求對(duì)象中
        SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        soapEnvelope.dotNet = true;
        soapEnvelope.setOutputSoapObject(request);
        HttpTransportSE httpTS = new HttpTransportSE(URL);
        soapEnvelope.bodyOut = httpTS;
        soapEnvelope.setOutputSoapObject(request);// 設(shè)置請(qǐng)求參數(shù)
        soapEnvelope.addMapping(NAMESPACE, "UserEntity", userEntity.getClass());
        try {
            httpTS.call(SOAP_ACTION, soapEnvelope);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        SoapObject result = null;
        try {
            result = (SoapObject) soapEnvelope.getResponse();
        } catch (SoapFault e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

OK,調(diào)用只要將數(shù)據(jù)對(duì)象傳遞正確,就不會(huì)調(diào)用失敗。android中定義的UserEntity如下

package bruce.grlc.model.Entity;
import java.util.Hashtable;
import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.PropertyInfo;
public class UserEntity implements KvmSerializable {
    private String UseNo;
    private String Pwd;
    private String IsAdmin;
    @Override
    public Object getProperty(int arg0) {
        // TODO Auto-generated method stub
        Object property = null;
        switch (arg0) {
        case 0:
            property = this.UseNo;
            break;
        case 1:
            property = this.Pwd;
            break;
        case 2:
            property = this.IsAdmin;
        default:
            break;
        }
        return property;
    }
    @Override
    public int getPropertyCount() {
        // TODO Auto-generated method stub
        return 3;
    }
    @Override
    public void getPropertyInfo(int arg0, Hashtable arg1, PropertyInfo arg2) {
        // TODO Auto-generated method stub
        switch (arg0) {
        case 0:
            arg2.type = PropertyInfo.STRING_CLASS;
            arg2.name = "UseNo";
            break;
        case 1:
            arg2.type = PropertyInfo.STRING_CLASS;
            arg2.name = "Pwd";
            break;
        case 2:
            arg2.type = PropertyInfo.STRING_CLASS;
            arg2.name = "IsAdmin";
        default:
            break;
        }
    }
    @Override
    public void setProperty(int arg0, Object arg1) {
        // TODO Auto-generated method stub
        if (arg1 == null)
            return;
        switch (arg0) {
        case 0:
            this.UseNo = arg1.toString();
            break;
        case 1:
            this.Pwd = arg1.toString();
            break;
        case 2:
            this.IsAdmin = arg1.toString();
            break;
        default:
            break;
        }
    }
}

必須繼承KvmSerializable這個(gè)抽象接口,并實(shí)現(xiàn)它的抽象方法。

public abstract interface org.ksoap2.serialization.KvmSerializable {
                                                           
  // Method descriptor #4 (I)Ljava/lang/Object;
  public abstract java.lang.Object getProperty(int arg0);
                                                           
  // Method descriptor #6 ()I
  public abstract int getPropertyCount();
                                                           
  // Method descriptor #8 (ILjava/lang/Object;)V
  public abstract void setProperty(int arg0, java.lang.Object arg1);
                                                           
  // Method descriptor #10 (ILjava/util/Hashtable;Lorg/ksoap2/serialization/PropertyInfo;)V
  public abstract void getPropertyInfo(int arg0, java.util.Hashtable arg1, org.ksoap2.serialization.PropertyInfo arg2);
}

OK,調(diào)用就是這么簡(jiǎn)單。最后,在界面操作的時(shí)候,當(dāng)焦點(diǎn)在文本框中時(shí),總是會(huì)彈出輸入法,遮擋按鈕,為了解決這一問(wèn)題,需要采取兩種方法

第一種,在AndroidManifest.xml中增加android:windowSoftInputMode="adjustResiz

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="bruce.grlc" android:versionCode="1" android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />
    <application android:icon="@drawable/app" android:label="@string/app_name">
        <activity android:name=".main"
        android:label="@string/app_LoginName"
        android:windowSoftInputMode="adjustResize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".index" android:label="@string/app_name">
        </activity>
        <activity android:name=".userregister" android:label="@string/btnUserReg">
        </activity>
    </application>
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>

這句的意思是當(dāng)輸入法出現(xiàn)時(shí),界面自適應(yīng),但是有時(shí)候界面上的控件比較多時(shí),依然會(huì)遮住某些控件。所以如下

第二種解決方案,在觸摸屏幕其他地方時(shí),自動(dòng)關(guān)閉輸入法

public boolean onTouchEvent(MotionEvent event) {
        InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        im.hideSoftInputFromWindow(getCurrentFocus()
                .getApplicationWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
        return super.onTouchEvent(event);
    }

OK,本篇到此結(jié)束。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI