所以我试图在android studio中实现一个简单的类,它以微调器的形式获取用户输入并相应地改变文本的颜色。但是,即使满足条件,从调试行可以看出,程序也不会执行if语句的内容。 debugging line
'import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class Colour extends AppCompatActivity {
TextView tv;
Spinner mySpinner;
ArrayAdapter<CharSequence> adapter;
public static final String EXTRA_MESSAGE = "message";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_colour);
Intent intent = getIntent();
String messageText = intent.getStringExtra(EXTRA_MESSAGE);
tv = (TextView)findViewById(R.id.message);
tv.setText(messageText);
mySpinner = (Spinner) findViewById(R.id.spinner);
adapter = ArrayAdapter.createFromResource(this,R.array.colours,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(adapter);
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), parent.getItemIdAtPosition(position)+ " selected",Toast.LENGTH_LONG).show();
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void change(View v){
String text = mySpinner.getSelectedItem().toString();
if(text == "Red"){
tv.setTextColor(Color.RED);
}
if(text == "Blue"){
tv.setTextColor(Color.BLUE);
}
if(text == "Green"){
tv.setTextColor(Color.GREEN);
}
}'
'<TextView
android:textColor="#000000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/message" />
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="@array/colours"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:id="@+id/spinner" />
<Button
android:text="HOME"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:onClick="home"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="52dp" />
<Button
android:text="changeColour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button4"
android:layout_above="@+id/button"
android:layout_alignStart="@+id/button"
android:layout_marginBottom="101dp"
android:onClick="change" />'
答案 0 :(得分:0)
if(text.equals("Red"))
等
因为text是String类型的对象,所以它不是基本类型
原始类型可以使用==而不是引用类型进行比较