android按钮_Android按钮

android按钮

In this tutorial, we will look into Android Button. We will create android studio application and look into various things about button designing, styling, click events etc.

在本教程中,我们将研究Android Button。 我们将创建android studio应用程序,并研究与按钮设计,样式,点击事件等有关的各种事情。

Android按钮 (Android Button)

Android Buttons are GUI components that the users can click upon to either goto the next screen, confirm an option/trigger any event created by you, the Android Developer.
The android.widget.Button is a subclass of Android TextView.

android button tutorial, android studio button example

Buttons in Android can be of the following forms:

Android Buttons是GUI组件,用户可以单击它们进入下一个屏幕,确认选项/触发由您(Android开发人员)创建的任何事件。
android.widget.Button是Android TextView的子类。

Android中的按钮可以采用以下形式:

In the following sections, we’ll be discussing the default button class, creating it programmatically, styling it.

在以下各节中,我们将讨论默认按钮类,以编程方式创建它,并设置其样式。

在布局中创建按钮 (Creating Button in Layout)

We can define the Button widget in our layout file in Android Studio in the following way.

我们可以通过以下方式在Android Studio中的布局文件中定义Button小部件。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context="com.journaldev.androidbutton.MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="DEFAULT BUTTON"
        android:onClick="clickMe"/>

</LinearLayout>

In the above code, we’ve wrapped our Button widget inside a LinearLayout
The id represents the unique identifier.
The onClick attribute requires the method name as the value. This method name should be defined in the corresponding activity of the layout.
It’ll get triggered when the button is clicked.
Setting android:background as a color would remove the selection animation from the button.
We can set an image inside the button alongise the text by using the attribute android:drawableLeft to set the image to the left of the text.
Our MainActivity.java class looks like this:

在上面的代码中,我们将Button小部件包装在LinearLayout中
id表示唯一标识符。
onClick属性需要将方法名称作为值。 该方法名称应在布局的相应活动中定义。
单击该按钮时将触发它。
android:background设置为颜色会从按钮中删除选择动画。
我们可以使用属性android:drawableLeft将图像设置在文本的左侧,从而在按钮内设置图像。
我们的MainActivity.java类如下所示:

package com.journaldev.androidbutton;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void clickMe(View view)
    {
        Toast.makeText(getApplicationContext(),"Button is clicked",Toast.LENGTH_LONG).show();
    }
}

On clicking the button a Toast notification would be displayed onto the screen.

单击按钮后, Toast通知将显示在屏幕上。

以编程方式创建按钮 (Create Button Programmatically)

Let’s set the attributes on the button programmatically and create one button programmatically.

让我们以编程方式设置按钮的属性,并以编程方式创建一个按钮。

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        Button button  = findViewById(R.id.button);
        button.setTextColor(Color.RED);
        button.setClickable(false);
    }

We hook the xml button id to the corresponding instance in the class using the findViewById method.
setTextColor() is used to set the text color,
setClickable accepts a boolean value. Setting it to false would make the button not clickable and the clickMe method won’t be triggered.

我们使用findViewById方法将xml按钮ID挂钩到类中的相应实例。
setTextColor()用于设置文本颜色,
setClickable接受布尔值。 将其设置为false会使按钮不可单击,并且不会触发clickMe方法。

以编程方式创建按钮 (Creating Button Programmatically)

The following code creates a button programmatically and adds it to the root hierarchy.

以下代码以编程方式创建一个按钮,并将其添加到根层次结构中。

Button programmaticButton = new Button(this);
        programmaticButton.setId(R.id.button2);
        programmaticButton.setText("CREATED PROGRAMMATICALLY");
        programmaticButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(),"Programmatic Button is clicked",Toast.LENGTH_LONG).show();
            }
        });

        LinearLayout linearLayout = findViewById(R.id.linearLayout);
        linearLayout.addView(programmaticButton);

We can set an ID programmatically using setId. We can create ids in the folder res | values | ids.xml as shown below:

我们可以使用setId以编程方式设置ID。 我们可以在文件夹res |中创建ID。 价值观| ids.xml如下所示:

setOnClickListener has an interface callback that listens for the click and triggers the onClick method whenever the button is clicked.

setOnClickListener具有接口回调,该回调侦听单击并在单击按钮时触发onClick方法。

Now let’s add another buttons in our layout programmatically in our MainActivity.java class.

