我在我的Android應用程序中有一個字符串生成器函數。我希望每次有「輕敲」或「觸摸」時調用字符串生成器函數。字符串生成器函數將更改文本標籤中的字符串。我沒有任何類型的錯誤,但是當我在Android模擬器和物理設備上測試應用程序時,文本標籤中的字符串沒有更改,這意味着字符串生成器函數未被調用。如何正確使用Android OnTouchListener和OnTouch功能?
這裏是我的代碼如下所示:
public class MainActivity extends Activity{
//member variables
private ExcuseGenerator mExcuseGenerator = new ExcuseGenerator();
private ImageView mMrExcuse;
private TextView mExcuse;
private RelativeLayout rl;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMrExcuse = (ImageView) findViewById(R.id.imageView1);
mExcuse = (TextView) findViewById(R.id.textView1);
rl = (RelativeLayout) findViewById(R.id.rl1);
rl.setOnTouchListener(
new View.OnTouchListener(){
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP){
//here is the string generator function
excuseGenerator();
return true;
}
return false;
}
}
);
}
注:我想水龍頭/倒是可以在屏幕上的任何地方檢測到,這就是爲什麼我使用了OnTouchListener相對佈局。
編輯:添加屏幕截圖顯示XML文件。
編輯2:這裏是我的excuseGenerator功能:
private void excuseGenerator(){
String excuse = mExcuseGenerator.getExcuse();
mExcuse.setText(excuse); //mExcuse is a text label.
}
這裏是從類mExcuseGenerator的getExcuse功能:
/*
* I want to create a "real random experience".
* This function will have 2 lists. Every time an excuse is generated,
* it is deleted from its original array and then put into a temporary array
* so that the same excuses are not to be seen over and over again.
* when the original array is emptied, it will be reassigned the set of excuses
* and the temporary array will be emptied again.
*/
public String getExcuse(){
if(stringArray.isEmpty()){
stringArray = Arrays.asList(mExcuseList);
tempHolder = null;
}
String excuse;
Random randomGenerator = new Random();
// get the position of the element from the array
int randomElement = randomGenerator.nextInt(stringArray.size());
excuse = stringArray.get(randomElement);
tempHolder.add(stringArray.get(randomElement));
stringArray.remove(stringArray.get(randomElement));
//return the element
return excuse;
}
是您的RelativeLayout表示根佈局? – Pankaj
我不知道根佈局是什麼。你指的是XML嗎? –
是的,我在談論XML。 – Pankaj