想要从主类访问变量到其他类...

时间:2011-08-05 08:07:57

标签: android

我的计划如下:

public class HelloGridViewActivity extends Activity {

    public int pos;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        GridView gridview = (GridView) findViewById(R.id.gridview);
        gridview.setAdapter(new ImageAdapter(this));

        gridview.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                pos = position;
                Toast.makeText(HelloGridViewActivity.this, "" + pos, Toast.LENGTH_SHORT).show();
                Intent secondActivity = new Intent(getBaseContext(), seconactivity.class);
                startActivity(secondActivity);
            }
        });
    }
}

这是我的主类文件,我的其他java文件如下

public class seconactivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        HelloGridViewActivity position1 = new HelloGridViewActivity();
        int p = position1.pos;
        if (p == 0) {
            setContentView(R.layout.ashtavinayak);
        } else {
            setContentView(R.layout.ayadhya);
        }
    }
}

我想在主类中定义的pos变量访问seconactivity class..can any1告诉我该怎么办?

1 个答案:

答案 0 :(得分:4)

最简单的方法是将其作为数据或额外内容传递给意图(查看Intent.setData()Intent.putExtra

在第二项活动中,您可以致电getIntent(),然后阅读其数据和附加内容。