2014-09-13 3 views
0

그래서 나는 gridview에 textView와 Button을 가지고 있습니다. gridview에서 SD 카드에있는 폴더의 이미지를 표시하려고합니다.그리드 뷰의 SD 카드 폴더에있는 안드로이드 조각로드 이미지가 나를 위해 작동하지 않습니다

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> 

단편의 배치는 다음과 같다 :

<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:paddingLeft="5dp" 
    android:paddingRight="5dp" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    > 

    <GridView xmlns:android="http://schemas.android.com/apk/res/android" 
     android:id="@+id/photogridview" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:columnWidth="90dp" 
     android:numColumns="auto_fit" 
     android:verticalSpacing="10dp" 
     android:horizontalSpacing="10dp" 
     android:stretchMode="columnWidth" 
     android:gravity="center"> 
    </GridView> 

    <Button 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="New capture" 
     android:id="@+id/btncapture" 
     android:layout_alignParentBottom="true" 
     android:layout_alignParentLeft="true" 
     android:layout_alignParentStart="true" /> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textAppearance="?android:attr/textAppearanceMedium" 
     android:text="Medium Text" 
     android:id="@+id/tvCalea" 
     android:layout_alignTop="@+id/btncapture" 
     android:layout_toRightOf="@+id/btncapture" 
     android:layout_toEndOf="@+id/btncapture" /> 
</RelativeLayout> 

단편의 코드이다

는 I 매니페스트의 권한을 첨가
@Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     String CaleaMea=""; 
     Bundle bundle = this.getArguments(); 
     if(bundle != null){ 
      CaleaMea = bundle.getString("patu", ""); 
     } 

     View view = inflater.inflate(R.layout.photos_layout,container,false); 
     GridView gridView = (GridView) view.findViewById(R.id.photogridview); 
     gridView.setAdapter(new PhotoImageAdapter(view.getContext(),CaleaMea)); // uses the view to get the context instead of getActivity(). 
     Log.d("POZE frag:",CaleaMea); 

     TextView tv = (TextView) view.findViewById(R.id.tvCalea); 
     tv.setText(CaleaMea); 

     Button btn = (Button) view.findViewById(R.id.btncapture); 
     final String finalCaleaMea = CaleaMea; 
     btn.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
       File resultingFile = new File(finalCaleaMea.toString() + "/image.jpg"); 
       Uri uriSavedImage=Uri.fromFile(resultingFile); 
       cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage); 

       startActivityForResult(cameraIntent, 1888); 
      } 
     }); 

     return view; 
    } 

    @Override 
    public void onActivityCreated(Bundle savedInstanceState) { 
     super.onActivityCreated(savedInstanceState); 
    } 

(10)과 어댑터 :

public class PhotoImageAdapter extends BaseAdapter { 
     private Context mContext; 
     private String mCalea; 
     ArrayList<String> itemList = new ArrayList<String>(); 

     public PhotoImageAdapter(Context c) { 
      mContext = c; 
     } 
     public PhotoImageAdapter(Context c, String calea) { 
     mContext = c; 
     mCalea = calea; 
    } 

     void add(String path) { 
      itemList.add(path); 
     } 

     void clear() { 
      itemList.clear(); 
     } 

     void remove(int index){ 
      itemList.remove(index); 
     } 

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

     @Override 
     public Object getItem(int position) { 
      return itemList.get(position); 
     } 

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

     @Override 
     public View getView(int position, View convertView, ViewGroup parent) { 
      ImageView imageView; 
      if (convertView == null) { // if it's not recycled, initialize some 
       // attributes 
       imageView = new ImageView(mContext); 
       imageView.setLayoutParams(new GridView.LayoutParams(220, 220)); 
       imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 
       imageView.setPadding(8, 8, 8, 8); 
      } else { 
       imageView = (ImageView) convertView; 
      } 

      Bitmap bm = decodeSampledBitmapFromUri(itemList.get(position), 220, 
        220); 

      imageView.setImageBitmap(bm); 
      return imageView; 
     } 

