从活动中调用另一活动的方法 [英] Calling a method in another activity from an activity
问题描述
好了,所以第一关,我知道,你不能从另一个活动的活动,多数民众赞成调用一个方法。我只是试图找出解决这个问题的最好办法。我是新来的Android编程,所以我道歉,如果这是明显的东西。
Ok so first off I know that you can't call a method from an Activity thats in another Activity. I'm just trying to figure out the best way around this. I'm new to android programming so I apologize if it is something obvious.
下面是我的code。这是方法,我试图打电话。这是我的记分卡的活动。
Here is my code. This is the method I am trying to call. It is in my ScoreCard activity.
public void numPlayerSetup(){
{
int[] ids = {
R.id.TextView11, R.id.TextView12, R.id.TextView13
};
for(int i : ids) {
TextView tv = (TextView)findViewById(i);
tv.setVisibility(View.INVISIBLE);
}
}
}
下面是我如何想调用的方法。分数是记分卡类的一个对象。
Here is how I am trying to call the method. score is an object of the ScoreCard class.
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
int item = spinner.getSelectedItemPosition();
if(item==1){
Log.i("error","This Sucks");
score.numPlayerSetup();
}
}
我试图把numPlayerSetup方法在不同的班级。这不会扩大活动,只包含了逻辑,但不延长活动我无法使用findViewById()方法。
I tried to put the numPlayerSetup method in a different class. That would not extend Activity, just contain the logic, but I can't use the findViewById() method without extending activity.
我希望我的问题是清楚的。感谢您的帮助!
I hope my question is clear. Thanks for the help!
@ninjasense
@ninjasense
这是我如何调用它。
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
int item = spinner.getSelectedItemPosition();
ArrayList<TextView> myTextViewList = new ArrayList<TextView>();
TextView tv1 = (TextView)findViewById(R.id.TextView14);
myTextViewList.add(tv1);
if(item==1){
Log.i("error","This Sucks");
Setup.numPlayerSetup(myTextViewList);
}
那么这是类我打电话。
Then this is the class I am calling.
public class Setup {
TextView tv;
public static void numPlayerSetup(ArrayList<TextView> tvs){
for(TextView tv : tvs) {
Log.i("crash","This Sucks");
tv.setVisibility(View.INVISIBLE); //this line is highlighted in the debugger as the line my error is coming from
}
}
}
它记录在logcat的消息,并给了我一个空指针异常。调试器说,电视值为null。这究竟是为什么我得到一个空指针异常?
It logs the message in the logcat and gives me a null pointer exception. The debugger says that the value for tv is null. Is this why I am getting a null pointer exception?
推荐答案
您可以只需打个Utitlity类(不活动)并传入你想改变Textviews。而当您需要它调用该方法。
You can just make a Utitlity class(not Activity) and pass in the Textviews you wish to change. and call that method whenever you need it.
public class Setup {
public static void numPlayerSetup(ArrayList<TextView> tvs){
for(TextView tv : tvs) {
tv.setVisibility(View.INVISIBLE);
}
}
}
然后你可以使用它像(以活动):
Then you can use it like(in Activity):
ArrayList<TextView> myTextViewList = new ArrayList<TextView>();
TextView tv1 = (TextView)findViewById(R.id.tv1);
myTextViewList.add(tv1);
Setup.numPlayerSetup(myTextViewList);
这篇关于从活动中调用另一活动的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!