如何从drawable中选择图像?

时间:2022-02-09 06:24:55

I am trying to pick images stored inside my app currently in Drawable folder since I don't know yet where to if I am wrong point me where.

我正在尝试选择存储在我的应用程序当前在Drawable文件夹中的图像,因为我不知道在哪里,如果我错了,请指出我在哪里。

Goal: Since I don't want to send whole image to the server for corresponding user instead I am storing some images(Zodiac Signs) lets say Library Images. How to open this drawable window to select image when I click to upload Image like it opens gallery window if I want to load image from gallery.

目标:因为我不想将整个图像发送到相应用户的服务器,而是我存储了一些图像(Zodiac Signs)让我们说库图像。如何打开这个可绘制的窗口,当我点击上传图像时选择图像如果我想从图库加载图像,它会打开图库窗口。

This is how I am doing for gallery :

这就是我为画廊做的事情:

prof.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(
                        Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI );
                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);
            cursor.close();

            Glide.with(this).load(picturePath)
                    .crossFade()
                    .thumbnail(0.5f)
                    .bitmapTransform(new CircleTransform(this))
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(prof);


        }
    }

What Do I achieve from doing it : I'll be able to send only image name which will set on user screen if he view other user's profile since these images are in all app.

我从中做到了什么:如果他查看其他用户的个人资料,我将只能发送将在用户屏幕上设置的图像名称,因为这些图像都在所有应用程序中。

1 个解决方案

#1


-10  

Unfortunately you cannot get a list of drawables.

很遗憾,你无法获得一个drawables列表。

EDIT: This is working solution but unfortunatly yet another my answer trolled with downvotes by some revengeful (add some f-word epithet here)..

编辑:这是工作的解决方案,但不幸的是另一个我的答案与一些报复的downvotes(在这里添加一些f字加词)拖累..

But you may build static list int[] or some other structure

但是你可以构建静态列表int []或其他一些结构

There are two examples here:

这里有两个例子:

  • SimpleFragment shwoing images only with custom adapter. You need to build imagesOnly

    SimpleFragment仅使用自定义适配器拍摄图像。你需要构建imagesOnly

    public static class SimpleFragment extends DialogFragment {
        final static int[] imagesOnly = new int[]{R.drawable.ic_android, R.drawable.ic_apps, R.drawable.ic_laptop_mac, R.drawable.ic_mood};
    
        @NonNull
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final BaseAdapter adapter = new BaseAdapter() {
                @Override
                public int getCount() {
                    return imagesOnly.length;
                }
    
                @Override
                public Object getItem(int i) {
                    return imagesOnly[i];
                }
    
                @Override
                public long getItemId(int i) {
                    return imagesOnly[i];
                }
    
                @Override
                public View getView(int i, View view, ViewGroup viewGroup) {
                    if (view == null)
                        view = new ImageView(getContext());
                    ((ImageView) view).setImageResource((int) getItem(i));
                    return view;
                }
            };
            return new AlertDialog.Builder(getContext()).setAdapter(adapter,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            ((MainActivity) getContext()).OnSelected(SimpleFragment.this.getClass(), (int) adapter.getItem(i));
                        }
                    }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.cancel();
                }
            }).setCancelable(true).setTitle("Pick image(simple)").create();
        }
    }
    

    如何从drawable中选择图像?

  • WithNamesFragment showing images with name using SimpleAdapter. You need to build imagesWithNames

    WithNamesFragment使用SimpleAdapter显示带有名称的图像。你需要构建imagesWithNames

    public static class WithNamesFragment extends DialogFragment {
        final static ArrayList<HashMap<String, ?>> imagesWithNames = new ArrayList<>();
    
        static {
            HashMap<String, Object> row = new HashMap<>();
            row.put("imageID", R.drawable.ic_android);
            row.put("name", "Android");
            imagesWithNames.add(row);
            row = new HashMap<>();
            row.put("imageID", R.drawable.ic_apps);
            row.put("name", "Apps");
            imagesWithNames.add(row);
            row = new HashMap<>();
            row.put("imageID", R.drawable.ic_laptop_mac);
            row.put("name", "Laptop Mac");
            imagesWithNames.add(row);
            row = new HashMap<>();
            row.put("imageID", R.drawable.ic_mood);
            row.put("name", "Mud black");
            imagesWithNames.add(row);
        }
    
        @NonNull
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final SimpleAdapter adapter = new SimpleAdapter(getContext(), imagesWithNames, R.layout.simple_row_with_image,
                    new String[]{"name", "imageID"}, new int[]{R.id.text1, R.id.image1});
            return new AlertDialog.Builder(getContext()).setAdapter(adapter,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            ((MainActivity) getContext()).OnSelected(WithNamesFragment.this.getClass(), (int) ((HashMap<String, Object>) adapter.getItem(i)).get("imageID"));
                        }
                    }).setCancelable(true).setTitle("Pick image(with names)").create();
        }
    }
    

    如何从drawable中选择图像?

