开发者

How to use a text as a Button in Android

开发者 https://www.devze.com 2023-03-08 09:01 出处:网络
I want to use a text as a button in Android. Suppose I have one text like \'Register\'. I want t开发者_运维问答o use this text as a button means when i will click in the text, it will open the Registr

I want to use a text as a button in Android. Suppose I have one text like 'Register'. I want t开发者_运维问答o use this text as a button means when i will click in the text, it will open the Registration Screen. I am using XML for developing the UI and i am doing it for Android Tablet Application.

Thanks in advance


Set the following property in the xml of TextView:

android:background="#dadada"
    android:clickable="true"

Now in the java src file recieve this TextView and set OnClickListener.

    TextView tv=(TextView)findViewById(R.id.text);

    tv.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            //perform your action here  
        }
    });


Used Below Code.

In XML file Textview assign this property

android:clickable="true"

and in java side OnClickListener used.


In your XML file use this for your TextView :

android:clickable="true"

Then in your source set on click listener :

TextView txtRegister = (TextView) findViewById(R.id.txtRegister);
txtRegister .setOnClickListener(new OnClickListener() {

    public void onClick(View view) {
          your codes here
    }
});


You can specify the method of the View to call with the following attribute in your xml layout:

android:onClick="yourMethodName"

The context that this View is used in is the class that should have this method (the context is usually your Activity)

For example:

<TextView
  android:onClick="register"
  android:layout_width="wrap_parent"
  android:layout_height="wrap_parent"/>

You would need to have the following method in your context (again, your Activity):

public void register(View v) {
  //
}

This is something you can do with ANY View type. Here is a link to the Android docs.


Best way to use a Text as a Button is BINDING.

First you need to enable binding: Go to

build.gradle(Module)

Now add the following snippet inside "android"

buildFeatures{
    viewBinding true
}

Now click on "SYNC NOW". This will enable binding.

Now you have to create object of binding

ActivityMainBinding binding;

if ID of your TextView is "textView", then you can use it as a button by using this command:

binding.textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            
        }
    });
0

精彩评论

暂无评论...
验证码 换一张
取 消