我刚刚进入 Android 应用程序,我还没有找到详细解释如何执行任何操作的教程。有人可以向我展示有关如何在 Android 中创建两个按钮(登录和注册)的代码吗?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginButton=(Button)findViewById(R.id.button);
button.setOnClickListener(LogInListener);
signUpButton=(Button)findViewById(R.id.button2);
button2.setOnClickListener(SignUpListener);
}
private OnClickListener LogInListener=new OnClickListener()
{
public void onClick(View v)
{
}
}
这是正确的实现方式吗?谢谢
activity_main.xml
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Log In"
android:id="@+id/button"
android:layout_marginTop="61dp"
android:layout_below="@+id/textView3"
android:layout_toStartOf="@+id/button2"
android:layout_toLeftOf="@+id/button2" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sign UP"
android:id="@+id/button2"
android:layout_alignTop="@+id/button"
android:layout_alignLeft="@+id/editText2"
android:layout_alignStart="@+id/editText2"
android:layout_marginLeft="48dp"
android:layout_marginStart="48dp" />
最佳答案
编辑:
现在您已经编辑了您的问题,您只需再做一件事将您的按钮声明为实例变量。在所有方法 (onCreate) 之外但在 mainActivity 内部声明它们。
预编辑:
我将向您展示您的主要 Activity (Java 类)以及您的布局(XML 文件)应该是什么样子:
<小时/>主要 Activity :
public class MainActivity extends AppCompatActivity {
Button signIn, signUp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
signIn = (Button) findViewById(R.id.'idOfButtonFromXMLLayout');
signUp = (Button) findViewById(R.id.'idOfButtonFromXMLLayout');
//Looking at my XML code, the signIn id would be R.id.signInButton
}
findViewById方法继承自AppCompatActivity类,所有的Activity都继承自AppCompatActivity类。旧版本的 android 只是扩展了 Activity 类。
findViewById 方法采用 int 参数,更具体地说是 id。
需要强制转换的原因是因为您假设的 findViewById 方法返回一种 View 类型,然后将其强制转换为按钮。
<小时/>XML 布局文件:
<RelativeLayout
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:padding="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<Button
android:id="@+id/signInButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sign In"
<!-- Complete Layout Details--> />
<Button
android:id="@+id/signUpButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/signUpText"
<!-- Complete Layout Details--> />
</RelativeLayout>
在上面的代码中,我用两种方式表示按钮的文本......
1) 硬编码字符串“登录”
2) 字符串资源“@string/signUpText
最好将硬编码字符串更改为后一种格式。
关于java - 如何使用 android studio 创建两个 android 按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32469674/