2016-09-06 2 views
0

Я написал код для поиска изображений в Twitter с помощью хэштегов и отображения изображений внутри приложения.Как разместить URL-адрес ImageView?

Здесь моя структура. У меня есть SearchView, если пользователь поместил некоторый текст в SearchView, запрос Twitter4j Query на него в Twitter. Затем я анализирую URL-адреса изображений из результатов.

Теперь мой вопрос. Как я могу поместить изображения из URL-адресов в изображениеView, чтобы отобразить изображение позади URL-адреса?

Вот мой код:

/* Setup Configurationbuilder for Twitter4j API, build a searchquery for search Twitter, 
    search Twitter with the search string from the SearchView 
*/ 
public void searchTweets(String searchString) { 

    //auth. the application by creating new ConfigurationBuilder 
    ConfigurationBuilder cb = new ConfigurationBuilder(); 
    cb.setJSONStoreEnabled(true); 
    cb.setOAuthConsumerKey("someSecretStuff"); 
    cb.setOAuthConsumerSecret("someSecretStuff"); 
    cb.setOAuthAccessToken("someSecretStuff"); 
    cb.setOAuthAccessTokenSecret("someSecretStuff"); 

    //start the search by build a new query 
    TwitterFactory tf = new TwitterFactory(cb.build()); 
    final twitter4j.Twitter twitter = tf.getInstance(); 
    final Query query = new Query(searchString); 

    //start a new Thread to evaluate the searchQuery 
    new Thread(new Runnable() { 
     @Override 
     public void run() { 
      try { 
       //get the results 
       QueryResult result = twitter.search(query); 
       //for each result print the user and the the messagetext 
       for (Status status : result.getTweets()) { 
        twitter4j.MediaEntity [] media = status.getMediaEntities(); 
        for (twitter4j.MediaEntity m : media) { 
         System.out.println(m.getMediaURL()); 
        } 
       } 
      } catch (TwitterException e) { 
       e.printStackTrace(); 
      } 
     } 
    }).start(); 
} 

Update

Эй Folks,

спасибо за все ваши ответы и подсказки. Теперь я знаю, как получить изображение с URL-адреса, но у меня все еще есть проблемы, чтобы показать его в моем изображении. Я хочу реализовать стопку фотографий для их скольжения для подобных и нелюбовь. Поэтому я создаю цикл, который создает относительныйLayout и imageView внутри для каждого элемента. Теперь я попытался поместить изображения из url в imageView, но это не сработало. Приложение запускается, и я вижу только белый экран.

Вот мой код:

//for each picture into the list... 
    for (int i = 0; i < imageUrl.size(); i++) { 

     //set RelativeLayout 
     final RelativeLayout relView = new RelativeLayout(this); 
     //set Params for the RelativeLayout 
     relView.setLayoutParams(new RelativeLayout.LayoutParams((windowWidth - 80), windowHeight - 80)); 
     relView.setX(40); 
     relView.setY(40); 
     relView.setTag(i); 
     //set BackgroundColor RelativeLayout 
     relView.setBackgroundColor(Color.WHITE); 

     String url = imageUrl.get(i); 

     //set ImageView 
     ImageView img = new ImageView(this); 
     Picasso 
       .with(this) 
       .load(url) 
       .resize(600, 200) 
       .centerCrop() 
       .into(img); 
     //set params to RelativLayout 
     img.setLayoutParams(new RelativeLayout.LayoutParams((windowWidth), windowHeight)); 
     //show image 
     relView.addView(img); 

     //create and set like stamp 
     final Button imageLike = new Button(this); 
     imageLike.setLayoutParams(new ActionBar.LayoutParams(100, 50)); 
     imageLike.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_stamp_like)); 
     imageLike.setX(20); 
     imageLike.setY(80); 
     imageLike.setAlpha(alphaValue); 

     relView.addView(imageLike); 

     //create and set dislike stamp 
     final Button imagePass = new Button(this); 
     imagePass.setLayoutParams(new ActionBar.LayoutParams(100, 50)); 
     imagePass.setBackgroundDrawable(getResources().getDrawable(R.drawable.ic_stamp_pass)); 
     imagePass.setX((windowWidth - 200)); 
     imagePass.setY(100); 
     imagePass.setRotation(45); 
     imagePass.setAlpha(alphaValue); 

     relView.addView(imagePass); 


     //create touchlistener for slide 
     final int finalI = i; 
     relView.setOnTouchListener(new View.OnTouchListener() { 
      @Override 
      public boolean onTouch(View v, MotionEvent event) { 
       //get screen coordinates 
       x_cord = (int) event.getRawX(); 
       y_cord = (int) event.getRawY(); 

       //set coordinates to RelativeLayout 
       relView.setX(x_cord - screenCenter + 40); 
       relView.setY(y_cord - 650); 

       switch (event.getAction()) { 
        //if picture slide down, nothing happens 
        case MotionEvent.ACTION_DOWN: 
         break; 
        //if pictures slide to side right, set rotation coordinates 
        //to RelativeLayout, set likes to 2 
        case MotionEvent.ACTION_MOVE: 
         x_cord = (int) event.getRawX(); 
         y_cord = (int) event.getRawY(); 
         relView.setX(x_cord - screenCenter + 40); 
         relView.setY(y_cord - 650); 
         if (x_cord >= screenCenter) { 
          relView.setRotation((float) ((x_cord - screenCenter) * (Math.PI/32))); 
          if (x_cord > (screenCenter + (screenCenter/2))) { 
           imageLike.setAlpha(1); 
           if (x_cord > (windowWidth - (screenCenter/4))) { 
            likes = 2; 
           } else { 
            likes = 0; 
           } 

          } else { 
           likes = 0; 
           imageLike.setAlpha(0); 
          } 
          imagePass.setAlpha(0); 
         } else { 

          //Rotation 
          relView.setRotation((float) ((x_cord - screenCenter) * (Math.PI/32))); 
          if (x_cord < (screenCenter/2)) { 
           imagePass.setAlpha(1); 
           if (x_cord < screenCenter/4) { 
            likes = 1; 
           } else { 
            likes = 0; 
           } 
          } else { 
           likes = 0; 
           imagePass.setAlpha(0); 
          } 
          imageLike.setAlpha(0); 
         } 
         break; 
        //if pictures moved up, picture were dropped to the primary position 
        case MotionEvent.ACTION_UP: 
         x_cord = (int) event.getRawX(); 
         y_cord = (int) event.getRawY(); 

         Log.e("X Point", "" + x_cord + " , Y " + y_cord); 
         imagePass.setAlpha(0); 
         imageLike.setAlpha(0); 

         //if like 0 nothing happens 
         if (likes == 0) { 
          Log.e("Event Status", "Nothing"); 
          relView.setX(40); 
          relView.setY(40); 
          relView.setRotation(0); 
          //if like == 1 destroy RelativeLayout with the picture 
         } else if (likes == 1) { 
          Log.e("Event Status", "Passed"); 
          imgContainer.removeView(relView); 
         } else if (likes == 2) { 
          //check and creat list 
          if (likeImageList == null) { 
           likeImageList = new ArrayList<>(); 
          } 
          //add picture to list 
          LikedImage likedImage = new LikedImage(); 
          likedImage.img = (BitmapFactory.decodeResource(getResources(), imageList[finalI])); 

          //save image as file 
          saveImageToExternalStorage(likedImage.img); 
          likeImageList.add(likedImage); 
          Log.e("Event Status", "Liked"); 
          Log.e("Groeße der Liste", "" + likeImageList.size()); 
          imgContainer.removeView(relView); 
         } 
         break; 
        default: 
         break; 
       } 
       return true; 
      } 
     }); 

     imgContainer.addView(relView); 
    } 
