3

という名前のアクティビティクラスがあると仮定しMainActivity.javaます。ただし、このアクティビティには、たとえば約3000行のコードがあります。

このファイルのコード部分を。という名前の外部Javaファイル(クラス)に分離したいと思いますNecessaryThings.java。しかし、エミュレーターでプロジェクトを実行すると、この操作の後でプロジェクトが停止します。

この活動のいくつかの行を分離する方法はありますか?

私はより良いミニ例を書きました。

また、あなたはどう思いますか。

この方法を使用することは、パフォーマンスの観点から有益または有害ですか?

これは私のMainActivity.javaです

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //I want to call these lines from NecessaryThings.java
    TextView genderResult = (TextView) findViewById(R.id.genderText);
    genderResult.setText("Cinsiyet:");
    TextView calorieResult = (TextView) findViewById(R.id.remainCalorie);

    String getGenderSTR = getIntent().getStringExtra("GENDER");
    genderResult.setText(getGenderSTR);

    String calorieResultSTR = getIntent().getStringExtra("CALORIECHOOSED");
    calorieResult.setText(calorieResultSTR);

            /*
              .....
              .....
            */


}

Aftet上記のコードを取得し、それをに保存したいNecessaryThings.java

このような..

//All necessary imports here. There is no problem about those.

public class NecessaryThings extends Activity {

    public void myPersonalMethod() {
        TextView genderResult = (TextView) findViewById(R.id.genderText);
        genderResult.setText("Cinsiyet:");
        TextView calorieResult = (TextView) findViewById(R.id.remainCalorie);

        String getGenderSTR = getIntent().getStringExtra("GENDER");
        genderResult.setText(getGenderSTR);

        String calorieResultSTR = getIntent().getStringExtra("CALORIECHOOSED");
        calorieResult.setText(calorieResultSTR);
    }
}

MainActivity.javaを再配置すると、次のようになります...

public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    NecessaryThings showMyMethod = new NecassaryThings();
    showMyMethod.myPersonalMethod();


   /*
    the rest of the codes...
   */
}

しかし、コードを分離すると機能しません。なぜ、どうすればそれができますか?

4

2 に答える 2

2
public class MainActivity extends NecessaryThings {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    myPersonalMethod();
}

NecessaryThingsはActivityを拡張するため、MainActivityはActivityから拡張する必要はなく、NecessaryThingsから拡張する必要があります。私が指摘する必要があることの1つは、super.onCreate(savedInstanceState);です。onCreate();を呼び出します。NecessaryThingsから。myPersonalMethod();以降 スーパークラスからです、あなたはそれを呼び出すことができます。

于 2013-02-26T03:11:03.203 に答える
1

すべてのアクティビティは通常のJavaクラスであり、次のようなUI以外のクラスを多数持つことができます。もちろん、持つApplicationことができますhelpers。質問を調べてみると、アクティビティにはユーザー定義のコンストラクタがなく、メソッドを呼び出すことによって間接的にのみ作成されstartActivityますが、他の側面では、一般的なJavaクラスです。

したがって、あなたがしなければならないことは、あなたNecessaryThings.javaを通常のクラスにして、あなたからコンテキストを渡し、MainActivity必要なすべてを行うことができるようにすることです。

お役に立てれば。

于 2013-02-26T03:11:04.867 に答える