1
在我的程序中,我有一個自定義視圖對象。視圖類中有一個名爲foo的方法。出於某種原因,當我從我的活動中調用foo時,它不會觸發。下面是代碼:無法調用活動中的視圖對象的方法
自定義視圖的XML:
<com.company.application.MyView
android:id="@+id/my_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
活動代碼:
public class Main extends Activity {
MyView mView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LayoutInflater li = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.main, null);
mView= (MyView) v.findViewById(R.id.my_view);
//A button to fire the method inside foo()
Button switchLeft = (Button) findViewById(R.id.switch_left);
switchLeft.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
callTest();
}
});
}
public void callTest() {
Log.w(this.getClass().getName(), "clicked left arrow");
mView.foo();
mView.postInvalidate();
}
}
最後這裏FOO:
public void foo() {
mBackground = mContext.getResources().getDrawable(R.drawable.temp_canvas);
Log.w(this.getClass().getName(), "background set");
}
第一個日誌始終當按下按鈕時寫入,但第二個日誌不是因爲foo從不會觸發。這裏的交易是什麼?
在此先感謝所有。
編輯:根據要求,在衆目睽睽
public class MyView extends View {
Drawable mBackground;
Context mContext;
public MyView (Context context) {
super(context);
mContext = context;
mBackground = mContext.getResources().getDrawable(R.drawable.leftarrow1);
}
public MyView (Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
mBackground = mContext.getResources().getDrawable(R.drawable.leftarrow1);
}
public void foo() {
mBackground = mContext.getResources().getDrawable(R.drawable.temp_canvas);
Log.w(this.getClass().getName(), "background set");
}
@Override
public void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
// draw a solid blue circle
paint.setColor(Color.BLUE);
canvas.drawCircle(20, 20, 15, paint);
// draw a test background
mBackground.setBounds(0, 0, 300, 400);
mBackground.draw(canvas);
}
}
我們需要看MyView的代碼 – Falmarri 2010-11-07 19:43:12
問,你們應該得到。謝謝! – user432209 2010-11-07 20:11:49
這可能很明顯,但您是否嘗試使用調試程序遍歷代碼?如果這是不可能的,是否在設置背景(但在foo內)以及另一個日誌級別(例如調試或信息)之前嘗試寫入日誌? – 2010-11-07 20:22:22