我正在使用一个简单的 Vertical SeekBar,如果我在 onCreate 函数上启动它,它就可以正常工作。但是,如果我在不同的线程上启动 SeekBar,则拇指位置不会按预期工作。
我用来启动 SeekBar 的代码:
public class MainActivity extends Activity {
AbsoluteLayout mainLayout;
VerticalSeekBar seekBar;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
mainLayout=(AbsoluteLayout)findViewById(R.id.main_layout_id);
Thread thread1 =new Thread(runnable1);
thread1.start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private Runnable runnable1 = new Runnable(){
@Override
public void run() {
seekBar=new VerticalSeekBar(context);
loadMainScreen.sendEmptyMessage(0);
}
};
Handler loadMainScreen = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
AbsoluteLayout.LayoutParams parameters = new AbsoluteLayout.LayoutParams(40,200,150,30);
mainLayout.addView(seekBar,parameters);
}
};
}
我认为问题不在 SeekBar 上,但无论如何我都会显示代码。
public class VerticalSeekBar extends SeekBar implements OnSeekBarChangeListener {
public VerticalSeekBar(Context context) {
super(context);
this.setOnSeekBarChangeListener(this);
}
public VerticalSeekBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public VerticalSeekBar(Context context, AttributeSet attrs) {
super(context, attrs);
}
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(h, w, oldh, oldw);
}
@Override
protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(heightMeasureSpec, widthMeasureSpec);
setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
}
protected void onDraw(Canvas c) {
c.rotate(-90);
c.translate(-getHeight(), 0);
super.onDraw(c);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (!isEnabled()) {
return false;
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
setProgress(getMax() - (int) (getMax() * event.getY() / getHeight()));
onSizeChanged(getWidth(), getHeight(), 0, 0);
break;
case MotionEvent.ACTION_CANCEL:
break;
}
return true;
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO Auto-generated method stub
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
我尝试将传递给变量上下文的上下文更改为 getApplicationContext() 和 getBaseContext() 但它不起作用。
如果我将初始化放在 runOnUiThread 上,它会崩溃,因为当我尝试添加到布局时 SeekBar 未初始化。如果我将初始化和 addView 都放在 runOnUiThread 上,它可以工作,但这不是我想要的。
我想知道我是否可以对 Context 做些什么来使其工作。欢迎任何不同的想法。
提前致谢