从Res ID(Int)值引用或创建Drawable?

时间:2014-04-17 02:00:42

标签: android resources drawable android-resources android-drawable

我希望能够在SQLite中存储一个drawables INT值(ResourceID),然后能够从数据库中提取它并将其转换为drawable以便在listview中查看。

以下snippit生成2个值,ResID部分是一个int值,我希望能够将其转换回另一个活动中的drawable。\

Drawable myDrawable = getResources().getDrawable(
                    images[position]);
            Log.e("DRAWABLE", "DrawableId 1:   " + myDrawable);
            int resId = images[position];
            Log.e("DRAWABLE", "DrawableId 2:   " + resId);

如何将ResID转换为drawable?如果可能

PicturePickerFragment

public class PicturePickerFragment extends DialogFragment {

ListView listView;
ArrayList<RowItem> rowItems = new ArrayList<RowItem>();
// attach adapter to a list view
// A String[] array that will hold the names of the items.
public static final String[] descriptions = { "Baby", "Baking",
        "Barbershop", "Camping", "Conference Call", "Funeral", "Gambling",
        "Gardening", "Halloweeen", "Medicine", "Meeting", "Poker",
        "Christmas", "Wedding" };
public static final Integer[] images = { R.drawable.baby,
        R.drawable.baking, R.drawable.barbershop, R.drawable.camping,
        R.drawable.conferencecall, R.drawable.funeral, R.drawable.gambling,
        R.drawable.gardening, R.drawable.halloween, R.drawable.medicine,
        R.drawable.meeting, R.drawable.poker, R.drawable.santa,
        R.drawable.wedding };

Button btn_pic;

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    LayoutInflater inflater = getActivity().getLayoutInflater();
    View convertView = (View) inflater.inflate(R.layout.dialog_view, null);

    // defining the alertdialog
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setView(convertView);
    builder.setTitle(R.string.event_type);

     builder.setPositiveButton(R.string.select_picture,
     new DialogInterface.OnClickListener() {
     @Override
     public void onClick(DialogInterface dialog, int which) {
     // call the method on the parent activity when
     // user click the positive button

     }
     });

    // populating the array list
    for (int i = 0; i < descriptions.length; i++) {
        RowItem item = new RowItem(images[i], descriptions[i]);
        rowItems.add(item);
    }

    // defining listview and using array adapter
    listView = (ListView) convertView.findViewById(R.id.listViewFragment2);
    DrawableAdapter adapter = new DrawableAdapter(getActivity(), rowItems);
    listView.setAdapter(adapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, final View view,
                int position, long id) {

            // final int item = images[position];
            Drawable myDrawable = getResources().getDrawable(
                    images[position]);
            Log.e("DRAWABLE", "DrawableId 1:   " + myDrawable);
            int resId = images[position];
            Log.e("DRAWABLE", "DrawableId 2:   " + resId);
            Button b = (Button) getActivity()
                    .findViewById(R.id.btn_picture);
            b.setCompoundDrawablesWithIntrinsicBounds(null, myDrawable,
                    null, null);
        }

    });

    adapter.addAll(rowItems);

    return builder.create();
}
}

CreateActivity

public class CreateActivity extends Activity implements OnClickListener {

EditText etTitle;
Button btDate;
Button btTime;
Button btPic;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_create);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    //onclicklistener
    findViewById(R.id.btn_confirm).setOnClickListener(this);
    findViewById(R.id.btn_back).setOnClickListener(this);

    etTitle = (EditText) findViewById(R.id.editTextTitle);
    btDate = (Button) findViewById(R.id.btn_date);
    btTime = (Button) findViewById(R.id.btn_time);
    btPic = (Button) findViewById(R.id.btn_picture);

}

// Will be called via the onClick attribute
// of the buttons in main.xml
public void onClick(View view) {
    switch (view.getId()) {
    case R.id.btn_confirm:
        String title = etTitle.getText().toString();
        String time = btTime.getText().toString();
        String date = btDate.getText().toString();


        Drawable drawable = btPic.getCompoundDrawables()[1];
        int 


        Log.e("DRAWABLE", "DrawableId 3:   " + drawable);
        //Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();


        Log.e("LOG", title);
        Log.e("LOG", time);
        Log.e("LOG", date);


        Bundle newBundle = new Bundle();
        newBundle.putString("TITLE", title);
        newBundle.putString("TIME", time);
        newBundle.putString("DATE", date);
        //newBundle.putInt

        //Trying to pass a drawable from one activity to another
        //newBundle.putParcelable("DRAWABLE", bitmap);


        Intent intent = new Intent(this, MainActivity.class);
        intent.putExtras(newBundle);

        setResult(RESULT_OK, intent);

        finish();

        break;

    case R.id.btn_back:
        finish();
        break;
    }

}

