我已经制作了string-array
来保存一些短语,每当我调用class
Master
类的方法时,都应该显示这些短语。
但是当我输入Resources res = getResources();
它标志着getResources()
红色表示没有这样的方法。
相反,如果我在主要活动中输入它,一切看起来都不错。
如何 <{1}} <{1}} reference
string-array
所以我可以在我的Main
班级里面创建method
吗?
这是我的字符串数组:
Master
修改
这是我的大师班级
<string-array name="goodMorning">
<item>Good Morning folks!</item>
[...]
<item>Be beep. Be beep. %s wake up!</item>
</string-array>
这是我的主要活动
public class Master extends Player {
private String mName;
private Context context;
public String getmName(){
return mName;
} // Get Master's name
public static int randInt(int min, int max) { //Get a random int between two values
// Usually this can be a field rather than a method variable
Random rand = new Random();
// nextInt is normally exclusive of the top value,
// so add 1 to make it inclusive
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public Master(Context c){ //it's your contsructor method
this.context = c;
}
public void goodMorning() { // Get a random phrase from a String-Array and display it to the user
int randomNumber = randInt(0, 8); //Random Number
String[] arrayPhrases = context.getResources().getStringArray(R.array.goodMorning); // String-Array with 'morning phrases
List<String> listPhrases = new ArrayList<>(); // List
Collections.addAll(listPhrases, arrayPhrases); // Insert the String-Array in the List
String randomPhrase = listPhrases.get(randomNumber); // Get the random phrase
System.out.printf(randomPhrase); // Display it
}
}
问题是当我调用public class MainActivity extends AppCompatActivity {
Master m = new Master(this);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
m.goodMorning();
}
时,它无法识别goodMorning()方法,有什么想法吗?
答案 0 :(得分:0)
你可以这样做。
您的 MainActivity
public class MainActivity extends Activity()
{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContextView(R.layout.yourlayout);
/*
Your operations
*/
}
private void createClass()
{
YourMaster yourMaster = new YourMaster(MainActivity.this);
yourMaster.doSomething();
}
}
<强> YourMaster.Class 强>
public class YourMaster
{
private Context context;
YourMaster(Context _context) //it's your contsructor methot
{
this.context = _context;
}
private void doSomething()
{
context.getResources().getStringArray(R.array.goodMorning);
//your array is yours now.
}
}