[英]How to make Image Views centre in a linear layout inside a Horizontal Scroll View?
I have ImageViews programmatically being added to the linear layout and want these centered in the linear layout, but the layout itself aligned to the left.我以编程方式将 ImageViews 添加到线性布局中,并希望它们在线性布局中居中,但布局本身与左侧对齐。
And in your code, obtain your LinearLayout:在您的代码中,获取您的 LinearLayout:
LinearLayout yourLinearLayout = (LinearLayout) findViewById(R.id.yourLinearLayout);
Define a common LayoutParams object:定义一个通用的LayoutParams object:
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
And add your ImageViews to your LinearLayout with a for loop:并使用 for 循环将您的 ImageViews 添加到您的 LinearLayout 中:
for (int i = 0; i < imagesToAdd.size(); i++) {
ImageView imgView = new ImageView(this);
imgView.setImageResource("yourResourceID" + i);
imgView.setLayoutParams(layoutParams);
yourLinearLayout.addView(imgView);
}
Create a Layout with a HorizontalScrollView
as a root view and a LinearLayout
as a child创建一个以 Horizo
HorizontalScrollView
作为根视图并以LinearLayout
作为子视图的布局
To center images, make sure to use android:gravity="center"
in the LinearLayout
要居中图像,请确保在
LinearLayout
中使用android:gravity="center"
<?xml version="1.0" encoding="utf-8"?>
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rootlayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="horizontal">
<LinearLayout
android:id="@+id/linearlayout"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal">
</LinearLayout>
</HorizontalScrollView>
And to add images programmatically, inflate the LinearLayout
and use addView()
method并以编程方式添加图像,膨胀
LinearLayout
并使用addView()
方法
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout linearLayout = findViewById(R.id.linearlayout);
linearLayout.addView(getImage(R.drawable.image1));
linearLayout.addView(getImage(R.drawable.image2));
linearLayout.addView(getImage(R.drawable.image3));
}
ImageView getImage(int drawable) {
ImageView image = new ImageView(this);
image.setLayoutParams(new
LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
image.setImageResource(drawable);
return image;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.