package com.example.paul_2.a5aprilie;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout root = new LinearLayout(this);
root.setOrientation(LinearLayout.VERTICAL);
root.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
setContentView(root);
Button btn1= new Button(this);
btn1.setText("Click Me");
root.addView(btn1);
LinearLayout linearContainer=new LinearLayout(this);
linearContainer.setOrientation(LinearLayout.HORIZONTAL);
linearContainer.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
root.addView(linearContainer);
final LinearLayout firstRow = new LinearLayout(this);
firstRow.setOrientation(LinearLayout.VERTICAL);
firstRow.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
linearContainer.addView(firstRow);
ImageView fiora = new ImageView(this);
fiora.setBackgroundResource(R.drawable.fiora);
ImageView katarina= new ImageView(this);
katarina.setBackgroundResource(R.drawable.katarina);
ImageView lb=new ImageView(this);
lb.setBackgroundResource(R.drawable.lb);
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(200,120);
// params1.leftMargin =0;
// params1.topMargin = 0;
firstRow.addView(fiora,params1);
firstRow.addView(katarina,params1);
firstRow.addView(lb,params1);
LinearLayout secondRow = new LinearLayout(this);
secondRow.setOrientation(LinearLayout.VERTICAL);
secondRow.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT));
linearContainer.addView(secondRow);
secondRow.addView(lb,params1);
secondRow.addView(fiora,params1);
secondRow.addView(katarina,params1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Animation animSlide = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.slide);
firstRow.startAnimation(animSlide);
}
});
}
}
我想要显示这些图像两次(在两种不同的布局中),但只能使用“firstRow”。当我在“secondRow”中尝试addView
图像时,我的应用程序崩溃了。有人可以解释我为什么以及如何做到这一点?
答案 0 :(得分:0)
错误是第二行中添加的项目已经附加。因此,您应该再次创建视图并将其添加到第二行。
此外,您应该更改行的布局参数:
firstRow.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
也许你的LinearLayouts方向有误,因为现在有两列代替行。
P.S。为什么不使用xml?