从ImageView设置背景图像

时间:2015-03-06 07:52:27

标签: java android drawable setbackground

根据标题,我需要从运行时加载的imageview设置相对布局的背景图像,从URL读取。 我试过outer.setBackground(background.getDrawable());但它对我不起作用:

//OUTER
RelativeLayout outer = (RelativeLayout)findViewById(R.id.outer);
//BACKGROUND
ImageView background = new ImageView(getApplicationContext());
Background reader = new Background(this, this, background);
reader.execute();
outer.setBackground(background.getDrawable());

loader class:

public class Background extends AsyncTask<Void, Void, Bitmap> {

    ImageView MyView = null;
    ProgressDialog dialog;

    private OnTaskComplete mlistener;

    public Background(Context context, OnTaskComplete mlistener, ImageView view) {
        this.mlistener = mlistener;
        MyView = view;
    }

    @Override
    protected Bitmap doInBackground(Void... params) {

        Bitmap image = null;

        try {
            URL url = new URL("http://www.youth-stories.com/public/admin/CH_Settings/background.jpg");
            image = BitmapFactory.decodeStream(url.openConnection().getInputStream());


        } catch (IOException e) {
            e.printStackTrace();
        }

        return image;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        super.onPostExecute(bitmap);
        mlistener.callBackFunction(bitmap);
        MyView.setImageBitmap(bitmap);
    }
}

public class Home extends ActionBarActivity implements OnTaskComplete, ScrollViewListener {

    Scroller scrollview = null;
    @Override
    public void onScrollChanged(Scroller scrollView, int x, int y, int oldx, int oldy) {
       // Toast.makeText(this,"sl",Toast.LENGTH_LONG).show();
        list();
    }

    LinearLayout wrapper = null;
    Context context = this;

    public Bitmap imageHandler;

    @Override
    public void callBackFunction(Bitmap image) {

        imageHandler = image;

/*
        RelativeLayout outer = (RelativeLayout)findViewById(R.id.outer);
        BitmapDrawable bd = new BitmapDrawable(getResources(), image);
        outer.setBackground(bd);
*/

    }

    public class Post{

        String id;
        String title;
        String description;
        String release;

        public String getTitle() {
            return title;
        }

        public String getDescription() {
            return description;
        }

