我无法以编程方式调用布局,我尝试在 xml 中使用 include 及其工作
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:id="@+id/btnTes"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/LL1"
android:orientation="vertical">
<include layout="@layout/extend">
</include>
<include layout="@layout/extend">
</include>
</LinearLayout>
但我想以编程方式创建它 这是我的扩展 XML:
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/textView" />
<TextView
android:text="TextView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/textView2" />
这是我的java:
public class MainActivity extends AppCompatActivity {
Button btnTes;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ViewGroup tes = (ViewGroup) findViewById(R.id.LL1);
btnTes = (Button) findViewById(R.id.btnTes);
final View extend = LayoutInflater.from(this).inflate(R.layout.extend,null);
btnTes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "KLIk", Toast.LENGTH_SHORT).show();
tes.addView(extend);
}
});
}
}
当我点击 btnTes 时 第一次点击它就可以了,但是当我再次点击它时,我的程序只是强制关闭。这是我的错误
FATAL EXCEPTION: main
Process: com.example.siwonhansamu.test, PID: 3796
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
谢谢
最佳答案
您无法将同一 View 添加到多个父 View 。
如果您需要多次使用该 View ,则必须复制该 View 。你可以这样做:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ViewGroup tes = (ViewGroup) findViewById(R.id.LL1);
btnTes = (Button) findViewById(R.id.btnTes);
btnTes.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "KLIk", Toast.LENGTH_SHORT).show();
final View extend = LayoutInflater.from(view.getContext()).inflate(R.layout.extend, tes, false);
tes.addView(extend);
}
});
}
关于java - 如何在android中以编程方式包含相同的布局两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40627001/