【发布时间】:2013-06-01 07:18:06
【问题描述】:
我正在开发一个应用程序,它在启动时会在下面的屏幕截图中显示预定义的布局,如 Image(1)。
现在单击一个按钮,我想在下面的屏幕截图中动态添加另一个视图,如 Image(2) 到现有视图中,从而生成一些类似 Image(3) 的视图如下截图。
如果再次单击 onclick,Image(2) 将被添加到现有视图中,从而生成类似 Image(4) 的内容。
我该如何实现?
通过搜索,我发现它需要LayoutInflater.addView() 之类的东西this 或LinearLayout.addView() 之类的this。
但我不知道在我的情况下到底要使用什么。
另外,我不是想在按钮点击时添加一个单一的视图,而是一组特定的视图像imageview,2个textviews等。如 Image(2) 所示。
任何帮助表示赞赏。
编辑 1:
我尝试过这样的事情: 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>
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);
}
}
它会产生这样的结果:
现在,我如何识别点击了哪个按钮?
【问题讨论】:
标签: android android-layout layout-inflater