1

として1つのクラスを作成しました

public class FormActivity extends Activity 
{
    TextView tv =new TextView(this);
    GridLayout gl=new GridLayout(this);

    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        paint();
    }

    public void paint()
    {
        tv.setText("In new File");
        gl=(GridLayout) findViewById(R.id.gl);
        gl.addView(tv);
    }
}

paint()別のクラス(同じパッケージ内のJavaファイル)からメソッドにアクセスしたい。私はこれを試しました:

public class FileSystemDemoActivity extends Activity 
{

    FormActivity f1=new FormActivity();
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        f1.paint();
    }
}

しかし、これはうまくいきません。エミュレーターは残念ながら停止エラーを返します。私を助けてください。

4

2 に答える 2

0

表示されるエラーは、おそらくglnull が原因です。アクティビティが正しく初期化されていないため、アクティビティのビューにアクセスできません。別のアクティビティから FormActivity を開始して表示するにはstartActivity()、そのアクティビティonCreateが呼び出され、最終的に「ペイント」メソッドが呼び出されます。

于 2012-06-27T08:06:39.497 に答える
0
sorry.i have not understood can you give an example? 

として他のアクティビティ機能にアクセスしようとしないでください。

1-アクティビティで他のアクティビティのインスタンスを作成しようとしないでください。

2- findViewById(R.id.gl) は現在のアクティビティ レイアウトにリンクされており、アクティビティ コードが記述されている特定のアクティビティの ID を検索します。

...

 public class FileSystemDemoActivity extends Activity 
        {
        FormActivity f1=new FormActivity();
        public void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            f1.paint();
        }

            public void paint()
            {
                 tv.setText("In new File");
                 gl=(GridLayout) findViewById(R.id.gl);
                 gl.addView(tv);
            }

        }  
于 2012-06-27T08:39:29.730 に答える