gpt4 book ai didi

android - 为不同的按钮点击打开不同的 Activity

转载 作者:行者123 更新时间:2023-11-29 17:05:20 25 4
gpt4 key购买 nike

我正在制作一个将点击存储在 firebase 中的投票应用程序。当按下两个按钮中的任何一个时,它应该转到通用布局 Activity (votes.java)。 Btn1 会发生这种情况,但单击 Btn2 时应用会崩溃。

主 Activity .java

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.os.Handler;
import com.firebase.client.Firebase;
public class Main2Activity extends AppCompatActivity {
private Firebase mRootRef;
private Button mBtn1;
private Button mBtn2;
int counter = 0;
int counter1 = 0;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Firebase.setAndroidContext(this);
mBtn1 = (Button) findViewById(R.id.btn1);
mBtn2 = (Button) findViewById(R.id.btn2);
mBtn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v.equals(mBtn1)) {
Intent i1= new Intent(Main2Activity.this, Votes.class);
startActivity(i1);
mRootRef = new Firebase("https://voting-cf0fa.firebaseio.com/House/Jupiter/Player 1");
Firebase mRefChild = mRootRef.child("Votes");
counter++;
mRefChild.setValue(counter);

}

mRootRef = new Firebase("https://voting-cf0fa.firebaseio.com/House/Jupiter/Player 2");
mBtn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v.equals(mBtn2)) {
Intent i2= new Intent(Main2Activity.this, Votes.class);
startActivity(i2);
Firebase mRefChild = mRootRef.child("Votes");
counter1++;
mRefChild.setValue(counter1);

}
}

});
}
});

}}

谢谢。

最佳答案

这是因为按钮 2 的点击监听器位于按钮 1 的点击监听器内。您需要为不同的按钮初始化不同的 onClick 监听器。

试试这个:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Firebase.setAndroidContext(this);
mBtn1 = (Button) findViewById(R.id.btn1);
mBtn2 = (Button) findViewById(R.id.btn2);
mBtn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{

Intent i1= new Intent(Main2Activity.this, Voted.class);
startActivity(i1);
mRootRef = new Firebase("https://voting-cf0fa.firebaseio.com/House/Jupiter/Player 1");
Firebase mRefChild = mRootRef.child("Votes");
counter++;
mRefChild.setValue(counter);
});

mBtn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
mRootRef = new Firebase("https://voting-cf0fa.firebaseio.com/House/Jupiter/Player 2");
Intent i2= new Intent(Main2Activity.this, Voted2.class);
startActivity(i2);
Firebase mRefChild = mRootRef.child("Votes");
counter1++;
mRefChild.setValue(counter1);
}
});

关于android - 为不同的按钮点击打开不同的 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41960417/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com