gpt4 book ai didi

android - 为什么我的 RelativeLayout 背景在我添加按钮时变成黑色?

转载 作者:行者123 更新时间:2023-11-29 22:16:04 25 4
gpt4 key购买 nike

我在下面有一些代码创建了一个 RelativeLayout 并向其添加了一个按钮。从 onCreate() 创建时它绘制得很好,在红色背景上显示蓝色按钮。

但是当点击第一个新按钮时创建一个新的 ReltativeLayout 时,新按钮显示在黑色背景上,所以我的 RelativeLayout 不显示。

有趣的是,如果我注释掉添加按钮的行,它就会起作用,所以按钮会以某种方式影响相对布局。

感谢您的帮助。

package com.android.mikeviewtester;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;

public class ViewTesterActivity extends Activity {

void createNewView( int bgColor, int btnColor ) {

// create a new relative layout
android.widget.RelativeLayout newView = new android.widget.RelativeLayout( this );

// create a button
Button btn = new Button( this );

// set the background color
btn.setBackgroundColor( btnColor );

// create a layoutParams struct for adding the button to the relative layout view
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams( 100, 100 );

// add the button to the relative layout
newView.addView( btn, params );

// set the relative layout background color
newView.setBackgroundColor( bgColor );

// set the ontouch listener for the relativeLayout
newView.setOnTouchListener( (android.view.View.OnTouchListener) mOnTouchListener );

// create the layout to fill the activity
RelativeLayout.LayoutParams viewParams = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);

// set the relative layout as the view
setContentView( newView, viewParams );
}

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );

// create and set the initial view
createNewView( Color.RED, Color.BLUE );
}

// ios - (void)buttonWasPressed:(id)whichButton {
private android.view.View.OnTouchListener mOnTouchListener = new android.view.View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {

if ( v != null )
v.onTouchEvent( event );

if ( event.getAction() == MotionEvent.ACTION_UP ) {

// create and set a new view
createNewView( Color.GREEN, Color.MAGENTA );
}

return true;
}
};
}

最佳答案

更改您的代码,即在调用 createNewView(Color.GREEN, Color.MAGENTA); 之前添加 v.setVisibility(View.GONE);;

关于android - 为什么我的 RelativeLayout 背景在我添加按钮时变成黑色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8432220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com