我的TextView看不到
我想在屏幕上看到一个Button
对象,一个TextView
对象和一个MyView
对象。 但是只能出现Button
对象和MyVıew
对象。 我认为,MyView与TextView重叠(在TextView
上方)。 因为如果我不添加( b.addView(a);
) MyView
对象到我的布局, Button
和TextView
对象出现在屏幕上。 但是,如果我添加( b.addView(a);
)MyView,TextView不见了。 我怎么解决这个问题?
MyView.java文件:
package com.example.mehmet.catchtheball; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.view.View; public class MyView extends View { public MyView(Context context) { super(context); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint paint = new Paint(); paint.setColor(Color.WHITE); canvas.drawPaint(paint); paint.setColor(Color.parseColor("lightGray")); canvas.drawCircle(500, 500, 150, paint); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); } public MyView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } }
Customer.java
文件:
package com.example.mehmet.catchtheball; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; public class Customer extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_customer); MyView a = new MyView(this); RelativeLayout b = (RelativeLayout)findViewById(R.id.relativeLayout); b.addView(a); // If I do this , TextView gone. final TextView label = (TextView) findViewById(R.id.textView3); label.setText("HelloEveryOne"); // My TextView a.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View view, MotionEvent motionEvent) { return true; } }); } }
activity_customer.xml
文件:
试试这个activity_customer.xml:
在textView3下面添加一个LinearLayout作为容器,然后添加全部
在你发布的XML中,添加一个与layout_belowOf = textView3,在你的代码中你做的b.addView(a)替换为:LinearLayout c = findViewById(R.id.ll_c_container)和c.addView(a)
如果你想要所有的组件都在一个线性的轴上,你可以只有一个线性布局(所有的addViews将被添加到最后一个视图的下面)
在你的java类只是做这一个(对不起,我正在写kotlin代码
MyView a = new MyView(this); val params = RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) params.addRule(RelativeLayout.BELOW, textView3.id) params.addRule(RelativeLayout.ALIGN_PARENT_START, RelativeLayout.TRUE) relativeLayout.addView(textView, params)