我正在做一些测试,以简单地根据三个滑块作为主要活动中的RGB值更改文本颜色。问题在于无法在滑块上设置我的自定义侦听器。这是我的代码。另外,所有需要导入的东西都被导入了,只是没有包含它们,因为这里的代码插入东西不喜欢它。
public class MainActivity extends AppCompatActivity {
int[] currentCol = {0, 0, 0};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
SeekBar Red = (SeekBar) findViewById(R.id.R);
SeekBar Blue = (SeekBar) findViewById(R.id.B);
SeekBar Green = (SeekBar) findViewById(R.id.G);
TextView textBox = (TextView) findViewById(R.id.colorText);
OnSeekBarChangeListener customListener = new OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar name, int progress, boolean fromUser) {
if (name == Red) {
currentCol[0] = progress;
} else if (name == Blue) {
currentCol[1] = progress;
} else if (name == Green) {
currentCol[2] = progress;
}
textBox.setTextColor(Color.rgb(currentCol[0], currentCol[1], currentCol[2]));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
};
public void setCustomListener(OnSeekBarChangeListener customListener) {
this.customListener = customListener;
}
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);
}
}
最佳答案
首先添加implements OnSeekBarChangeListener{
公共类MainActivity扩展了AppCompatActivity实现
OnSeekBarChangeListener {
在oncreate()函数中调用它
SeekBar Red = (SeekBar) findViewById(R.id.R);
SeekBar Blue = (SeekBar) findViewById(R.id.B);
SeekBar Green = (SeekBar) findViewById(R.id.G);
Red.setOnSeekBarChangeListener(this); // set seekbar listener.
练习演示
Android SeekBar Example