且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何添加一个可点击的按钮,一个TextView是目前点击

更新时间:2022-12-08 22:54:59

编辑:

创建您的code选择器的XML,并在您绘制文件夹中。我将创建一个btn_custom.xml

create a selector xml with your code and put in your drawable folder. I'll create a btn_custom.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"
    android:drawable="@drawable/btn_active" />
<item android:state_focused="true" android:state_enabled="true"
    android:drawable="@drawable/btn_active" />
<item
     android:drawable="@drawable/btn_default" />
</selector>

然后,在你的TextView的:

Then, on your TextView:

<TextView android:text="MyButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:layout_marginLeft="20dp"
    android:clickable="true"
    android:background="@drawable/btn_custom"
    android:padding="10dp"/>

在填充,您调整按钮填充。

On padding, you adjust your button padding.

在后台,把你选择的名称(在我的情况,@绘制/ btn_custom)

On background, put the name of your selector (in my case, @drawable/btn_custom)

和你的影响已经在

比,只注册一个onClickListener

Than, just register an onClickListener

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView myTextButton = (TextView) findViewById(R.id.my_button_id);
    myTextButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Toast.makeText(MainActivity.this, "ButtonClick", 200).show();
        }
    });
}

PS:你可以用你的onClick方法来代替:P

Ps: You can use your onClick method instead :P

永远记住:一个按钮只是一个病急乱投医的TextView

Always remember: A Button is just a "styled" TextView.

这是Android源$ C ​​$ C为Button类:

This is the Android source code for Button class:

public class Button extends TextView {
    public Button(Context context) {
        this(context, null);
    }

    public Button(Context context, AttributeSet attrs) {
        this(context, attrs, com.android.internal.R.attr.buttonStyle);
    }

    public Button(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
}

是的,它只是