usage - important thing callback public void OnSelected(Class<?> clazz, int i) of course clazz is here only for logging purpose so you can remove it ... also there is no cancel callback - it's up to you

用法 - 重要的事情回调public void OnSelected(Class <?> clazz,int i)当然clazz只是为了记录目的所以你可以删除它...也没有取消回调 - 这取决于你

import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {


    private static final String PICKER_TAG = "PICKER_TAG";
    static boolean mShowSimple = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Button button = new Button(this);
        button.setText("Click me!");
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mShowSimple)
                    showSimple();
                else
                    show();
                mShowSimple = !mShowSimple;
            }
        });
        setContentView(button);
    }

    ;

    void show() {
        new WithNamesFragment().show(getSupportFragmentManager(), PICKER_TAG);
    }

    void showSimple() {
        new SimpleFragment().show(getSupportFragmentManager(), PICKER_TAG);
    }

    public void OnSelected(Class<?> clazz, int i) {
        Toast toast = Toast.makeText(this, "Class \"" + clazz.getSimpleName() + "\" returns this image with id: " + getResources().getResourceName(i), Toast.LENGTH_SHORT);
        final TextView toastView = (TextView) toast.getView().findViewById(android.R.id.message);
        toastView.setCompoundDrawablesWithIntrinsicBounds(0, i, 0, 0);
        toast.show();
    }
}

simple_row_with_image.xml (only needed for version with names)

simple_row_with_image.xml(仅对具有名称的版本需要)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/image1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toEndOf="@id/image1"
        android:layout_toRightOf="@id/image1" />
</RelativeLayout>

#1


-10  

Unfortunately you cannot get a list of drawables.

很遗憾,你无法获得一个drawables列表。

EDIT: This is working solution but unfortunatly yet another my answer trolled with downvotes by some revengeful (add some f-word epithet here)..

编辑:这是工作的解决方案,但不幸的是另一个我的答案与一些报复的downvotes(在这里添加一些f字加词)拖累..

But you may build static list int[] or some other structure

但是你可以构建静态列表int []或其他一些结构

There are two examples here:

