사용자가 올바른 버튼을 선택해야 하는 이미지를 무작위로 표시하는 앱을 만들고 있습니다. 이미지가 설정되면 태그도 설정합니다. 그런 다음 태그를 가져와 조건과 비교하고 일치하는 경우 버튼 텍스트를 변경하려고 합니다. 그러나 true 문에 대한 조건부 논리가 작동하지 않고 else가 실행 중입니다.
//the initial image view and button in question
<ImageView
android:id="@+id/imageView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:tag="bicycle"
app:srcCompat="@drawable/bicycle" /> <Button
android:id="@+id/button_one_way"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="@string/one_way"
style="?android:attr/buttonBarButtonStyle" />
//the java setter
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button oneWayButton, startButton;
oneWayButton= (Button) findViewById(R.id.button_one_way);
startButton= (Button) findViewById(R.id.button5);
startButton.setOnClickListener(new View.OnClickListener() {
ImageView image= (ImageView) findViewById(R.id.imageView2);
@Override
public void onClick(View view) {
image.setImageResource(R.drawable.one_way);
image.setTag("one_way");
}
//the getter and logic
oneWayButton.setOnClickListener(new View.OnClickListener() {
ImageView image= (ImageView) findViewById(R.id.imageView2);
String imageName= (String) image.getTag();
@Override
public void onClick(View view) {
if (imageName.equals("one_way")){ //this statement is not executing
oneWayButton.setText("Correct!");
oneWayButton.setTextColor(Color.GREEN);
}
else{
oneWayButton.setText("Incorrect!");
oneWayButton.setTextColor(Color.RED);
}
}
});
감사 해요. 효과가 있었다!
KillerSheltie2022-02-15 09:39:13
문자열 이동 imageName= (String) image.getTag(); 먼저 onClick() 메서드에 줄을 넣습니다. 지금 가지고 있듯이 시작할 때 한 번만 태그를 잡습니다.
Mike M.2022-02-15 09:39:13