English 中文(简体)
Java 我如何利用继承来简化我的法典? (Android Dev.)
原标题:In Java, How do I simplify my code using inheritance? (Android Dev.)

在各种活动中,我有非常相似的方法。

例如:

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.ibHome:
        Intent menuIntent = new Intent(v.getContext(),Menu.class);
        startActivity(menuIntent);
        break;
    }

}

and

@Override
public void onClick(View v) {
     /**  */

    //
    switch(v.getId()){
        case R.id.bNew:
            Intent newSwimmerIntent = new Intent(v.getContext(),NewSwimmer.class);
            startActivity(newSwimmerIntent);
            break;
case R.id.ibHome:
            Intent menuIntent = new Intent(v.getContext(),Menu.class);
            startActivity(menuIntent);
            break;

是否有办法(我假定将利用继承)防止在每一类别中明确说明menu Intent?

感谢。

最佳回答

你可以使用继承财产,但事实上可能不是最佳选择,特别是如果两项活动与“Is-A”关系没有直接关系的话。

在该案中,你也许更能宣布一个新班,以安装OnClickListener界面。 然后,你可以立即进行这一分类,并把它与你的纽芬兰人一道点击事件,不管它们被再次使用。

例如:

public class HomeButtonHandler implements OnClickListener{

        @Override
        public void onClick(View v) {
            Intent menuIntent = new Intent(v.getContext(),Menu.class);
            v.getContext().startActivity(menuIntent);            

        }

    }

在你的活动中,你只能把ButtonHandler装在纽芬兰的ClickListner上:

homeButton.setOnClickListener(new HomeButtonHandler());
问题回答

为您的所有活动建立一个共同的<条码>基本标准/代码,然后只优先于<条码>。 基础活动.onClick(方法。

这样,你们就能够为你们的所有活动单独开关。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签