android - 传递 Volley 图像作为下一个 Activity 背景图像

标签 android json android-layout android-volley

这是一个简单的问题,但让我感到困惑。我有如下所示的第一个 Activity 和详细信息 Activity 。

第一个 Activity

enter image description here

第二个 Activity

enter image description here

作为 ListView 的第一个 Activity 使用截击下载了 json 数据,我能够将标题和图像发送到详细信息 Activity ,但现在我想将传递的图像设置为详细信息 Activity 背景图片,这是我的第一个 Activity 代码:

主要 Activity :

public class MainActivity extends Activity {
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();

// Movies json url
private static final String url = "http://api.androidhive.info/json/movies.json";
private ProgressDialog pDialog;
private List<Movie> movieList = new ArrayList<Movie>();
private ListView listView;
private CustomListAdapter adapter;

private static String Title="title";
private static String bitmap="thumbnailUrl";


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

    Intent newActivity2=new Intent();
    setResult(RESULT_OK, newActivity2);

    listView = (ListView) findViewById(R.id.list);
    adapter = new CustomListAdapter(this, movieList);
    listView.setAdapter(adapter);

    pDialog = new ProgressDialog(this);
    // Showing progress dialog before making http request
    pDialog.setMessage("Loading...");
    pDialog.show();

    // changing action bar color
    getActionBar().setBackgroundDrawable(
            new ColorDrawable(Color.parseColor("#1b1b1b")));

    // Creating volley request obj
    JsonArrayRequest movieReq = new JsonArrayRequest(url,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, response.toString());
                    pDialog.dismiss();

                    // Parsing json
                    for (int i = 0; i < response.length(); i++) {
                        try {

                            JSONObject obj = response.getJSONObject(i);
                            Movie movie = new Movie();
                            movie.setTitle(obj.getString("title"));
                            movie.setThumbnailUrl(obj.getString("image"));
                            movie.setRating(((Number) obj.get("rating"))
                                    .doubleValue());
                            movie.setYear(obj.getInt("releaseYear"));

                            // Genre is json array
                            JSONArray genreArry = obj.getJSONArray("genre");
                            ArrayList<String> genre = new ArrayList<String>();
                            for (int j = 0; j < genreArry.length(); j++) {
                                genre.add((String) genreArry.get(j));
                            }
                            movie.setGenre(genre);

                            // adding movie to movies array
                            movieList.add(movie);

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

                    }

                    // notifying list adapter about data changes
                    // so that it renders the list view with updated data
                    adapter.notifyDataSetChanged();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    if (error instanceof NoConnectionError){
                        Toast.makeText(getBaseContext(), "Bummer..There's No Internet connection!", Toast.LENGTH_LONG).show();

                    }

                }
            });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(movieReq);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // TODO Auto-generated method stub
            String name = ((TextView) view.findViewById(R.id.title)).getText().toString();

            bitmap = ((Movie)movieList.get(position)).getThumbnailUrl();
            Intent intent = new Intent(MainActivity.this, Detail.class);    
            intent.putExtra(Title, name);
            intent.putExtra("images", bitmap);

            startActivity(intent);
        }

    });
}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

这是详细信息 Activity :

public class Detail extends Activity{
private static String Title = "title";

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.detail);
    getActionBar().hide();


    Intent i = getIntent();
    ImageLoader imageLoader = AppController.getInstance().getImageLoader();
    String name = i.getStringExtra(Title);
    String bitmap = i.getStringExtra("images");
    NetworkImageView thumbNail = (NetworkImageView) findViewById(R.id.thumbnail);
    thumbNail.setImageUrl(bitmap, imageLoader);
    TextView lblname = (TextView) findViewById(R.id.name_label);

    lblname.setText(name);
}

public void onClickHandler(View v){
    switch(v.getId()){
    case R.id.thumbnail:startActivity(new Intent(this,MainActivity.class));
    }
}

