我的MainActivity是通过水平方向设置的,它包括2个Framelayout。
<LinearLayout 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"
android:orientation="horizontal"
android:weightSum="1"
tools:context="com.example.helloandroid.MainActivity" >
<FrameLayout
android:id="@+id/framelayout1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="0.5" >
</FrameLayout>
<FrameLayout
android:id="@+id/framelayout2"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="0.5" >
</FrameLayout>
</LinearLayout>
从MainActivity.java中,frameLayout1以编程方式添加一些按钮,这些按钮通过以下代码设置为随机位置:
private void addNumbers(){ // Numbers is set with random position
for (int i = 1; i < 3; i++) {
Button btn = new Button(this);
btn.setText("" + i);
btn.setId(i);
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(50, 50);
int leftMargin = new Random().nextInt(widthScreen/2 - btnSize );
int topMargin = new Random().nextInt(heightScreen - btnSize);
lp.leftMargin = leftMargin;
lp.topMargin = topMargin;
btn.setLayoutParams(lp);
framelayout1.addView(btn);
//framelayout2.addView(btn);
}
}
我想使framelayout2具有与framelayout1相同的布局,如下图所示
那么,如何将framelayout1的布局复制到framelayout2?
以及如何识别按钮的onclick事件在framelayout1或framelayout2上?
最佳答案
尝试遵循以下示例代码,
private void addNumbers(){ // Numbers is set with random position
for (int i = 1; i < 3; i++) {
Button btn1 = new Button(this);
Button btn2 = new Button(this);
btn1.setOnClickListener(listener1);
btn2.setOnClickListener(listener2); // here using different listener
btn1.setText("" + i);
btn2.setText("" + i); //same text
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(50, 50);
int leftMargin = new Random().nextInt(widthScreen/2 - btnSize );
int topMargin = new Random().nextInt(heightScreen - btnSize);
lp.leftMargin = leftMargin;
lp.topMargin = topMargin;
btn1.setLayoutParams(lp);
btn2.setLayoutParams(lp); //same lp
framelayout1.addView(btn1);
framelayout2.addView(btn2);
}
}