     public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, 
               int reqHeight) { 
      Bitmap bm = null; 
      // First decode with inJustDecodeBounds=true to check dimensions 
      final BitmapFactory.Options options = new BitmapFactory.Options(); 
      options.inJustDecodeBounds = true; 
      BitmapFactory.decodeFile(path, options); 
      // Calculate inSampleSize 
      options.inSampleSize = calculateInSampleSize(options, reqWidth, 
        reqHeight); 
      // Decode bitmap with inSampleSize set 
      options.inJustDecodeBounds = false; 
      bm = BitmapFactory.decodeFile(path, options); 
      return bm; 
     } 

     public int calculateInSampleSize(

       BitmapFactory.Options options, int reqWidth, int reqHeight) { 
      // Raw height and width of image 
      final int height = options.outHeight; 
      final int width = options.outWidth; 
      int inSampleSize = 1; 

      if (height > reqHeight || width > reqWidth) { 
       if (width > height) { 
        inSampleSize = Math.round((float) height 
          /(float) reqHeight); 
       } else { 
        inSampleSize = Math.round((float) width/(float) reqWidth); 
       } 
      } 
      return inSampleSize; 
     } 



AsyncTaskLoadFiles myAsyncTaskLoadFiles; 
public class AsyncTaskLoadFiles extends AsyncTask<Void, String, Void> { 
    File targetDirector; 
    ImageAdapter myTaskAdapter; 

    public AsyncTaskLoadFiles(ImageAdapter adapter) { 
     myTaskAdapter = adapter; 
    } 

    @Override 
    protected void onPreExecute() { 
     String ExternalStorageDirectoryPath = Environment 
       .getExternalStorageDirectory().getAbsolutePath(); 

     String targetPath = ""; 
     targetPath = mCalea; 
     Toast.makeText(mContext,mCalea,Toast.LENGTH_SHORT).show(); 
     targetDirector = new File(targetPath); 
     myTaskAdapter.clear(); 

     super.onPreExecute(); 
    } 

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

     File[] files = targetDirector.listFiles(); 
     for (File file : files) { 
      publishProgress(file.getAbsolutePath()); 
      if (isCancelled()) break; 
     } 
     return null; 
    } 

    @Override 
    protected void onProgressUpdate(String... values) { 
     myTaskAdapter.add(values[0]); 
     super.onProgressUpdate(values); 
    } 

    @Override 
    protected void onPostExecute(Void result) { 
     myTaskAdapter.notifyDataSetChanged(); 
     super.onPostExecute(result); 
    } 

} 
} 

그래서, 동작은 다음과 같습니다 아무것도 버튼 및 텍스트 뷰를 제외하고, 조각에 표시되지됩니다. 그래서 GridView는 이미지로 채워지지 않습니다 ...

무엇이 잘못 되었나요? 그래서 당신이 그것에 대한 참조를 유지하지 않는 원인 당신이있는 항목을 채우는하지 않을 생각

gridView.setAdapter(new PhotoImageAdapter(view.getContext(),CaleaMea)); // uses the view to get the context instead of getActivity(). 

:

당신은 같이있는 gridview의 어댑터를 설정하는 당신에게

답변

1

감사드립니다.

편집 : 확실히 그 문제가 당신이 당신의 어댑터의 getCount에 들어갈 항목의 양() 방법를 기록 할 수있어 확인합니다. 또한 "AsyncTask.execute (...)"메소드에 코드 내에 참조가 없기 때문에 AsycTask를 실행 중인지 확인할 수 있습니다.

: 당신의 AsyncTask를을 사용하여 어댑터를 생성 한 후

photoImageAdapter = new PhotoImageAdapter(view.getContext(),CaleaMea); 

당신이 그것을의 항목을 채우는 :

PhotoImageAdapter photoImageAdapter; 

이 그 다음을 intantiate :

글로벌 구성원으로 어댑터를 선언하십시오

AsyncTaskLoadFiles alf = new AsyncTaskLoadFiles(photoImageAdapter); 
alf.execute(); 

다음 gridview 어댑터를 설정합니다 :

gridView.setAdapter(photoImageAdapter); 

희망이 있습니다.

+0

내가 글로벌 회원으로 선언한다는 것은 무엇을 의미합니까? 어디에서 선언해야합니까? 'public class poze_fragment extends Fragment {'의 직후입니까? – user1137313

+0

예. 필수는 아니지만 코드의 여러 위치에서 참조를 유지해야하는 경우 좋은 방법입니다. –

+0

어댑터의 getCount() 메소드 내에 목록의 크기를 기록하여 목록 채우기에 실패했는지 확인하십시오. –

관련 문제