我對這個簡單的代碼有問題。我嘗試了一切可能,但setContent(R.layout.main)總是會導致錯誤。如果我嘗試調試代碼svgView =(SVGView)findViewById(R.id.svgview)值始終爲空。ImageView findViewById和setContent(R.layout.main)不起作用
這是我的代碼:
SVGViewActivity.java:
package android.svgview;
import com.larvalabs.svgandroid.SVG;
import com.larvalabs.svgandroid.SVGParser;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
public class SVGViewActivity extends Activity {
/** Called when the activity is first created. */
private SVGView svgView;
private ViewListener viewListener;
private ViewState viewState;
private SVG svg;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
svgView = (SVGView)findViewById(R.id.svgview);
viewListener = new ViewListener();
viewState = new ViewState();
svgView.setViewState(viewState);
svgView.setOnTouchListener(viewListener);
viewListener.setViewState(viewState);
svg = SVGParser.getSVGFromResource(getResources(), R.drawable.android);
svgView.setImageDrawable(svg.createPictureDrawable());
svgView.setBackgroundColor(Color.WHITE);
}
}
SVGView.java
package android.svgview;
import java.util.Observable;
import java.util.Observer;
import android.content.Context;
import android.graphics.Canvas;
import android.widget.ImageView;
public class SVGView extends ImageView implements Observer {
private ViewState viewState;
public SVGView(Context context) {
super(context);
}
public void setViewState(ViewState viewState){
if(this.viewState==null){
this.viewState = viewState;
this.viewState.addObserver(this);
}
}
protected void onDraw(Canvas canvas){
canvas.scale(1.0f, 1.0f);
canvas.translate(viewState.getX(), viewState.getY());
super.onDraw(canvas);
}
public void update(Observable observable, Object data) {
invalidate();
}
}
和main.xml中
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<android.svgview.SVGView
android:id="@+id/svgview"
/>
</LinearLayout>
當我改變svgView = (SVGView)findViewById(R.id.svgview);
爲svgView = new SVGView(this);
然後setContentView(R.layout.main);
爲setContentView(svgView);
一切工作正常。但是使用main.xml會導致錯誤。
我嘗試清理並重新編譯項目,將其編譯爲新的Eclipse安裝包,但沒有任何更新。我不知道在哪裏出了問題: -/
請附上您收到的錯誤 - 理想來回堆棧跟蹤m logcat。 –