如果需要,我会上传更多代码。

自定义列表适配器:

public class CustomListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();

public CustomListAdapter(Activity activity, List<Movie> movieItems) {
    this.activity = activity;
    this.movieItems = movieItems;
}

@Override
public int getCount() {
    return movieItems.size();
}

@Override
public Object getItem(int location) {
    return movieItems.get(location);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    if (inflater == null)
        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null)
        convertView = inflater.inflate(R.layout.list_row, null);

    if (imageLoader == null)
        imageLoader = AppController.getInstance().getImageLoader();
    NetworkImageView thumbNail = (NetworkImageView) convertView
            .findViewById(R.id.thumbnail);
    TextView title = (TextView) convertView.findViewById(R.id.title);
    TextView rating = (TextView) convertView.findViewById(R.id.rating);
    TextView genre = (TextView) convertView.findViewById(R.id.genre);
    TextView year = (TextView) convertView.findViewById(R.id.releaseYear);

    // getting movie data for the row
    Movie m = movieItems.get(position);

    // thumbnail image
    thumbNail.setImageUrl(m.getThumbnailUrl(), imageLoader);

    // title
    title.setText(m.getTitle());

    // rating
    rating.setText("Rating: " + String.valueOf(m.getRating()));

    // genre
    String genreStr = "";
    for (String str : m.getGenre()) {
        genreStr += str + ", ";
    }
    genreStr = genreStr.length() > 0 ? genreStr.substring(0,
            genreStr.length() - 2) : genreStr;
    genre.setText(genreStr);

    // release year
    year.setText(String.valueOf(m.getYear()));

    return convertView;
}

和detail.xml

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:background="#ffffff" >

    
    <com.android.volley.toolbox.NetworkImageView
    android:id="@+id/thumbnail" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="42dp"
    tools:ignore="ContentDescription"/>
    
    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical" >
    
    <TextView
        android:id="@+id/name_label"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="20sp"
        android:divider="@color/list_divider"
        android:dividerHeight="1dp" />
    </LinearLayout>

		 
	</RelativeLayout>

我是这方面的新手,所以任何帮助都将不胜感激。非常感谢!

最佳答案

给你!

MainActivity 内部:

listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // your code
        BitmapDrawable bd = (BitmapDrawable) ((NetworkImageView) view.findViewById(R.id.thumbnail))
                .getDrawable();
        Bitmap bitmap=bd.getBitmap();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bd.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, baos); 
        byte[] imgByte = baos.toByteArray();

        Intent intent = new Intent(MainActivity.this, Detail.class);
        intent.putExtra("image", imgByte);
        // any other extra you need to pass
        startActivity(intent);
    }
}

内部细节:

Bundle extras = getIntent().getExtras();
byte[] b = extras.getByteArray("image");

Bitmap bmp = BitmapFactory.decodeByteArray(b, 0, b.length);
BitmapDrawable background = new BitmapDrawable(bmp);
findViewById(R.id.root_layout).setBackgroundDrawable(background);

内部 detail.xml

为您的 RelativeLayout 分配一个 ID

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/root_layout"

关于android - 传递 Volley 图像作为下一个 Activity 背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30332620/

相关文章:

android - 为什么 OS X (Yosemite) 上的 Android Studio 1.0.1 无法下载 SDK 组件?

database - 安卓新手 : openOrCreateDatabase(): where does the sqlite file go?

android - 保存开关状态android

Android WebView - 它支持摘要身份验证吗?

java - 解析包含原语和对象的 JSONArray

php - x-editable 发布到 MySQL 并返回 Json

javascript - 主干 : Making Collections out of JSON attributes advice, 并使事情变得更好

android - 如何在自定义 ViewGroup 中正确扩展 XML-Layout-File?

android - 错误 : A factory has already been set on this LayoutInflater (change background color of menu options)

java - 从实例内部 inflatedView 不起作用