如何在android中调用另一个类?
我有个问题。我不知道如何称呼不同的班级。这段代码是一个按钮的代码(当你点击按钮时,会随机出现一条消息),所以我认为如果我把它放在一个不同的类中会更好,因为我也使用了数组。现在我不知道如何调用这个类 这是我的代码。我想在SecondActivity中调用“Firstin”如何在android中调用另一个类?,android,clicklistener,Android,Clicklistener,我有个问题。我不知道如何称呼不同的班级。这段代码是一个按钮的代码(当你点击按钮时,会随机出现一条消息),所以我认为如果我把它放在一个不同的类中会更好,因为我也使用了数组。现在我不知道如何调用这个类 这是我的代码。我想在SecondActivity中调用“Firstin” public class SecondActivity extends Activity { private Firstin mFirst = new Firstin (); @Override protecte
public class SecondActivity extends Activity {
private Firstin mFirst = new Firstin ();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//finds textview
final Text Ftext = (Text) findViewById(R.id.textView2);
@SuppressWarnings("unused")
final Text Stext = (Text) findViewById(R.id.textView3);
//finds button view
Button btnView = (Button) findViewById(R.id.button1);
@SuppressWarnings("unused")
Button btnView2 = (Button) findViewById(R.id.button2);
btnView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String Answer = mFirst.firstAnswer();
Ftext.setTextContent(Answer);
}
});
这是我想呼叫的班级:
package com.example.insultgenerator;
import java.util.Random;
public class Firstin {
public String firstAnswer(){
String [] mResults={
"its cool",
"we cool",
"im cool",
"he cool",
"she cool"
};
// the button was clicked so replace the answer label with answer
String Answer = "" ;
// the two double is a 'empty string
Random RandomGen = new Random();// telling the program to construct a random generator
int RandomNum= RandomGen.nextInt(mResults.length);
Answer = mResults[RandomNum];
return(Answer);
}
}
您应该转换到
TextView
final TextViewFtext = (TextView) findViewById(R.id.textView2);
@SuppressWarnings("unused")
final TextViewStext = (TextView) findViewById(R.id.textView3);
然后使用TextView.setText(…)方法:
然后最后使用
new Firstin().firstAnswer()
从另一个类调用该方法,该方法创建该类的实例并执行该方法。您得到的错误是什么您不能调用一个类,除非它是一个函子——但在Java中,您不能调用该类。。。你是说调用一个类的方法,对吗?还是什么?在onCreate
中实例化类!同时检查您的TextView
casts!短而精确。。繁荣
String Answer = mFirst.firstAnswer();
Ftext.setText(new Firstin().firstAnswer());
}
});