在android sdk中,我编写了2个按钮,带我进入2种不同的布局。但是,只有我编程的第一个才能工作,而第二个则完全没有。如果你能抓到我错过的任何东西,我会提供代码,请告诉我你的想法。这是我在Android上运行的第一个应用程序之一,所以尽可能简单地解释你的建议。
代码:
public class MainActivity extends Activity {
private final String T = "Settings";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settingsButton();
}
private final String T2 = "ManualAdd";
protected void onCreate1(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
feederButton();
}
private void settingsButton() {
Button messageButton = (Button) findViewById(R.id.Settings);
View.OnClickListener myListener = new View.OnClickListener() {@
Override
public void onClick(View v) {
Log.i(T, "You clicked the settings button!");
startActivity(new Intent(MainActivity.this, SettingsActivity.class));
}
};
messageButton.setOnClickListener(myListener);
}
private void feederButton() {
Button feedButton = (Button) findViewById(R.id.AddFeeder);
View.OnClickListener my2ndListener = new View.OnClickListener() {
public void onClick(View v) {
Log.i(T2, "You clicked the add button!");
startActivity(new Intent(MainActivity.this, ManualAdd.class));
}
};
feedButton.setOnClickListener(my2ndListener);
}
}
答案 0 :(得分:1)
您无法为拥有的每个按钮设置不同的onCreate()
方法。只有一个按钮工作的原因是因为仅 onCreate()
方法才被调用。系统不知道onCreate1()
。要让两个按钮都正常工作
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settingsButton();
}
到
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
settingsButton();
feederButton();
}
您可以从源代码中完全删除onCreate1()
,现在已经过时了。
最好按照官方的Android "First App"教程进行操作。
答案 1 :(得分:0)
试试此代码
public class MainActivity extends Activity {
Button Your_Button_Name;
Button Your_Button_Name;
Activity activity;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.Your_Layout_Name);
//In (R.id.Your_Btn_Name) that's the name that you gave your button in the XML
activity = this;
Your_Button_Name = (Button) findViewById(R.id.Your_Btn_Name);
Your_Button_Name = (Button) findViewById(R.id.Your_Btn_Name);
Your_Button_Name.setOnClickListener(listener);
Your_Button_Name.setOnClickListener(listener);
}
private View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case (R.id.Your_Btn_Name):
startActivity(new Intent(MainActivity.this, Your_Layout_Name.class));
break;
case (R.id.Your_Btn_Name):
startActivity(new Intent(MainActivity.this, Your_Layout_Name.class));
break;
}
}
};
}