使用数字选择器 Integer 更改 android textview 颜色

Change android textview color with number picker Integer

我是 android 的新手,我只是在接触 is。我想让数字选择器定义文本的颜色。这是目前号码选择器的代码。

package nathan.nathan;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.NumberPicker;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {
    TextView numberView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        numberView = (TextView)findViewById(R.id.numberview);
        NumberPicker numberPicker = (NumberPicker) findViewById(R.id.numberPicker);
        numberPicker.setMaxValue(100);
    numberPicker.setMinValue(0);
    numberPicker.setWrapSelectorWheel(true);
    numberPicker.setOnValueChangedListener( new NumberPicker.
            OnValueChangeListener() {
        @Override
        public void onValueChange(NumberPicker picker, int
                oldVal, int newVal) {
            numberView.setText("I am "+
                    newVal);
        }

    });
    }


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

我只是不知道该怎么做。帮助将不胜感激! :)

这取决于您如何将 0 到 100 之间的整数映射到一种颜色,但这是一种方法:

numberPicker.setOnValueChangedListener(
    new NumberPicker.OnValueChangeListener() {
    @Override
    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
        numberView.setText("I am " + newVal);

        int color;
        if (newVal < 30) {
            color = Color.parseColor("#ff0000");
        } else if (newVal < 60) {
            color = Color.parseColor("#00ff00");
        } else {
            color = Color.parseColor("#0000ff");
        }
        numberView.setTextColor(color);
    }
});

请参阅 TextView.setTextColor() 文档。