+0

Вам необходимо скачать изображение с url, тогда вы сможете установить его в изображение. – GrIsHu

ответ

0

Вы должны загрузить изображение в первую очередь

public static Bitmap loadBitmap(String url) { 
Bitmap bitmap = null; 
InputStream in = null; 
BufferedOutputStream out = null; 

try { 
    in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE); 

    final ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 
    out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE); 
    copy(in, out); 
    out.flush(); 

    final byte[] data = dataStream.toByteArray(); 
    BitmapFactory.Options options = new BitmapFactory.Options(); 
    //options.inSampleSize = 1; 

    bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options); 
} catch (IOException e) { 
    Log.e(TAG, "Could not load Bitmap from: " + url); 
} finally { 
    closeStream(in); 
    closeStream(out); 
} 

return bitmap; 

}

Затем используйте Imageview.setImageBitmap установить растровое изображение в ImageView

+0

Эй, такая же проблема, как и первый ответ. Нет изображений на imageView – dudi

+0

Эй, первое изображение для проверки полностью загружается с адреса или нет –

1

использовать Picaso ..

Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView); 

в вашем gradel

compile 'com.squareup.picasso:picasso:2.5.2' 
+0

Один глупый вопрос. Что я должен использовать для контекста? Я сохраняю URL-адрес изображения из твиттера в ArrayList . Поэтому для каждого URL-адреса я хочу сделать imageView и поместить изображение внутрь. Здесь мой код: '// для каждого изображения в списке ... для (int i = 0; i dudi

+0

Я пробовал:' Picasso.with (this) .load (imageUrl.get (i)). В (img); 'но я не вижу никаких изображений в imageViews – dudi

+0

try изменить размер изображения – Ashish

0

его просто, вы можете использовать изображения погрузчиков с мощностью LazyLoad как скольжение:

первым добавить зависимость к build.gradle

dependencies { 
    // glide 
    compile 'com.github.bumptech.glide:glide:3.7.0' 
} 

затем используйте это в своей деятельности:

String imgUrl = "http://yoururl.com"; 

ImageView imageView = (ImageView) view.findViewById(R.id.thumbnail); 

Glide.with(mContext).load(imgUrl) 
       .thumbnail(0.5f) 
       .crossFade() 
       .diskCacheStrategy(DiskCacheStrategy.ALL) 
       .into(imageView); 

Goodluck.

+0

Эй, такая же проблема, как ответ ниже. У меня нет изображений внутри моего образа. – dudi

+0

Ур проблема найти URL. но так я объяснил. –

Смежные вопросы