设置背景信息:
RelativeLayout layout = (RelativeLayout) findViewById(R.id.background);
layout.setBackgroundResource(R.drawable.ready);
这是最好的方法吗?
设置背景信息:
RelativeLayout layout = (RelativeLayout) findViewById(R.id.background);
layout.setBackgroundResource(R.drawable.ready);
这是最好的方法吗?
当前回答
setBackground(getContext().getResources().getDrawable(R.drawable.green_rounded_frame));
其他回答
试试ViewCompat。setBackground (yourView drawableBackground)
如果您的背景现在在drawable文件夹中,请尝试将图像从drawable文件夹移动到项目中的drawable-nodpi文件夹。这为我工作,似乎其他图像是由他们自己重新缩放。
在app/res/your_xml_layout_file.xml中
为父布局分配一个名称。 去MainActivity,通过调用findViewById(R.id."given_name")找到RelativeLayout。 通过调用setBackgroundColor()方法,将布局作为经典对象使用。
RelativeLayout relativeLayout; //declare this globally
现在,在任何函数中,如onCreate, onResume
relativeLayout = new RelativeLayout(this);
relativeLayout.setBackgroundResource(R.drawable.view); //or whatever your image is
setContentView(relativeLayout); //you might be forgetting this
我正在使用minSdkVersion 16和targetSdkVersion 23。 以下是为我工作,它使用
ContextCompat.getDrawable(context, R.drawable.drawable);
而不是使用:
layout.setBackgroundResource(R.drawable.ready);
而使用:
layout.setBackground(ContextCompat.getDrawable(this, R.drawable.ready));
getActivity()在片段中使用,如果从活动调用则使用此方法。