我試圖在畫布內創建一個矩形,以便它出現在屏幕的右側,但每次運行應用程序似乎都會崩潰。我真的不知道我在這裏做錯了+我的代碼中需要改變什麼?矩形沒有出現在右邊
activity_main.xml中
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView android:text="@string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<com.apptacularapps.customview.DrawView
android:id="@+id/diagram"
android:layout_width="fill_parent"
android:layout_height="52dp" />
</LinearLayout>
MainActivity.java
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DrawView drawView = new DrawView(this);
drawView.setBackgroundColor(Color.BLACK);
setContentView(drawView);
}
}
DrawView.java
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;
public class DrawView extends View {
Paint paint = new Paint();
Context context;
public DrawView(Context context) {
super(context);
this.context = context;
}
@Override
public void onDraw(Canvas canvas) {
//Code to Measure the Screen width in pixels
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
paint.setColor(Color.RED);
canvas.drawRect(0, 0, 5, canvas.getHeight(), paint);
paint.setColor(Color.RED);
canvas.drawRect(canvas.getWidth()-width, 0, 5, canvas.getHeight(), paint);
}
}
崩潰?請張貼你的logcat,今天早上我忘了我的水晶球...... – shkschneider
爲什麼我們需要你的開發環境屏幕截圖並停止消息? – weston
爲什麼問這樣的問題呢? – MacaronLover