简体   繁体   English

android哪里把OnClickListener面向对象?

[英]android where to put OnClickListener OOP-wise?

Suppose I have a MyTextView class that extends TextView. 假设我有一个扩展TextView的MyTextView类。 The myTextView Objects should be clickable. myTextView对象应该是可单击的。

On one hand, it seems that the OnClickListener should be in the MyTextView class since I will be using a few of those, and I don't want to set an OnClickListener to each one. 一方面,似乎OnClickListener应该在MyTextView类中,因为我将使用其中的一些,并且我不想为每个类都设置一个OnClickListener。 If the OnClickListener is in the MyTextView class, it will only be written once. 如果OnClickListener在MyTextView类中,则将只写入一次。 Moreover, all myTextView objects perform the same thing when clicked. 而且,所有myTextView对象在单击时都执行相同的操作。

On the other hand, these objects need to update the UI and some variables in the activity they're in. I don't have access to these variables and UI objects from within MyTextView class and it doesn't feel right to send reference to all of them via the costructor. 另一方面,这些对象需要更新其所在活动中的UI和一些变量。我无权从MyTextView类中访问这些变量和UI对象,并且感觉不适合将引用发送给所有这些都是通过构造函数。

What would be the right thing to do OOP-wise ? 在OOP方面明智的做法是什么?

you can do so 你可以这样做

class MyTextView extends TextView implements View.OnClickListener{

    public MyTextView(Context context) {
        super(context);
        this.setOnClickListener(this);
    }

    public static interface MyTextListener{
        public void updateUI();
    }

    @Override
    public void onClick(View v) {
        if(getContext() instanceof MyTextListener){
            ((MyTextListener)getContext()).updateUI();
        }
    }
}

continue to implement the interface in activity 继续在活动中实现接口

public class MainActivity extends Activity implements MyXextView.MyTextListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);    
    }

    @Override
    public void updateUI() {
        //update here
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM