Para definir o plano de fundo:
RelativeLayout layout =(RelativeLayout)findViewById(R.id.background);
layout.setBackgroundResource(R.drawable.ready);
É a melhor maneira de fazer isso?
RelativeLayout layout =(RelativeLayout)findViewById(R.id.background);
layout.setBackgroundResource(R.drawable.ready);
É a melhor maneira de fazer isso?
Respostas:
layout.setBackgroundResource(R.drawable.ready);está correto.
Outra maneira de conseguir isso é usar o seguinte:
final int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
layout.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.ready) );
} else {
layout.setBackground(ContextCompat.getDrawable(context, R.drawable.ready));
}
Mas acho que o problema ocorre porque você está tentando carregar imagens grandes.
Aqui está um bom tutorial sobre como carregar bitmaps grandes.
UPDATE:
getDrawable (int) descontinuado no nível 22 da API
getDrawable(int ) agora está descontinuado no nível 22 da API. Você deve usar o seguinte código da biblioteca de suporte:
ContextCompat.getDrawable(context, R.drawable.ready)
Se você se referir ao código fonte de ContextCompat.getDrawable , ele fornece algo parecido com isto:
/**
* Return a drawable object associated with a particular resource ID.
* <p>
* Starting in {@link android.os.Build.VERSION_CODES#LOLLIPOP}, the returned
* drawable will be styled for the specified Context's theme.
*
* @param id The desired resource identifier, as generated by the aapt tool.
* This integer encodes the package, type, and resource entry.
* The value 0 is an invalid identifier.
* @return Drawable An object that can be used to draw this resource.
*/
public static final Drawable getDrawable(Context context, int id) {
final int version = Build.VERSION.SDK_INT;
if (version >= 21) {
return ContextCompatApi21.getDrawable(context, id);
} else {
return context.getResources().getDrawable(id);
}
}
Mais detalhes sobre ContextCompat
Na API 22, você deve usar o getDrawable(int, Theme)método em vez de getDrawable (int).
ATUALIZAÇÃO:
Se você estiver usando a biblioteca de suporte v4, o seguinte será suficiente para todas as versões.
ContextCompat.getDrawable(context, R.drawable.ready)
Você precisará adicionar o seguinte em seu aplicativo build.gradle
compile 'com.android.support:support-v4:23.0.0' # or any version above
Ou usando o ResourceCompat, em qualquer API como abaixo:
import android.support.v4.content.res.ResourcesCompat;
ResourcesCompat.getDrawable(getResources(), R.drawable.name_of_drawable, null);
if(buttonBackground.equals(R.drawable.myDrawable)), onde Drawable buttonBackground = myButton.getBackground();eu recebo este erro: snag.gy/weYgA.jpg
myActivity.getTheme()da versão mais recente do método, em vez do parâmetro nulo:myView.setBackground( getResources().getDrawable(R.drawable.my_background, activity.getTheme()));
AppCompatResources.getDrawable(this.getContext(), resId)Google já o implementou no AppCompat*widget / visualização, por exemplo:android.support.v7.widget.AppCompatCheckBox
Tente o seguinte:
layout.setBackground(ContextCompat.getDrawable(context, R.drawable.ready));
e para API 16 <:
layout.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.ready));
getResources().getDrawable(). O código correto é layout.setBackgroundResource(R.drawable.ready);exatamente como o OP usado. O problema aqui vem do tamanho do bitmap.
RelativeLayout relativeLayout; //declare this globally
agora, dentro de qualquer função como onCreate, onResume
relativeLayout = new RelativeLayout(this);
relativeLayout.setBackgroundResource(R.drawable.view); //or whatever your image is
setContentView(relativeLayout); //you might be forgetting this
Você também pode definir o plano de fundo de qualquer imagem:
View v;
Drawable image=(Drawable)getResources().getDrawable(R.drawable.img);
(ImageView)v.setBackground(image);
(.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)interior do código
Estou usando o minSdkVersion 16 e o targetSdkVersion 23.
O seguinte está funcionando para mim, ele usa
ContextCompat.getDrawable(context, R.drawable.drawable);
Ao invés de usar:
layout.setBackgroundResource(R.drawable.ready);
Em vez disso, use:
layout.setBackground(ContextCompat.getDrawable(this, R.drawable.ready));
getActivity()é usado em um fragmento, se for chamado de um uso de atividade this.
Se os seus planos de fundo estão na pasta drawable agora, tente mover as imagens da pasta drawable para drawable-nodpi em seu projeto. Isso funcionou para mim, parece que mais as imagens são redimensionadas por elas mesmas.
Use butterknife para vincular o recurso extraível a uma variável, adicionando-o ao topo da sua classe (antes de qualquer método).
@Bind(R.id.some_layout)
RelativeLayout layout;
@BindDrawable(R.drawable.some_drawable)
Drawable background;
então dentro de um dos seus métodos adicione
layout.setBackground(background);
É tudo o que você precisa
if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)
layout.setBackgroundDrawable(getResources().getDrawable(R.drawable.ready));
else if(android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1)
layout.setBackground(getResources().getDrawable(R.drawable.ready));
else
layout.setBackground(ContextCompat.getDrawable(this, R.drawable.ready));
Faça uma tentativa de ViewCompat.setBackground(yourView, drawableBackground)
tente isso.
int res = getResources().getIdentifier("you_image", "drawable", "com.my.package");
preview = (ImageView) findViewById(R.id.preview);
preview.setBackgroundResource(res);
setBackground(getContext().getResources().getDrawable(R.drawable.green_rounded_frame));
Dentro do aplicativo / res / your_xml_layout_file .xml
remoteViews.setInt(R.id.btn_start,"setBackgroundResource", R.drawable.ic_button_start);