1

Я хотел бы отобразить несколько изображений в формате сетки, по 2 изображения на строку. Как сделать это с помощью Android-запроса? Существующие примеры являются недостаточными и не имеют надлежащей документации ...Android-запрос: отображение сетки (изображения)

activity_identify_animals.xml:

<ProgressBar     
    android:layout_width="15dip"  
    android:layout_height="15dip" 
    android:id="@+id/progress" 
    android:layout_centerInParent="true" 
    /> 

<ImageView 
    android:id="@+id/image"  
    android:layout_width="fill_parent"  
    android:layout_height="75dip" 
    /> 

IdentifyAnimals.java:

package uk.ac.gla.serengeti.activities; 

import com.androidquery.AQuery; 

import uk.ac.gla.serengeti.R; 
import android.os.Bundle; 
import android.app.Activity; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.annotation.TargetApi; 
import android.os.Build; 

public class IdentifyAnimals extends Activity { 

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

     AQuery aq = new AQuery(this); 

     aq.id(R.id.image).progress(R.id.progress).image("http://www.ibeta.eu/blog/wp-content/uploads/2012/02/darthvader-design.jpg"); 
     aq.id(R.id.image).progress(R.id.progress).image("http://www.geekome.com/wp-content/uploads/2013/09/anakin-skywalker-voice-as-darth-vader.jpeg"); 
     aq.id(R.id.image).progress(R.id.progress).image("http://www.camelcitydispatch.com/wp-content/uploads/2013/01/Darth-Vader-liking-villans-more-than-heroes-31394364-1280-960.jpg"); 
     aq.id(R.id.image).progress(R.id.progress).image("http://www.geekbinge.com/wp-content/uploads/2013/08/Darth-Vader-Star-Wars.jpg"); 
     aq.id(R.id.image).progress(R.id.progress).image("http://static1.wikia.nocookie.net/__cb20111223224559/starwars/images/b/b0/DarthVader-CotF.jpg"); 
     aq.id(R.id.image).progress(R.id.progress).image("http://www.wallsave.com/wallpapers/1920x1200/darth-vader/460382/darth-vader-hd-free-for-460382.jpg"); 
    } 

    /** 
    * Set up the {@link android.app.ActionBar}, if the API is available. 
    */ 
    @TargetApi(Build.VERSION_CODES.HONEYCOMB) 
    private void setupActionBar() { 
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { 
      getActionBar().setDisplayHomeAsUpEnabled(true); 
     } 
    } 

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

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     switch (item.getItemId()) { 
     case android.R.id.home: 
      // This ID represents the Home or Up button. In the case of this 
      // activity, the Up button is shown. Use NavUtils to allow users 
      // to navigate up one level in the application structure. For 
      // more details, see the Navigation pattern on Android Design: 
      // 
      // http://developer.android.com/design/patterns/navigation.html#up-vs-back 
      // 
      //NavUtils.navigateUpFromSameTask(this); 
      finish(); 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 

} 

Ссылка: http://code.google.com/p/android-query/

ответ

4

Вы можете использовать GridView с 2 колонками

<GridView 
    android:id="@+id/gridviewimg" 
    android:layout_width="wrap_content" 
    android:layout_height="fill_parent" 
    android:gravity="center" 
    android:numColumns="2" 
    android:scrollbarStyle="outsideInset" 
    android:smoothScrollbar="true" 
    android:verticalSpacing="10dp" 
    android:paddingBottom="50dp" 
    android:paddingTop="10dp" /> 

EDIT Конечно. Вы можете написать свой собственный класс адаптера и заполнить массив

