2016-08-13 76 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