gpt4 book ai didi

android - 两个按钮打开两个新 Activity

转载 作者:行者123 更新时间:2023-11-30 01:22:48 24 4
gpt4 key购买 nike

我正在学习 Android,我在主要 Activity 中创建了两个按钮,然后我想从每个按钮打开新 Activity ,按钮 2 工作但按钮 1 不工作,我的代码:

public class MainActivity extends Activity {
Button btn;
Button btn2;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button2);
btn2 = (Button) findViewById(R.id.button1);

btn.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, Allactivities.class);
startActivity(intent);
Intent i = new Intent(MainActivity.this, Review.class);
startActivity(i);
}
});
}
}

XML代码:

<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_above="@+id/button1"
android:layout_marginBottom="26dp"
android:background="@drawable/btnbluee"
android:text="@string/button_tittle"
android:onClick="onClick" />

<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="192dp"
android:background="@drawable/btnorange"
android:text="@string/button_title"
android:onClick="onClick" />

最佳答案

button 2 is working but button one is not work,

这是因为您需要为每个按钮添加一个监听器:

 btn.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this,Allactivities.class);
startActivity(intent);
Intent i = new Intent(MainActivity.this,Review.class);
startActivity(i);

}
});

btn2.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this,Allactivities.class);
startActivity(intent);
Intent i = new Intent(MainActivity.this,Review.class);
startActivity(i);

}
});

只是一个建议..

尝试在布局和代码之间保持一致,您将免除颈部疼痛...

 btn = (Button)findViewById(R.id.button2);
btn2= (Button)findViewById(R.id.button1);

必须是:

 btn = (Button)findViewById(R.id.button1);
btn2= (Button)findViewById(R.id.button2);

关于android - 两个按钮打开两个新 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36848830/

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