试试这个,当你加载MainActivity时,它转到ActivityB,ActivityB点击MainActivity中创建的按钮。您必须确保您尝试单击的按钮不为空。
祝你好运
主要活动
package com.example.testproject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class MainActivity extends Activity {
RelativeLayout lyt;
public static Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lyt = (RelativeLayout) findViewById(R.id.main);
button = new Button(this);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "clicked the button",
Toast.LENGTH_SHORT).show();
}
});
lyt.addView(button);
Intent i = new Intent(MainActivity.this, ActivityB.class);
startActivity(i);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
活动B
package com.example.testproject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
public class ActivityB extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MainActivity a = new MainActivity();
Button button = MainActivity.button;
button.performClick();
}
}
显现
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testproject"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.testproject.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.testproject.ActivityB" >
</activity>
</application>
</manifest>