以编程方式设置android:background / android:src

您所在的位置:网站首页 background什么 以编程方式设置android:background / android:src

以编程方式设置android:background / android:src

#以编程方式设置android:background / android:src | 来源: 网络整理| 查看: 265

我需要像在xml中一样设置两个属性:

123456

如您所见,有一个背景和一个src属性。如何通过编程设置两者?

我只知道一个:是哪一个?还有另一个是什么?

1 btnBack.SetBackgroundResource(Resource.Drawable.thebook_backbutton); 相关讨论 您可以使用以下方法:imageButton.setImageResource(); imageButton.setBackgroundResource(); 在Android中如何以编程方式设置背景可绘制的可能重复项

使用setImageResource()将android:src设置为ImageButton

setImageResource() Sets a drawable as the content of this ImageView.

示例代码

1btnBack.setImageResource(R.drawable.ic_camera);

使用setBackgroundResource()将android:background设置为ImageButton

示例代码

1btnBack.setBackgroundResource(R.color.colorAccent);

您可以通过以下代码进行操作:

1234567891011121314151617private void initView() {         rootLayout =new LinearLayout(this);         rootLayout.setBackgroundDrawable(getResources().getDrawable(R.drawable.layer_5));         imgLogo=new ImageView(this);         imgLogo.setImageDrawable(getResources().getDrawable(R.drawable.splash_logo));         RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(              350,              350);         imgLogo.setLayoutParams(params);         rootLayout.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);         rootLayout.addView(imgLogo);         setContentView(rootLayout);     }

并在onCreate

中调用initView方法

12imageView.setBackgroundResource(R.drawable.some_bg_res); // for setting background 'android:background' imageView.setImageResource(R.drawable.some_res); // for setting src 'android:src'

已经有了正确的答案,但是更好的方法是将这个属性放在styles.xml中,并将该样式赋予您想要使用的按钮,以提高清晰度并减少必须编写的行数。当您的应用程序变大时,从活动/分段中进行的所有设置都将变得难以维护。

如果您唯一的目标是在代码中进行更改,那么请看一下。

如何以编程方式在视图中设置样式属性

android:src is set with setImageResource()

android:background is set with setBackgroundResource()

在代码中

123ImageButton btn = (ImageButton)findViewById(R.id.btn_friendsMainMenu); btn.setImageResource(R.drawable.general_btn_header_friendlist) btn.setBackgroundResource(R.drawable.ripple)

ImagResource will be on top of the BackgroundResource.

您可以在Android中以编程方式将图像设置为ImageView,请使用下面的代码。

1imageView.setImageResource(R.drawable.android_image3);

setBackgroundResource()设置背景-它与setBackground()有所不同,它采用资源ID(如int)作为输入。

我相当确定setImage()是在xml中设置\\'src \\'属性的方法。它还有一些不同的变体。如果要像示例中那样设置可绘制对象,请使用setImageDrawable()。

setImageResource()用于android:src。 ImageButton从ImageView继承。

1btnBack.SetImageResource(Resource.Drawable.drawable_name) 1234ImageButton btn = (ImageButton)findViewbyId(R.id.img_btn) btn.setImageResource(R.drawable.image)     btn.setBackgroundResource(R.drawable.ripple) 相关讨论 尽管此代码可以回答问题,但提供有关如何以及为什么解决问题的其他上下文将提高??答案的长期价值。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3