Java – create a switch case onclicklistener for textview

I just started programming in Java and had some trouble implementing the onclicklistener switch case for clickable textview I've tried to make a switch case for menu items, but I obviously can't understand it enough to constitute a more general case

This is an important part of my code for it

public class MyActivity extends Activity implements SensorEventListener {
TextView tv,tv1,tv2,tv3;

@Override
public void onCreate(Bundle savedInstanceState) {
//get textviews
    tv = (TextView) findViewById(R.id.xval);
    tv1 = (TextView) findViewById(R.id.yval);
    tv2 = (TextView) findViewById(R.id.zval);
    tv3 = (TextView) findViewById(R.id.scalar);

Then I set up a separate click listener for each textview, such as

tv1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            // Do things
            }
        }
    });

But I'm trying to set it up, so I have a combined onclicklistener, such as:

@Override
public boolean onClickListener (View v) {
    switch (tv.findViewById()) {
        case tv:
            //Do things
            return true;
        case tv1:
            //Do things
            return true;
        case tv2:
            //Do things
            return true;
        case tv3:
            //Do things
            return true;

}}

I know the code is very wrong, but I can't seem to get around it I have assigned my findviewbyid, so I'm not sure what else can be put into the switch!

thank you!

Solution

I will provide an alternative answer First, you must create an onclicklistener that will receive your onclick events:

OnClickListener listener = new OnClickListener()
    {

        @Override
        public void onClick(View v)
        {
            switch (v.getId())
            {
                case R.id.xval:
                    //code
                    break;

                case R.id.yval:
                    //code
                    break;

                case R.id.zval:
                    //code
                    break;

                case R.id.scalar:
                    //code
                    break;

                default:
                    break;
            }

        }
    };

You must then associate the listener with each textview you own:

tv.setOnClickListener(listener);
tv1.setOnClickListener(listener);
tv2.setOnClickListener(listener);
tv3.setOnClickListener(listener);

After clicking one of the textviews, the onclicklistener onclick() callback is called, which checks the textview ID you clicked and runs the code accordingly, depending on the case

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>