14

请原谅我是新手,我的术语可能不正确:

I have an array of images in class1, when an image is selected its id is passed to class2 (code below) I then display that image and give the option to set it as a wallpaper. 问题是,使用下面的代码我需要一个drawable来分配壁纸,而不是ImageView。有人可以给我一些指导来参考我有“myWallpaperManager.setResource(这里需要一个drawable);”的实际drawable

提前致谢。希望这是有道理的,正如我所说的我是一个菜鸟!

public class FullWallView extends Activity {
private Button wallbutton;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.wallpaper_full);

    // get intent data
    Intent i = getIntent();

    // Selected image id
    int position = i.getExtras().getInt("id");
    ImageAdapter imageAdapter = new ImageAdapter(this);

    ImageView imageView = (ImageView) findViewById(R.id.full_wall_view);
    imageView.setImageResource(imageAdapter.mThumbIds[position]);

    //Making Button Clickable and setting the wallpaper
    wallbutton = (Button) findViewById(R.id.apply);
    wallbutton.setOnClickListener(new Button.OnClickListener()
    {

           @Override
           public void onClick(View arg0) {
            // TODO Auto-generated method stub
            WallpaperManager myWallpaperManager
             = WallpaperManager.getInstance(getApplicationContext());
            try {
                myWallpaperManager.setResource(need a drawable here);
            } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
            }

           }});
4

4 回答 4

35

首先定义 Drawable,然后在 ImageView 中设置它。

img=(ImageView)findViewById(R.id.imageview1);
Drawable myDrawable = getResources().getDrawable(R.drawable.imageView1);
img.setImageDrawable(myDrawable);
于 2014-01-31T17:29:29.327 回答
12

getResources().getDrawable(int id)方法在 API 级别 22 中已弃用。

您可以检查版本,然后使用以下方法:

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
       imageView.setImageDrawable(getApplicationContext().getDrawable(R.drawable.myDrawable));
  } else {
      imageView.setImageDrawable(getResources().getDrawable(R.drawable.myDrawable));
    }

.

于 2016-09-20T21:05:37.817 回答
1

我刚刚注意到你需要传递resourceID而不是Drawable,没有直接的方法可以从ImageView中获取resourceID,你为什么不尝试记住这个值然后传递它。

希望这对您有所帮助并享受您的工作

于 2013-05-20T01:43:05.583 回答
0

如果您想通过仅提供图像名称来动态执行此操作:

public static Drawable getImage(Context context, String name) {
    return context.getResources().getDrawable(context.getResources().getIdentifier(name, "drawable", context.getPackageName()));
}

然后像这样设置imagedrawable:

ImageView image = findViewById(R.id.logo);
image.setImageDrawable(getImage(context, "imageName"));
于 2019-05-09T13:42:06.303 回答