我对android编程很新。我想使用一个代码,通过单击Button,将我从当前活动转到MainActivity。
这是我目前的代码:
package com.example.flashlightapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Whitelight extends Activity implements OnClickListener {
Button b1 = (Button) findViewById(R.id.b3);
Intent i = new Intent(this, MainActivity.class);
{
this.startActivity(i);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_whitelight);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
我应该放什么
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
答案 0 :(得分:0)
试试这个..
public class Whitelight extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_whitelight);
Button b1 = (Button) findViewById(R.id.b3); // Initialization of Button
b1.setOnClickListener(this); // Initialization of ClickListener to the Button
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
}
}
点击链接
http://developer.android.com/index.html
答案 1 :(得分:0)
使用以下内容:
Button b1;
public class Whitelight extends Activity implements OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_whitelight);
b1 = (Button) findViewById(R.id.b3); // Initialization of Button
b1.setOnClickListener(this); // Initialization of ClickListener to the Button
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v==b1){
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
}
}
}
onClick(...)中的:
您可以选择按下按钮然后执行特定活动,在您的情况下按b1按钮然后执行按钮特定活动:
所以我们可以查看 v == b1 按钮。如果你想要更多按钮那么
if(v==b1){
Intent i = new Intent(this, MainActivity.class);
startActivity(i);
}
else if(v==b2)
{
// perform another action ;
}
答案 2 :(得分:0)
首先,您必须检查是否在manifest.xml文件中声明了所有活动。
并在您的Java代码中尝试:
package com.example.flashlightapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Whitelight extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_whitelight);
Button b1 = (Button) findViewById(R.id.b3);
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(Whitelight.this, MainActivity.class);
this.startActivity(i);
}
});
}
}
本教程介绍了如何使用意图和监听器:http://goo.gl/phLWkx