GAM*_*AMA 1 android android-layout layout-inflater
我正在开发一个应用程序,在启动时将在下面的屏幕截图中显示预定义的布局,如Image(1).
现在单击一个按钮,我想在下面的屏幕截图中动态添加另一个像Image(2)的视图到现有视图,结果如下面的截图中的Image(3).
如果再次单击onclick,Image(2)将被添加到现有视图中,从而产生类似Image(4)的内容.
我该如何实现这一目标?
通过搜索,我发现,它需要类似LayoutInflater.addView()像这样或LinearLayout.addView()像这样.
但我不知道在我的情况下究竟要使用什么.
此外,我不是只想在按钮点击上添加一个视图,而是添加一组特定视图,如imageview,2个textviews等.如图(2)所示.
任何帮助赞赏.

我试过这样的事情: activity_main.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" >
<LinearLayout
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</LinearLayout>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="20dp"
android:onClick="addViews"
android:text="Add" />
</RelativeLayout>
Run Code Online (Sandbox Code Playgroud)
MainActivity.java
public class MainActivity extends Activity {
LinearLayout main;
int count = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
main = (LinearLayout) findViewById(R.id.main);
}
public void addViews(View view) {
LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
Button btn = new Button(this);
btn.setLayoutParams(lparams);
count++;
btn.setText("Hello World : " + count);
main.addView(btn, count);
}
}
Run Code Online (Sandbox Code Playgroud)
它产生这样的东西:

现在,如何识别单击了哪个按钮?
所以,你可以从一个充气从XML布局视图Activity像这样
View v = View.inflate(this, R.layout.whatever, null);
然后你可以把它添加到你的LinearLayout喜欢这个:
linearLayout.addView(v);
如果要访问项目中的内部视图,可以这样做:
TextView textView = (TextView) v.findViewById(R.id.textView1);
因此,您必须在XML布局中定义该组视图,对其进行充气,根据需要操纵其视图,然后将其添加到您的LinearLayout.
请注意,您需要将LinearLayout方向设置为垂直方向,否则它将无法正常工作.