这里有两个例子:

  • SimpleFragment shwoing images only with custom adapter. You need to build imagesOnly

    SimpleFragment仅使用自定义适配器拍摄图像。你需要构建imagesOnly

    public static class SimpleFragment extends DialogFragment {
        final static int[] imagesOnly = new int[]{R.drawable.ic_android, R.drawable.ic_apps, R.drawable.ic_laptop_mac, R.drawable.ic_mood};
    
        @NonNull
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final BaseAdapter adapter = new BaseAdapter() {
                @Override
                public int getCount() {
                    return imagesOnly.length;
                }
    
                @Override
                public Object getItem(int i) {
                    return imagesOnly[i];
                }
    
                @Override
                public long getItemId(int i) {
                    return imagesOnly[i];
                }
    
                @Override
                public View getView(int i, View view, ViewGroup viewGroup) {
                    if (view == null)
                        view = new ImageView(getContext());
                    ((ImageView) view).setImageResource((int) getItem(i));
                    return view;
                }
            };
            return new AlertDialog.Builder(getContext()).setAdapter(adapter,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            ((MainActivity) getContext()).OnSelected(SimpleFragment.this.getClass(), (int) adapter.getItem(i));
                        }
                    }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.cancel();
                }
            }).setCancelable(true).setTitle("Pick image(simple)").create();
        }
    }
    

    如何从drawable中选择图像?

  • WithNamesFragment showing images with name using SimpleAdapter. You need to build imagesWithNames

    WithNamesFragment使用SimpleAdapter显示带有名称的图像。你需要构建imagesWithNames

    public static class WithNamesFragment extends DialogFragment {
        final static ArrayList<HashMap<String, ?>> imagesWithNames = new ArrayList<>();
    
        static {
            HashMap<String, Object> row = new HashMap<>();
            row.put("imageID", R.drawable.ic_android);
            row.put("name", "Android");
            imagesWithNames.add(row);
            row = new HashMap<>();
            row.put("imageID", R.drawable.ic_apps);
            row.put("name", "Apps");
            imagesWithNames.add(row);
            row = new HashMap<>();
            row.put("imageID", R.drawable.ic_laptop_mac);
            row.put("name", "Laptop Mac");
            imagesWithNames.add(row);
            row = new HashMap<>();
            row.put("imageID", R.drawable.ic_mood);
            row.put("name", "Mud black");
            imagesWithNames.add(row);
        }
    
        @NonNull
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final SimpleAdapter adapter = new SimpleAdapter(getContext(), imagesWithNames, R.layout.simple_row_with_image,
                    new String[]{"name", "imageID"}, new int[]{R.id.text1, R.id.image1});
            return new AlertDialog.Builder(getContext()).setAdapter(adapter,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            ((MainActivity) getContext()).OnSelected(WithNamesFragment.this.getClass(), (int) ((HashMap<String, Object>) adapter.getItem(i)).get("imageID"));
                        }
                    }).setCancelable(true).setTitle("Pick image(with names)").create();
        }
    }
    

    如何从drawable中选择图像?

usage - important thing callback public void OnSelected(Class<?> clazz, int i) of course clazz is here only for logging purpose so you can remove it ... also there is no cancel callback - it's up to you

用法 - 重要的事情回调public void OnSelected(Class <?> clazz,int i)当然clazz只是为了记录目的所以你可以删除它...也没有取消回调 - 这取决于你

import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {


    private static final String PICKER_TAG = "PICKER_TAG";
    static boolean mShowSimple = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final Button button = new Button(this);
        button.setText("Click me!");
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mShowSimple)
                    showSimple();
                else
                    show();
                mShowSimple = !mShowSimple;
            }
        });
        setContentView(button);
    }

    ;

    void show() {
        new WithNamesFragment().show(getSupportFragmentManager(), PICKER_TAG);
    }

    void showSimple() {
        new SimpleFragment().show(getSupportFragmentManager(), PICKER_TAG);
    }

    public void OnSelected(Class<?> clazz, int i) {
        Toast toast = Toast.makeText(this, "Class \"" + clazz.getSimpleName() + "\" returns this image with id: " + getResources().getResourceName(i), Toast.LENGTH_SHORT);
        final TextView toastView = (TextView) toast.getView().findViewById(android.R.id.message);
        toastView.setCompoundDrawablesWithIntrinsicBounds(0, i, 0, 0);
        toast.show();
    }
}

simple_row_with_image.xml (only needed for version with names)

simple_row_with_image.xml(仅对具有名称的版本需要)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ImageView
        android:id="@+id/image1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toEndOf="@id/image1"
        android:layout_toRightOf="@id/image1" />
</RelativeLayout>