android自定义view(1)

这节是基本的自定义view知识

MainActivity.java中的代码

public class MainActivity extends Activity {

private Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,GActivity.class);
startActivity(intent);
}
});
}

activity_main.xml中代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >
    
    <Button
android:id="@+id/btn"        
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/iv"
android:text="确定"
android:onClick="onClick"
        />
</RelativeLayout>

GActivity.java中的代码

//注:在清单文件里注册GActivity

public class GActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(new Image1(this));
super.onCreate(savedInstanceState);
}
class Image1 extends View{

//画笔
private Paint paint;

public Image1(Context context) {
super(context);
// TODO Auto-generated constructor stub
}

@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);

paint = new Paint();
paint.setFlags(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.BLACK);
canvas.drawText("画无规则图形", 150, 30, paint);
//画圆
paint.setColor(Color.GREEN);
canvas.drawCircle(300, 300, 100, paint);
//画矩形
paint.setColor(Color.RED);
canvas.drawRect(10, 120, 150, 200, paint);
}
}
}

android自定义view(1)_第1张图片



你可能感兴趣的:(android自定义view(1))