public void showTimePickerDialog(View v) {
    DialogFragment newFragment = new TimePickerFragment();
    newFragment.show(getFragmentManager(), "timePicker");
}

public void showDatePickerDialog(View v) {
    DialogFragment newFragment = new DatePickerFragment();
    newFragment.show(getFragmentManager(), "datePicker");
}

public void showPicturePickerDialog(View v) {
    DialogFragment newFragment = new PicturePickerFragment();
    newFragment.show(getFragmentManager(), "picturePicker");
}

}

主要活动

public class MainActivity extends FragmentActivity implements OnClickListener {

ListView listView;
int lastIndex = -1;
ArrayList<Event> lstEvents = new ArrayList<Event>();

// detail view
TextView tvTitle, tvTime, tvDate;
ImageView ivPic;
View vw_master;

boolean _isBack = true;

ImageButton add;

String title;
String date;
String time;
int resId;

static final int PICK_CONTACT_REQUEST = 0;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    // // get detail controls
    tvTitle = (TextView) findViewById(R.id.textViewTitle);
    tvDate = (TextView) findViewById(R.id.textViewDate);
    tvTime = (TextView) findViewById(R.id.textViewTime);
    ivPic = (ImageView) findViewById(R.id.imageView1);

    add = (ImageButton) findViewById(R.id.add);
    add.setOnClickListener(this);


    /////////////////////////////////LISTVIEW////////////////////////////////////////
    // Create the adapter to convert the array to views
    EventAdapter adapter = new EventAdapter(this, lstEvents);

    // attach adapter to a list view
    listView = (ListView) findViewById(R.id.listViewFragment);
    listView.setAdapter(adapter);
    /////////////////////////////////LISTVIEW////////////////////////////////////////




    // /////////////////////////////DATABASE/////////////////////////////////////////////
    DatabaseHandler db = new DatabaseHandler(this);
    // /////////////////////////////DATABASE/////////////////////////////////////////////

    List<Event> events = db.getAllContacts();

    adapter.addAll(events);
    adapter.notifyDataSetChanged();






}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()) {
    case R.id.add:
        Intent intent = new Intent(this, CreateActivity.class);
        startActivityForResult(intent, 100);
        break;
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // /////////////////////////////DATABASE/////////////////////////////////////////////
    DatabaseHandler db = new DatabaseHandler(this);
    // /////////////////////////////DATABASE/////////////////////////////////////////////

    // Create the adapter to convert the array to views
    EventAdapter adapter = new EventAdapter(this, lstEvents);

    // attach adapter to a list view
    listView = (ListView) findViewById(R.id.listViewFragment);
    listView.setAdapter(adapter);

    if (requestCode == 100) {
        if (resultCode == RESULT_OK) {
            Bundle b = data.getExtras();
            title = b.getString("TITLE");
            time = b.getString("TIME");
            date = b.getString("DATE");

            // retrieving bitmap from CreateActivity
            int drawable = b.getInt("DRAWABLE");
            //Bitmap bitmap = (Bitmap) b.getParcelable("DRAWABLE");

            // converting from bitmap to drawable
            //Drawable drawable = new BitmapDrawable(getResources(), bitmap);

            // Event newEvent = new Event();
            // newEvent.set_date(date);
            // newEvent.set_title(title);
            // newEvent.set_time(time);

            // set drawable
            // newEvent.set_drawable(drawable);

            // lstEvents.add(newEvent);

            // adapter.addAll(lstEvents);
            // adapter.notifyDataSetChanged();

            ///////////////////////////////DATABASE/////////////////////////////////////////////
            /**
             * CRUD OPERATIONS
             */

            Log.e("Insert: ", "Inserting ..");
            db.addEvent(new Event(0, title, time, date, drawable));

            // Reading all contacts
            Log.e("Reading: ", "Reading all contacts..");
            // List<Event> events = db.getAllContacts();
            List<Event> events = db.getAllContacts();
            adapter.addAll(events);
            adapter.notifyDataSetChanged();

            //logging all events

            for (Event ev : events) {
                String log = "Id: " + ev.get_Id() + " ,Title: "
                        + ev.get_title() + " ,Date: " +           ev.get_date();
                // Writing Contacts to log
                Log.e("Name: ", log);

            }

            ///////////////////////////////DATABASE/////////////////////////////////////////////
        }

    }
}
}

1 个答案:

答案 0 :(得分:0)

我认为存储Resource Id不是正确的方法,因为Id's对每种类型的资源只有unique。因此,对于两种不同的资源,可能存在相同的Id

最好的方法是将资源的文件名存储为字符串。

您可以使用Resource Identifier

检索资源文​​件名称的资源ID
 int resourceId = getResources().getIdentifier("file_name", "drawable", getPackageName());