我有一个ImageView
和一个TextView
我希望将背景颜色从底部更改为ImageView
高度的一半。我尝试用这样的View
来做到这一点:
activity_main.xml中:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.MainActivity">
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:background="@color/cyan"
android:id="@+id/blue_background" />
<TextView
android:id="@+id/credits"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:textAlignment="center"
android:textColor="@color/white"
android:text="@string/credits"/>
<ImageView
android:id="@+id/logo"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_above="@id/credits"
android:layout_below="@id/resume_button"
android:layout_centerHorizontal="true"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:src="@drawable/logo"/>
</RelativeLayout>
MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView logo = (ImageView) findViewById(R.id.logo);
TextView credits = (TextView) findViewById(R.id.credits);
View background_blue = (View) findViewById(R.id.blue_background);
background_blue.getLayoutParams().height = credits.getLayoutParams().height + (logo.getLayoutParams().height / 2);
}
但它不起作用,我将整个背景视为蓝色而不仅仅是我感兴趣的部分。
答案 0 :(得分:1)
尝试此解决方法
替换此
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:background="@color/cyan"
android:id="@+id/blue_background" />
有了这个
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
<View
android:id="@+id/blue_background"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@color/cyan" />
</LinearLayout>
并从主要活动中删除此行
background_blue.getLayoutParams().height = credits.getLayoutParams().height + (logo.getLayoutParams().height / 2);
答案 1 :(得分:1)
使用 ViewTreeObserver
final ImageView logo = (ImageView) findViewById(R.id.logo);
ViewTreeObserver vto = logo.getViewTreeObserver();
vto.addOnGlobalLayoutListener (new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
logo.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int width = logo.getMeasuredWidth();
int height = logo.getMeasuredHeight();
background_blue.getLayoutParams().height = credits.getLayoutParams().height + (height / 2);
}
});