Android从其他布局膨胀视图

时间:2015-04-04 13:49:39

标签: android android-layout view

我对Android开发相对较新,我试图找到一种方法在每次按下按钮时,在不同位置重复充气视图,因此每个充气视图都有自己的位置:

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class teamCreateScreen extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.team_locate_layout);
}
public void createTeam(View view) {
    final RelativeLayout rlTeam = (RelativeLayout) findViewById(R.id.rlTeam);
    View teamBox = View.inflate(this, R.layout.team_box, rlTeam);

    final TextView teamBoxView = (TextView) findViewById(R.id.team_task_box);
    teamBoxView.setX(0);
    teamBoxView.setY(230);
}
}

布局的XML代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rlTeam">

<Button
    android:layout_width="60dp"
    android:layout_height="60dp"
    android:id="@+id/teamAddBtn"
    android:text="+"
    android:textSize="30sp"
    android:onClick="createTeam"/>

</RelativeLayout>

被夸大的观点的XML代码:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
    android:layout_width="192dp"
    android:layout_height="120dp"
    android:id="@+id/team_task_box"
    android:text="New Team" />

</RelativeLayout>

我想使用相同的视图来扩充布局中具有不同坐标的多个框。每当我按下按钮再次给视图充气时,它会以相同的坐标对盒子进行充气,使它们重叠。我需要让第二个盒子出现在第一个盒子的右边,第三个盒子出现在第一个盒子下面,依此类推,就像一个盒子网格。

1 个答案:

答案 0 :(得分:0)

试试这段代码并告诉我它是否有效。删除布局的膨胀

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class teamCreateScreen extends Activity {

int i=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.team_locate_layout);
}
public void createTeam(View view) {
   final RelativeLayout rlTeam = (RelativeLayout) findViewById(R.id.rlTeam);
   RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
   TextView tv=new TextView(getApplicationContext());
   if(tv.getId()>0) {
      relativeParams.addRule(RelativeLayout.BELOW, tv.getId());
   }
   tv.setId(i);
   r1Team.addView(tv, relativeParams);
   i++;
}
}

int i = 0; 声明为全局变量,并在 createTeam()方法中将其递增。