我对Java和Android开发非常陌生,我正在尝试创建一个小的“测验”,在每个视图上都有RadioButton
个选项,以及下一个和后退按钮。我正在使用下一个和后面的按钮工作,但这似乎是一个非常冗长的方式来做到这一点。有没有一种方法可以定义一个函数,让它在该布局中工作,而不必每次使用后退按钮重新定义它。即我在nexButtonGPAbuttonClick()
中定义了onCreate
,但当我到达activity_main_2_.xml
并将后退按钮设置为setContentView(activty_main.xml)
时,我不得不再次重新定义nextButtonGPAbuttonClick();
setContentView(R.layout.activity_main)
。这是我的.java文件。任何指导都会非常有帮助。
package com.example.studentadvisorapp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nextButtonGPAbuttonClick();
}
private void nextButtonGPAbuttonClick() {
//Get reference to button
Button nextButtonGPA = (Button) findViewById(R.id.next_button_gpa);
//set click listener
nextButtonGPA.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setContentView(R.layout.activity_main_2);
prevButtonHoursEnrolledbuttonClick();
nextButtonHoursEnrolledbuttonClick();
}
private void prevButtonHoursEnrolledbuttonClick() {
//Get reference to button
Button prevButtonHoursEnrolled = (Button) findViewById(R.id.prev_button_hours_enrolled);
//set click listener
prevButtonHoursEnrolled.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setContentView(R.layout.activity_main);
nextButtonGPAbuttonClick();
}
});
}
private void nextButtonHoursEnrolledbuttonClick() {
//Get reference to button
Button nextButtonHoursEnrolled = (Button) findViewById(R.id.next_button_hours_enrolled);
//set click listener
nextButtonHoursEnrolled.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setContentView(R.layout.activity_main_3);
nextButtonHoursWorkingbuttonClick();
prevButtonHoursWorkingbuttonClick();
}
private void nextButtonHoursWorkingbuttonClick() {
//Get reference to button
Button nextButtonHoursWorking = (Button) findViewById(R.id.next_button_hours_working);
//set click listener
nextButtonHoursWorking.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { setContentView(R.layout.activity_main_4);
}
});
}
private void prevButtonHoursWorkingbuttonClick() {
//Get reference to button
Button nextButtonHoursWorking = (Button) findViewById(R.id.prev_button_hours_working);
//set click listener
nextButtonHoursWorking.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { setContentView(R.layout.activity_main_2); prevButtonHoursEnrolledbuttonClick(); nextButtonHoursEnrolledbuttonClick();
}
});
}
});
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
答案 0 :(得分:1)
启动一个新的Activity而不是调用setContentView。这样,后退按钮将自动将用户带回到上一个屏幕。