很多个ImageView在RelativeLayout中放置一个横排,怎样使整体居中

如题所述

第1个回答  2015-07-24
package com.example.s_1;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.util.DisplayMetrics;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

public class MainActivity extends Activity {

private TextView mTextView;
private ImageView mImageView;
private RelativeLayout mRelativeLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mTextView = (TextView) this.findViewById(R.id.tv);
mRelativeLayout = (RelativeLayout) this.findViewById(R.id.relative_layout);

RelativeLayout.LayoutParams params = new LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
DisplayMetrics outMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(outMetrics);

int tHeight = mTextView.getHeight();
int tWidth = mTextView.getWidth();
System.out.println("width="+outMetrics.widthPixels+"=height="+outMetrics.heightPixels);

Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher);
int iWidth = drawable.getMinimumWidth();
int iHeight = drawable.getMinimumHeight();

int left = outMetrics.widthPixels/2-iWidth/2;
int top = (outMetrics.heightPixels-tHeight-iHeight)/2;

params.setMargins(left, top, 0, 0);
mImageView = new ImageView(MainActivity.this);
mImageView.setBackgroundResource(R.drawable.ic_launcher);
mRelativeLayout.addView(mImageView, params);

}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/relative_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/hello_world" />

</RelativeLayout本回答被提问者和网友采纳