综合应用各类样式资源,完成个性化的登录界面。写Android运行代码
时间: 2023-07-15 09:10:19 浏览: 50
这里提供一个简单的例子,演示如何使用样式资源和布局文件创建个性化的登录界面。
首先,创建一个新的 Android 项目并打开 activity_main.xml 文件。在这个文件中,我们将添加一个垂直的 LinearLayout,并在其中添加两个 EditText 和一个 Button。
```
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username"
android:textSize="18sp"
android:padding="8dp"
android:background="@drawable/edittext_style"/>
<EditText
android:id="@+id/password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Password"
android:textSize="18sp"
android:padding="8dp"
android:background="@drawable/edittext_style"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:textSize="18sp"
android:padding="8dp"
android:background="@drawable/button_style"/>
</LinearLayout>
```
在 EditText 和 Button 中,我们使用了 @drawable/edittext_style 和 @drawable/button_style。这些资源位于 res/drawable 目录中,我们需要在这个目录下创建相应的 XML 文件。
在 edittext_style.xml 文件中,我们定义了一个圆角矩形的背景和一个边框。在 button_style.xml 文件中,我们定义了一个渐变背景和一个圆角矩形的边框。
edittext_style.xml:
```
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="8dp" />
<stroke
android:width="2dp"
android:color="@color/black" />
<solid android:color="@color/white" />
</shape>
```
button_style.xml:
```
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="8dp" />
<gradient
android:startColor="@color/orange"
android:endColor="@color/yellow"
android:type="linear"
android:angle="0"/>
<stroke
android:width="2dp"
android:color="@color/black" />
</shape>
```
最后,我们需要在 colors.xml 文件中定义颜色值。
colors.xml:
```
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="black">#000000</color>
<color name="white">#FFFFFF</color>
<color name="orange">#FFA500</color>
<color name="yellow">#FFFF00</color>
</resources>
```
现在,我们已经完成了登录界面的布局和样式。下面是 MainActivity.java 文件的代码:
```
public class MainActivity extends AppCompatActivity {
private EditText username;
private EditText password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = findViewById(R.id.username);
password = findViewById(R.id.password);
Button loginButton = findViewById(R.id.login_button);
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String usernameText = username.getText().toString();
String passwordText = password.getText().toString();
// TODO: 登录操作
}
});
}
}
```
现在,您可以运行应用程序并查看您的个性化登录界面!