在活动中有2个按钮。第一个按钮应打开一个活动,第二个按钮应打开另一个活动。我写的是以下代码。请帮帮我。
Button voice;
Button msg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_type_of_msg);
voice=(Button)findViewById(R.id.voice);
msg=(Button)findViewById(R.id.text);
}
@Override
public void onClick(View view) {
if(view.getId()==R.id.voice)
{
Intent intent=new Intent(getBaseContext(), TypeOfMsgActivity.class);
startActivity(intent);
setContentView(R.layout.activity_voice_msg);
}
else if(view.getId()==R.id.text)
{
Intent intent=new Intent(getApplicationContext(), TypeOfMsgActivity.class);
startActivity(intent);
setContentView(R.layout.activity_text_msg);
}
}
答案 0 :(得分:1)
Replace this;
`Button voice;
Button msg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_type_of_msg);
voice=(Button)findViewById(R.id.voice);
voice.setOnClickListener(this);
msg=(Button)findViewById(R.id.text);
msg.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if(view.getId()==R.id.voice)
{
Intent intent=new Intent(getBaseContext(), TypeOfMsgActivity.class);
startActivity(intent);
setContentView(R.layout.activity_voice_msg);
}
else if(view.getId()==R.id.text)
{
Intent intent=new Intent(getApplicationContext(), TypeOfMsgActivity.class);
startActivity(intent);
setContentView(R.layout.activity_text_msg);
}
}`
By this:
Button voice;
Button msg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_type_of_msg);
voice=(Button)findViewById(R.id.voice);
msg=(Button)findViewById(R.id.text);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.voice:
Intent intent=new Intent(getBaseContext(), TypeOfMsgActivity.class);
startActivity(intent);
break;
case R.id.text:
Intent intent=new Intent(getApplicationContext(), TypeOfMsgActivity.class);
startActivity(intent);
break;
default:
break;
}
}
还在类中实现OnClickListener
答案 1 :(得分:1)
请尝试以下代码:
button1 = (Button)findViewById(R.id.Button1);
button1.setOnClickListener(new OnClickListener()
{ public void onClick(View v)
{
intent = new Intent(CurrentActivity.this, SecondActivity.class);
startActivity(intent);
finish();
}
});
button2 = (Button)findViewById(R.id.Button2);
button2.setOnClickListener(new OnClickListener()
{ public void onClick(View v)
{
intent = new Intent(CurrentActivity.this, ThirdActivity.class);
startActivity(intent);
finish();
}
});