Android - setOnClickListener for TextView

后端 未结 6 1957
孤街浪徒
孤街浪徒 2021-02-05 10:47

It should be straightforward, but I am not sure where something is wrong. I try to catch the click on the TextView with:

public void runNextTask(){
         


        
相关标签:
6条回答
  • 2021-02-05 11:20

    You can remove this:

    android:onClick="onClick"
    

    Or, remove this:

    modelTextview.setOnClickListener(new OnClickListener() {
        @Override
         public void onClick(View v) {
    
         }
    });
    

    and have this:

    public void onClick(View v)
    {
        // do something
    }  
    

    android:onClick="onClick"/> // It would be better to rename the method to avoid confusion

    Also, you have this:

    <TextView
         android:id="@+id/model" // id is model
    

    so initialize your TextView as below:

    TextView modelTextview = (TextView)addView.findViewById(R.id.model);
    
    0 讨论(0)
  • 2021-02-05 11:30

    This line: android:onClick="onClick" Tells Android to look in the activity for a method with this signature:

    public void onClick(View v)
    

    This wasn't your intention, as you've set the OnClickListener inside your code and haven't created the dedicated method for it in the activity. So your options are either to simply remove the android:onClick="onClick" from your xml file or remove the on click listener you've created and change it to an onClick method (and preferablly change it's name to something better than onClick...

    0 讨论(0)
  • 2021-02-05 11:33

    If you change your code to have this structure it will work:

    public void runNextTask(){
       ...
    }
    
    public void onClick(View v) {
    
    }
    

    as you're telling in your xml to capture the click for the text view (android:onClick="onClick") in onClick module, you don't need to add an onClick listener in your java code.

    0 讨论(0)
  • 2021-02-05 11:33

    for every view component we can call setOnclickLister() like that for TextView also call

    textview.setOnclickListener(new setOnclickListener
                               {
                                    public void onclick()
                                                       {
    
    
                                                        }
                               }
                                );``
    
    0 讨论(0)
  • 2021-02-05 11:40
     super.onCreate(savedInstanceState);
     setContentView(R.layout.other_activity);
     findViewById(R.id.TextView).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
    
        }
    });
    
    0 讨论(0)
  • 2021-02-05 11:40

    Change :

     TextView modelTextview = (TextView)addView.findViewById(R.id.modelEdit);
    

    to

     TextView modelTextview = (TextView)addView.findViewById(R.id.model);
    

    and there is no need of android:onClick="onClick" in your xml code if you want do this with java code

    0 讨论(0)
提交回复
热议问题