我正在尝试在主要活动上显示2个(和更多)方格,并在点击其中一个方格时显示一条消息,其中包含方形的数字。我的问题是只显示第一个方块(屏幕上只有一个蓝色方块,仅此而已)。
MainActivity
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.blank);
final LinearLayout mContainer = (LinearLayout)findViewById(R.id.blank);
View sq1 = new MyView(this, 0, 100, 100, Color.BLUE);
View sq2 = new MyView(this, 1, 200, 200, Color.GREEN);
mContainer.addView(sq1,0);
mContainer.addView(sq2,1);
}}
可绘制的课程
public class MyView extends View implements OnClickListener{
private final Context context;
private final int index;
private ShapeDrawable mDrawable;
public MyView(Context context, int index, int xPos, int yPos, int color) {
super(context);
this.index = index;
this.context = context;
setOnClickListener(this);
int x = xPos;
int y = yPos;
int width = xPos;
int height = yPos;
mDrawable = new ShapeDrawable(new RectShape());
mDrawable.getPaint().setColor(color);
mDrawable.setBounds(x, y, x + width, y + height);
}
protected void onDraw(Canvas canvas) {
mDrawable.draw(canvas);
}
public void onClick(View v) {
Toast.makeText(context, index+1+". view clicked.", Toast.LENGTH_SHORT).show();
}}
blank.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/blank">
</LinearLayout>
答案 0 :(得分:1)
您的例子中遗漏了两件事:
首先:您必须将LayoutParams设置为您的视图。
LayoutParams paramsSq1 = new LayoutParams(100,100);
LayoutParams paramsSq2 = new LayoutParams(200,200);
View sq1 = new MyView(this, 0, 100, 100, Color.BLUE);
sq1.setLayoutParams(paramsSq1);
View sq2 = new MyView(this, 1, 200, 200, Color.GREEN);
sq2.setLayoutParams(paramsSq2);
mContainer.addView(sq1, 0);
mContainer.addView(sq2, 1);
其次:从原点(0,0)绘制形状。
public MyView(Context context, int index, int xPos, int yPos, int color) {
super(context);
this.index = index;
this.context = context;
setOnClickListener(this);
int x = 0;
int y = 0;
int width = xPos;
int height = yPos;
mDrawable = new ShapeDrawable(new RectShape());
mDrawable.getPaint().setColor(color);
mDrawable.setBounds(x, y, x + width, y + height);
}
答案 1 :(得分:0)
我认为您需要为LayoutParams
的孩子设置LinearLayout
。
试试这个:
LinearLayout mContainer = (LinearLayout) findViewById(R.id.blank);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mContainer.addView(sq1, params);
mContainer.addView(sq2, params);