嗯,我有一个有 5 个按钮的主屏幕。每次按下按钮我都想进入一个新屏幕。到目前为止,我还有其他 5 个类(每个类对应每个屏幕)和 5 个 xml。但我确信会有更好的方法,因为这个屏幕和 xml 是相同的,而我想要做的是更改一些文本和从数据库获取的一些数据。我确信我只能使用另一个类和一个 xml,然后传递我想要的值作为参数。 (想象一下,在其最终状态下,我的应用程序必须有 15 个按钮,所以我认为这太浪费空间了,没有必要拥有 15 个看起来相同的 .java 文件和 15 个 xml 文件,并且只有图像和 TextView 的某些值发生变化) 。我的主要 Activity 代码是:
public class MyActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
main2Theme();}
private void main2Theme() {
setContentView(R.layout.main_new);
Button Button100 = (Button)findViewById(R.id.Button100);
Button113.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent i = new Intent(this, OtherScreenName.class);
startActivity(i);
}
}); //and so on for 15 buttons
我的OtherScreenName.class是:
public class OtherScreenName extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Theme();
}
@SuppressWarnings("null")
private void Theme() {
Log.d("SnowReportApp","Do first thing");
setContentView(R.layout.otherscreenname); //THIS CHANGES IN EVERY CLASS DEPENDING ON THE ID OF THE BUTTON
String result = "";
InputStream is = null;
StringBuilder sb=null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();//() before
nameValuePairs.add(new BasicNameValuePair("ski_id","OtherScreenName"));
TextView text1 = (TextView) findViewById(R.id.otherscreenname_1);
//THESE 2 CHANGE DEPERNDING ON THE BUTTON PRESSED
//perform action.....
//AND ALSO HERE I NEED THE ID OF THE BUTTON
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(OtherScreenName.this,MyActivity.class);
startActivity(i);
}
});
任何人都可以建议如何向我的类提供参数以及它们的类型应该是什么?
最佳答案
如果我正确理解你的问题,你想将参数传递给 Activity 。通常它会通过类构造函数来完成,但是, Activity 不能有用户定义的构造函数,只能有默认的构造函数;它们只能通过 Intent 创建间接实例化。如果您需要在 Activity 之间传递数据,请通过将额外内容放入 bundle 来实现,例如:
bundle.putInt("intName",intValue);
然后您可以通过以下方式从 bundle 中提取数据
int intValue = bundle.getInt("intName");
开始 Activity 前添加额外内容:
Intent i = new Intent(this, YourActivity.class);
Bundle b = new Bundle();
b.putInt("intName",intValue);
i.putExtras(b);
startActivity(i);
然后在 onCreate 方法中读取额外内容:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
int intValue;
if (b != null)
{
intValue= b.getInt("intName");
}
}
以同样的方式,您可以传递其他数据类型,如字符串 boolean 值等。如果这还不够,并且您需要传递一些更复杂的数据,则使用 Parcelable interface .
关于java - 让我的类(class)进行争论,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8810943/