public class ImageListAdapter extends BaseAdapter { 

private Context context; 
private List<String> imgPic; 

public ImageListAdapter(Context c, List<String> thePic) { 
    context = c; 
    imgPic = thePic; 
} 

public int getCount() { 
    if(imgPic != null) 
     return imgPic.size(); 
    else 
     return 0; 
} 

//---returns the ID of an item--- 
public Object getItem(int position) { 
    return position; 
} 

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

//---returns an ImageView view--- 
public View getView(int position, View convertView, ViewGroup parent) { 
    ImageView imageView; 
    BitmapFactory.Options bfOptions=new BitmapFactory.Options(); 
    bfOptions.inDither=false;      //Disable Dithering mode 
    bfOptions.inPurgeable=true;     //Tell to gc that whether it needs free memory, the Bitmap can be cleared 
    bfOptions.inInputShareable=true;    //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future 
    bfOptions.inTempStorage=new byte[32 * 1024]; 
    if (convertView == null) { 
     imageView = new ImageView(context); 
     imageView.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); 
     imageView.setPadding(0, 0, 0, 0); 
    } else { 
     imageView = (ImageView) convertView; 
    } 
    FileInputStream fs = null; 
    Bitmap bm; 
    try { 
     fs = new FileInputStream(new File(imgPic.get(position).toString())); 

     if(fs!=null) { 
      bm=BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions); 
      imageView.setImageBitmap(bm); 
      imageView.setId(position); 
      imageView.setLayoutParams(new GridView.LayoutParams(200, 160)); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally{ 
     if(fs!=null) { 
      try { 
       fs.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
    return imageView; 
} 

} 

Позволь мне знать, если это нормально, то я могу помочь вам с всем кодом, а также.

MainActivity.java

public class MainActivity extends Activity implements OnClickListener { 

    Button captureBtn = null; 
    final int CAMERA_CAPTURE = 1; 
    private Uri picUri; 
    private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
    private GridView grid; 
    private List<String> listOfImagesPath; 
    public static final String GridViewDemo_ImagePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/GridViewDemo/"; 

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

     captureBtn = (Button)findViewById(R.id.capture_btn1); 
     captureBtn.setOnClickListener(this); 
     grid = (GridView) findViewById(R.id.gridviewimg); 

     listOfImagesPath = null; 
     listOfImagesPath = RetriveCapturedImagePath(); 
     if(listOfImagesPath!=null){ 
      grid.setAdapter(new ImageListAdapter(this,listOfImagesPath)); 
     } 
    } 

    @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; 
    } 

    @Override 
    public void onClick(View arg0) { 
     // TODO Auto-generated method stub 
     if (arg0.getId() == R.id.capture_btn1) { 

      try { 
       //use standard intent to capture an image 
       Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
       //we will handle the returned data in onActivityResult 
       startActivityForResult(captureIntent, CAMERA_CAPTURE); 
      } catch(ActivityNotFoundException anfe){ 
      //display an error message 
       String errorMessage = "Whoops - your device doesn't support capturing images!"; 
       Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT); 
       toast.show(); 
      } 
     } 

    } 

    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     if (resultCode == RESULT_OK) { 
      //user is returning from capturing an image using the camera 
      if(requestCode == CAMERA_CAPTURE){ 
       Bundle extras = data.getExtras(); 
       Bitmap thePic = extras.getParcelable("data"); 
       String imgcurTime = dateFormat.format(new Date()); 
       File imageDirectory = new File(GridViewDemo_ImagePath); 
       imageDirectory.mkdirs(); 
       String _path = GridViewDemo_ImagePath + imgcurTime+".jpg"; 
       try { 
        FileOutputStream out = new FileOutputStream(_path); 
        thePic.compress(Bitmap.CompressFormat.JPEG, 90, out); 
        out.close(); 
       } catch (FileNotFoundException e) { 
        e.getMessage(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
       listOfImagesPath = null; 
       listOfImagesPath = RetriveCapturedImagePath(); 
       if(listOfImagesPath!=null){ 
        grid.setAdapter(new ImageListAdapter(this,listOfImagesPath)); 
       } 
      } 
     } 
    } 

    private List<String> RetriveCapturedImagePath() { 
     List<String> tFileList = new ArrayList<String>(); 
     File f = new File(GridViewDemo_ImagePath); 
     if (f.exists()) { 
      File[] files=f.listFiles(); 
      Arrays.sort(files); 

      for(int i=0; i<files.length; i++){ 
       File file = files[i]; 
       if(file.isDirectory()) 
        continue; 
       tFileList.add(file.getPath()); 
      } 
     } 
     return tFileList; 
    } 
} 

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    tools:context=".MainActivity" > 

    <RelativeLayout 
     android:id="@+id/RelativeGridLayout" 
     android:layout_width="wrap_content" 
     android:layout_height="fill_parent" > 

     <GridView 
      android:id="@+id/gridviewimg" 
      android:layout_width="wrap_content" 
      android:layout_height="fill_parent" 
      android:gravity="center" 
      android:numColumns="2" 
      android:scrollbarStyle="outsideInset" 
      android:smoothScrollbar="true" 
      android:verticalSpacing="10dp" 
      android:paddingBottom="50dp" 
      android:paddingTop="10dp" /> 
    </RelativeLayout> 

    <RelativeLayout 
     android:id="@+id/RelativeLayout01" 
     android:layout_width="fill_parent" 
     android:layout_height="40dp" 
     android:layout_alignBottom="@+id/RelativeGridLayout" > 

     <Button 
      android:id="@+id/capture_btn1" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:layout_alignParentTop="true" 
      android:layout_centerHorizontal="true" 
      android:text="Camera" /> 
    </RelativeLayout> 

</RelativeLayout> 
+0

Спасибо. Не могли бы вы предоставить мне код о том, как динамически отображать изображения из массива строк или что-то в этом роде? – chuckfinley

+1

Конечно. Ознакомьтесь с моим обновленным ответом. – VikramV

+0

Я создал класс ImageListAdapter - как я теперь заполняю сетку? Извините, я совершенно новый в Android Development :) – chuckfinley