        public String getRelease() {
            return release;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public void setRelease(String release) {
            this.release = release;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getId() {

            return id;
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        //OUTER
        RelativeLayout outer = (RelativeLayout)findViewById(R.id.outer);
        //BACKGROUND
        ImageView background = new ImageView(getApplicationContext());
        Background reader = new Background(this, this, background);
        reader.execute();

        BitmapDrawable bd = new BitmapDrawable(getResources(), background);
        outer.setBackground(bd);


        //SCROLLER
        Scroller scroller = new Scroller(this, this);
        scroller.setLayoutParams(new RelativeLayout.LayoutParams(
                RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT));

        //WRAPPER
        wrapper = new LinearLayout(this);
        wrapper.setOrientation(LinearLayout.VERTICAL);

        outer.addView(scroller);
        scroller.addView(wrapper);

        Globals.FOCUSON_PAGE = 0;
        list();

    }


    public void list(){

        ProgressDialog dialog = new ProgressDialog(context);
        dialog.setMessage("loading contents, please wait..");
        dialog.setCancelable(false);
        dialog.show();


        String result = null;
        ArrayList<Post> focusOn = new ArrayList<Post>();


        try {
            URL address = new URL("http://www.youth-stories.com/api/focusOnAll.php");
            URLDataReader reader = new URLDataReader(context);
            result = reader.execute(address).get();

        }catch (IOException e){
            e.printStackTrace();
        } catch(InterruptedException e){
            e.printStackTrace();
        } catch (ExecutionException e){
            e.printStackTrace();
        }
        try {
            JSONObject obj = new JSONObject(result);
            String success = (String) obj.getString("success");
            JSONArray records = obj.getJSONArray("records");

            int start = (Globals.FOCUSON_PAGE * Globals.FOCUSON_STEP);
            int limit = start + Globals.FOCUSON_STEP;
            for(int i = start ; i < limit; i++) {

                Post tmp = new Post();
                tmp.setId(records.getJSONObject(i).getString("id"));
                tmp.setTitle(records.getJSONObject(i).getString("title"));
                tmp.setDescription(records.getJSONObject(i).getString("contents"));
                tmp.setRelease(records.getJSONObject(i).getString("data_post"));
                focusOn.add(tmp);
            }

        }catch (JSONException e){
            e.printStackTrace();
        }


        //wrapper
        LinearLayout container = wrapper;

        for(int i = 0; i < focusOn.size(); i++) {
            //item
            LinearLayout item = new LinearLayout(getApplicationContext());
            String select = focusOn.get(i).getId();
            item.setId(new Integer(select));
            item.setClickable(true);

            //setUp new activity
            final Intent intent = new Intent(getApplicationContext(),HomeOnSelect.class);
            Bundle bundle = new Bundle();
            int id = item.getId();
            String strid = new Integer(id).toString();
            bundle.putString("id",  strid);
            bundle.putString("title",   focusOn.get(i).getTitle());
            bundle.putString("contents", focusOn.get(i).getDescription());
            bundle.putString("release", focusOn.get(i).getRelease());
            intent.putExtras(bundle);

            item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(intent);
                }
            });
            container.addView(item);
            item.setOrientation(LinearLayout.HORIZONTAL);
            item.setPadding(0, 40, 0, 40);
            item.setGravity(Gravity.CENTER_VERTICAL);
            item.setBackgroundResource(R.drawable.postlayout);

            //image
            ImageView asset = new ImageView(getApplicationContext());
            URL address = null;

            try {

                address = new URL("http://www.youth-stories.com/public/admin/CH_FocusOn/images/" + focusOn.get(i).getId() + "_thumb2.jpg");
                URLImageReader reader = new URLImageReader(this, this, asset, dialog, i, focusOn.size());
                reader.execute(address);

            } catch (MalformedURLException e) {
                e.printStackTrace();
            }

            item.addView(asset);

            LinearLayout.LayoutParams imgSettings = new LinearLayout.LayoutParams(300, 300);

            asset.setLayoutParams(imgSettings);
            asset.setPadding(50,0,0,0);

            //inside
            LinearLayout contents = new LinearLayout(getApplicationContext());
            contents.setOrientation(LinearLayout.VERTICAL);
            contents.setPadding(55, 0, 100, 0);
            item.addView(contents);
            //title
            TextView title = new TextView(getApplicationContext());
            title.setText(focusOn.get(i).getTitle());
            title.setTextAppearance(this, R.style.title);
            contents.addView(title);
            //description
            TextView description = new TextView(getApplicationContext());
            description.setText(focusOn.get(i).getDescription());
            description.setTextAppearance(this, R.style.description);
            contents.addView(description);
            //date
            TextView date = new TextView(getApplicationContext());
            date.setText(focusOn.get(i).getRelease());
            date.setTextAppearance(this, R.style.description);
            contents.addView(date);
            //div
            LinearLayout div = new LinearLayout(getApplicationContext());
            div.setLayoutParams(new LinearLayout.LayoutParams(200, 40));
            div.setBackgroundColor(Color.parseColor("#00000000"));
            container.addView(div);
        }


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_home, menu);

        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        switch(item.getItemId()){
            case R.id.search:
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

}

3 个答案:

答案 0 :(得分:0)

您可以直接使用Bitmap设置RelativeLayout背景,而无需通过onPostExecute(位图位图)方法中的ImageView传递:

编辑:完整的AsyncTask

public class Background extends AsyncTask<Void, Void, Bitmap> {

        Context ctxt;
        RelativeLayout outer = null;
        ProgressDialog dialog;

        private OnTaskComplete mlistener;

        public Background(Context context, OnTaskComplete mlistener, RelativeLayout rl) {
            this.mlistener = mlistener;
            outer = rl;
            ctxt = context;
        }

        @Override
        protected Bitmap doInBackground(Void... params) {

            Bitmap image = null;

            try {
                URL url = new URL("http://www.youth-stories.com/public/admin/CH_Settings/background.jpg");
                image = BitmapFactory.decodeStream(url.openConnection().getInputStream());


            } catch (IOException e) {
                e.printStackTrace();
            }

            return image;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            BitmapDrawable bd = new BitmapDrawable(ctxt.getResources(), bitmap);
            outer.setBackground(bd);
            mlistener.callBackFunction(bitmap);
        }
    }

通过以下方式实现此AsyncTask:

//OUTER
RelativeLayout outer = (RelativeLayout)findViewById(R.id.outer);
//BACKGROUND
Background reader = new Background(this, this, outer);
reader.execute();

答案 1 :(得分:0)

您的Activity实施OnTaskComplete界面,并在callBackFunction(bitmap)上调用onPostExecute。您需要的是在此方法中移动您拥有的所有背景相关逻辑。

E.g

public void callBackFunction(Bitmap bitmap) {
  RelativeLayout outer = (RelativeLayout)findViewById(R.id.outer);
  BitmapDrawable bd = new BitmapDrawable(getResources(), bitmap);
  outer.setBackground(bd);
}

答案 2 :(得分:0)

从下面的方法中使用drawable use设置图像:

.setBackgroundResource(R.drawable.ic_launcher);

并从位图类型设置图像使用:

.setImageBitmap(bitmap);