我很难把观点放在主要活动上,我所做的是,
我有一个文件lines.java,在这个文件中,我们有绘制圆的所有功能,这个圆类扩展了视图
如下所示
public class Lines extends View {
Paint paint = new Paint();
public Views(Context context) {
super(context);
paint.setColor(Color.BLACK);
}
@Override
protected void onDraw(Canvas canvas)
{
canvas.drawLine(0, 0, 20, 20, paint);
System.out.println("called");
}}
现在在mainactivity中,我正在创建这个circle类的一个对象,并将其放入setcontentview(obj)中;
下面是它的代码片段
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Linesobj=new Lines(getApplicationContext());
setContentView(obj);
}
}
当我这样做的时候,它占据了整个屏幕的位置,我不想这样,我想把它放在我试图通过xml使用this链接的主活动中,我附上了一张主活动的图片,我想把这个视图放在活动的中间
红色矩形显示要放置Lines类的位置(即视图)
感谢您的帮助!!
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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.compoundview.MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Line" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Free" />
</LinearLayout>
<com.example.compoundview.Views
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
最佳答案
它接管整个视图的原因是,这就是您调用setContentView
时所做的操作。从文档中:
将活动内容设置为显式视图。此视图直接放置在活动的视图层次结构中。
因此,XML中的任何内容(无论是LinearLayout、RelativeLayout还是其他什么内容)都将被自定义视图替换。要解决此问题,需要以编程方式将视图添加到现有布局中。例如,如果您有一个线性布局,您可以这样添加圆:
LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.my_linear_layout);
mLinearLayout.addView(obj);
以下是addView的文档。相对而言,它看起来会有点不同。我会引用this question。
通过你的编辑,我发现你有一个相对的布局和一个线性布局。因此,您编程使用哪条路径将取决于您希望将对象放置在视图层次结构中的位置,这完全取决于您自己。