2016-08-13 71 views
0

类似的应用程序。我有一个由xml文件设置的顶部栏,在运行时,我想创建一些直接在它下面的文本视图。此外,还会有一个按钮在点击时添加新的文本视图。Android的地方视图动态相对视图

当我从按钮创建新的文本视图时,如何确保新的Textview保持在我创建的静态文本视图和/或布局下。现在不是,它只是重叠。

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

    Button btn = (Button) findViewById(R.id.Add_new); 

    btn.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      AddNewTask(v); 
     } 
    }); 
} 

我想这两个选项添加一个新的TextView和他们都只是overalpp,我无法找到一个方法的任何文件,如下面/下方,最让我能看到的是刚下车的顶部和底部对齐这将不会在这种情况下是有用的

public void AddNewTask(View v) { 
    RelativeLayout rl = (RelativeLayout) findViewById(R.id.overallview); 
    TextView tv= new TextView(this); 
    tv.setText("TEST"); 
    rl.addView(tv); 
} 

我的XML

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:app="http://schemas.android.com/apk/res-auto" 
xmlns:tools="http://schemas.android.com/tools" 
android:id="@+id/overallview" 
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" 
app:layout_behavior="@string/appbar_scrolling_view_behavior" 
tools:context="com.example.robertli.hustle.MainActivity" 
tools:showIn="@layout/activity_main" 
android:background="#00095e"> 

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:background="@android:color/white" 
    android:id="@+id/topbar" 
    > 

    <TextView 
     android:id="@+id/app_name" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:maxLines="2" 
     android:text="Hustle" 
     android:textSize="25dp" /> 
</LinearLayout> 

<Button 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="+" 

    android:layout_below="@id/topbar" 
    android:id="@+id/Add_new" 
    android:background="#00095e" 
    android:textColor="#ffffff" 
    android:clickable="true" 
    android:textSize="50dp" /> 

+0

检查此链接 - https://stackoverflow.com/questions/2305395/how-to-lay-out-views-in-relativelay出编程?RQ = 1 –

回答

0

建议:你应该看看ListView来做到这一点! ListView也可以帮助您动态添加文本视图。

如果你仍然想直接添加到RelativeLayout的 参考下面这个例子:

 RelativeLayout relativeLayout = new RelativeLayout(context); 
     View view = new View(context); 
     relativeLayout.addView(view); 

代码,以动态的RelativeLayout的

 RelativeLayout.LayoutParams viewLayoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams(); 
     viewLayoutParams.addRule(RelativeLayout.BELOW, R.id.your_view); 

添加排列看看文档更 https://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html