现在,让我们在MainActivity.java类中以编程方式在布局中添加另一个按钮。

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = findViewById(R.id.button);
        button.setTextColor(Color.RED);
        button.setClickable(false);

        //Creating a Button programmatically
        Button programmaticButton = new Button(this);
        programmaticButton.setId(R.id.button2);
        programmaticButton.setText("CREATED PROGRAMMATICALLY");
        programmaticButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "Programmatic Button is clicked", Toast.LENGTH_LONG).show();
            }
        });

        LinearLayout linearLayout = findViewById(R.id.linearLayout);
        linearLayout.addView(programmaticButton);

        programmaticButton = new Button(this);
        programmaticButton.setId(R.id.button3);
        programmaticButton.setText(getResources().getString(R.string.another_button));
        programmaticButton.setBackgroundColor(ContextCompat.getColor(this, R.color.colorAccent));
        programmaticButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "Another Programmatic Button is clicked", Toast.LENGTH_LONG).show();
            }
        });

    }

setBackgroundColor() method is to set a color on the button programmatically.
Ideally, we should use string resources to set text on the button instead of hardcoding them in the java class itself.
In the above code, we’ve created two buttons and each of them has a separate interface callback for the listener. This means we’ll have a different object created in the memory for each of the buttons. This would add up in the heap memory and eventually the application would use more memory than required from the device. We can fix this performance issue by making the class implement the View.OnClickListener itself.

setBackgroundColor()方法用于以编程方式在按钮上设置颜色。
理想情况下,我们应该使用字符串资源在按钮上设置文本,而不是在Java类本身中对其进行硬编码。
在上面的代码中,我们创建了两个按钮,每个按钮都有一个用于侦听器的单独的接口回调。 这意味着我们将在内存中为每个按钮创建一个不同的对象。 这将增加堆内存,最终应用程序将使用比设备所需更多的内存。 我们可以通过使类实现View.OnClickListener本身来解决此性能问题。

Instead of using separate setOnClickListener callbacks for every Button, implement the interface on the class itself.
不必对每个Button使用单独的setOnClickListener回调,而应在类本身上实现接口。

So with the View.OnClickListener implemented in the class itself, our MainActivity.java class would look like this:

因此,通过在类本身中实现View.OnClickListener ,我们的MainActivity.java类将如下所示:

package com.journaldev.androidbutton;

import android.graphics.Color;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = findViewById(R.id.button);
        button.setTextColor(Color.RED);
        button.setClickable(false);

        //Creating a Button programmatically
        Button programmaticButton = new Button(this);
        programmaticButton.setId(R.id.button2);
        programmaticButton.setText("CREATED PROGRAMMATICALLY");
        programmaticButton.setOnClickListener(this);

        LinearLayout linearLayout = findViewById(R.id.linearLayout);
        linearLayout.addView(programmaticButton);

        programmaticButton = new Button(this);
        programmaticButton.setId(R.id.button3);
        programmaticButton.setText(getResources().getString(R.string.another_button));
        programmaticButton.setBackgroundColor(ContextCompat.getColor(this, R.color.colorAccent));
        programmaticButton.setOnClickListener(this);

        linearLayout.addView(programmaticButton);

    }

    public void clickMe(View view) {
        Toast.makeText(getApplicationContext(), "Button is clicked", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button2:
                Toast.makeText(getApplicationContext(), "Programmatic Button is clicked", Toast.LENGTH_LONG).show();
                break;
            case R.id.button3:
                Toast.makeText(getApplicationContext(), "Another Programmatic Button is clicked", Toast.LENGTH_LONG).show();
                break;

        }
    }
}

We’ve set each of the setOnClickListener to the common View.OnClickListener interface using this. In the switch block we detect the Button view that was clicked using their id.
This saves a lot of memory!

我们已使用this将每个setOnClickListener设置为公共View.OnClickListener接口。 在开关块中,我们检测到使用其ID单击的Button视图。
这样可以节省大量内存!

设定文字大小 (Setting Text Size)

Text size of a button is typically set in sp units.

按钮的文本大小通常以sp单位设置。

<Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="DEFAULT BUTTON"
        android:textSize="20sp"
        android:background="#147D03"
        android:onClick="clickMe"/>

OR do the following in your activity.

或者在您的活动中执行以下操作。

Button button = findViewById(R.id.button);
button.setTextColor(Color.RED);
button.setClickable(false);
button.setTextSize(22); //size in float

We’ve added a few more buttons to the layout and attached their listeners in the Activity.
Following is the output of the application in action.

我们在布局中添加了一些按钮,并在“活动”中附加了其侦听器。
以下是实际应用程序的输出。

This brings an end to this tutorial. You can find the source code for the Android Button Project below.
In the next tutorial, we’ll be discussing the Button states and selectors.

本教程到此结束。 您可以在下面找到Android Button项目的源代码。
在下一个教程中,我们将讨论Button状态和选择器。

翻译自: https://www.journaldev.com/19838/android-button

android按钮

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值