2016-10-06 15 views
0

2つのレイアウト1)イメージ用と2)ドキュメント用 MainActivityでオプションメニューでデバイスストレージからimageまたはpdfを選択し、pojoクラスを使用してアダプタクラスにデータを送信します。リサイクラビューに2つの異なるレイアウトを動的に追加します

私の問題は、私がリサイクラビューで適切にバインドすることができないことです。リサイクラビューで表示される画像よりもイメージを選択したい場合、同じリストでも同様にpdfファイルビューで表示されます。

public class HirenModifided extends AppCompatActivity { 
    private Dialog dialog; 
    private RecyclerView recyclerView; 
    SetterGetter setGet; 

    public static final int RESULT_LOAD_FILE = 0; 
    public static final int RESULT_LOAD_IMAGE = 1; 
    public static final int RESULT_OK = -1; 
    public static final int REQUEST_IMAGE_CAPTURE = 2; 
    private ImageAdapter objAdapter; 
    public static ArrayList<SetterGetter> pdfPaths = new ArrayList<>(); 
    public static ArrayList<SetterGetter> imagePaths = new ArrayList<>(); 

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

     recyclerView = (RecyclerView) findViewById(R.id.recycler); 
     setGet = new SetterGetter(); 

     recyclerView.setHasFixedSize(true); 
     LinearLayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext()); 
     recyclerView.setLayoutManager(mLayoutManager); 
     objAdapter = new ImageAdapter(getApplicationContext()); 
     recyclerView.setAdapter(objAdapter); 


    } 


    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.menu, menu); 
     return true; 
    } 

    public boolean onOptionsItemSelected(MenuItem item) { 
     switch (item.getItemId()) { 
      case R.id.image: 
       itemAddClick(); 
       return true; 
      case R.id.file: 
       FilePicker(); 
       return true; 
      default: 
       return super.onOptionsItemSelected(item); 
     } 
    } 

    public void FilePicker() { 
     Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); 
     intent.addCategory(Intent.CATEGORY_OPENABLE); 
     intent.setType("*/*"); 
     startActivityForResult(intent, RESULT_LOAD_FILE); 
    } 


    public void itemAddClick() { 
     dialog = new Dialog(HirenModifided.this); 
     dialog.setContentView(R.layout.custom_dialog_box); 
     dialog.setTitle("Select Photo"); 

     Button btnExit = (Button) dialog.findViewById(R.id.btnExit); 
     btnExit.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       dialog.dismiss(); 
      } 
     }); 
     dialog.findViewById(R.id.btnChoosePath).setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       activeGallery(); 
      } 
     }); 
     dialog.findViewById(R.id.btnTakePhoto).setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       activeTakePhoto(); 
      } 
     }); 

     // show dialog on screen 
     dialog.show(); 
    } 

    private void activeGallery() { 
     Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
     startActivityForResult(intent, RESULT_LOAD_IMAGE); 
     dialog.dismiss(); 
    } 

    private void activeTakePhoto() { 

     Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
     startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); 
     dialog.dismiss(); 

    } 


    //this method is for resize image 
    public Bitmap getResizedBitmap(Bitmap image, int maxSize) { 
     int width = image.getWidth(); 
     int height = image.getHeight(); 

     float bitmapRatio = (float) width/(float) height; 
     if (bitmapRatio > 1) { 
      width = maxSize; 
      height = (int) (width/bitmapRatio); 
     } else { 
      height = maxSize; 
      width = (int) (height * bitmapRatio); 
     } 
     return Bitmap.createScaledBitmap(image, width, height, true); 
    } 

    public void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 

     switch (requestCode) { 

      case RESULT_LOAD_IMAGE: 
       if (requestCode == RESULT_LOAD_IMAGE && 
         resultCode == RESULT_OK && null != data) { 
        Uri filePath = data.getData(); 
        Log.e("IMAGE", filePath + ""); 

        try { 
         InputStream imageStream = this.getContentResolver().openInputStream(filePath); 
         Bitmap selectedImage = BitmapFactory.decodeStream(imageStream); 
         ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
         selectedImage = getResizedBitmap(selectedImage, 400); 
         selectedImage.compress(Bitmap.CompressFormat.PNG, 100, stream); 

         byte[] byteArray = stream.toByteArray(); 
         /* setGet.path(Base64.encodeToString(byteArray, Base64.DEFAULT)); 
         imagePaths.add(setGet); 
         //FilePaths.clear(); 
         FilePaths.addAll(imagePaths); 
         objAdapter.notifyDataSetChanged();*/ 
         setGet.path(Base64.encodeToString(byteArray, Base64.DEFAULT)); 
         imagePaths.add(setGet); 
         objAdapter.insert(imagePaths); 


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

       } 


      case RESULT_LOAD_FILE: 
       if (requestCode == RESULT_LOAD_FILE && 
         resultCode == RESULT_OK && null != data) { 
        String FilePath = data.getData().getPath(); 
        Log.e("FILEPATH", FilePath); 
        String filename = FilePath.substring(FilePath.lastIndexOf("/") + 1); 
        Log.e("onActivityResult: ", filename); 

        /* setGet.path(filename); 
        pdfPaths.add(setGet); 
        //FilePaths.clear(); 
        FilePaths.addAll(pdfPaths); 
        objAdapter.notifyDataSetChanged();*/ 

        setGet.path(filename); 
        pdfPaths.add(setGet); 
        objAdapter.insert(pdfPaths); 
       } 
     } 


    } 


} 

POJO

public class SetterGetter { 
    public static String path; 


    public void path(String s) { 
     path = s; 
    } 

    public String getPath() { 
     return path; 
    } 


} 

アダプタ

public class ImageAdapter extends RecyclerView.Adapter<ImageAdapter.ViewHolder> { 
    private LayoutInflater inflater = null; 

    public static ArrayList<SetterGetter> file_paths = new ArrayList<>(); 

    public static final int RESULT_LOAD_FILE = 0; 
    public static final int RESULT_LOAD_IMAGE = 1; 

    int get_list_position; 

    Context context; 

    public ImageAdapter(Context mcontext) { 
     this.context = mcontext; 
     inflater = LayoutInflater.from(context); 
    } 


    public class ViewHolder extends RecyclerView.ViewHolder { 
     public ViewHolder(View itemView) { 
      super(itemView); 
     } 

    } 

    public class FilePick extends ViewHolder { 
     TextView temp; 

     public FilePick(View v) { 
      super(v); 
      this.temp = (TextView) v.findViewById(R.id.file_name); 
     } 
    } 

    public class ImagePick extends ViewHolder { 
     ImageView score; 

     public ImagePick(View v) { 
      super(v); 
      this.score = (ImageView) v.findViewById(R.id.image_list); 
     } 

    } 

    @Override 
    public void onAttachedToRecyclerView(RecyclerView recyclerView) { 
     super.onAttachedToRecyclerView(recyclerView); 
    } 

    // Insert a new item to the RecyclerView on a predefined position 
    public void insert(ArrayList<SetterGetter> data) { 

     file_paths.add(data.get(get_list_position)); 
     notifyItemInserted(get_list_position); 
    } 

    /* // Remove a RecyclerView item containing a specified Data object 
    public void remove(SetterGetter data) { 
     int position = file_paths.indexOf(data); 
     file_paths.remove(position); 
     Toast.makeText(context, "Deleted : " + position, Toast.LENGTH_SHORT).show(); 
     notifyItemRemoved(position); 
    }*/ 


    @Override 
    public int getItemViewType(int position) { 

     // Log.e("getItemViewType:pos ", String.valueOf(position)); 
     Log.e("IS this PDF ?", String.valueOf(file_paths.get(position).getPath().endsWith(".pdf"))); 
     if (file_paths.get(position).getPath().endsWith("pdf")) { 
      return RESULT_LOAD_FILE; 
     } else { 
      return RESULT_LOAD_IMAGE; 
     } 
    } 

    @Override 
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
     View v; 

     Log.e("layout code: ", viewType + ""); 

     if (viewType == RESULT_LOAD_FILE) { 
      v = inflater 
        .inflate(R.layout.file_raw, parent, false); 
      return new FilePick(v); 
     } else { 
      v = inflater 
        .inflate(R.layout.raw, parent, false); 
      return new ImagePick(v); 
     } 


    } 

    @Override 
    public void onBindViewHolder(ViewHolder holder, int position) { 


     Log.e("onBindViewHolder:pos ", String.valueOf(position)); 
     get_list_position = position; 

     if (holder instanceof FilePick) { 
      FilePick file = (FilePick) holder; 
      file.temp.setText(file_paths.get(position).getPath()); 

     } else if (holder instanceof ImagePick) { 
      ImagePick image = (ImagePick) holder; 
      byte[] decodeValue = new byte[0]; 
      try { 
       decodeValue = Base64.decode(file_paths.get(position).getPath().getBytes("UTF-8"), Base64.DEFAULT); 
      } catch (UnsupportedEncodingException e) { 
       e.printStackTrace(); 
      } 
      Bitmap bitmap = BitmapFactory.decodeByteArray(decodeValue, 0, decodeValue.length); 
      image.score.setImageBitmap(bitmap); 
     } 
    } 

    @Override 
    public int getItemCount() { 
     return file_paths.size(); 
    } 

} 
+0

あなたのコードは正しいようですが、あなたが直面しているエラー/問題は何ですか? iは画像最初に選択した場合 – Pr38y

+0

その番組likeE/AndroidRuntime:致命的な例外:メイン プロセス:com.example.guest999.demo_jordar、PID:10873 java.lang.IndexOutOfBoundsException:無効なインデックス1は、サイズがログを何1 – Hiren

+0

あります。 e( "onBindViewHolder:pos"、String.valueOf(position));印刷しますか? – Pr38y

答えて

0

あなたのレイアウトが実装されることを告げるあなたのPOJO内の1つのより多くの変数を追加します。

+2

これはコメント – Stallion

+0

のために答えることができました、はい、私もそれをしました。しかし、現在私はgetItemViewType(int位置){arryalistの内容を使用して}でビューの種類を選択することができますまた私は静的な値でチェックした。 – Hiren

0

@Override 
public void onBindViewHolder(ViewHolder holder, int position) { 


    Log.e("onBindViewHolder:pos ", String.valueOf(position)); 
    if (holder instanceof FilePick) { 
     FilePick file = (FilePick) holder; 
     file.temp.setText(Data.get(position).getPath()); 

    } else if (holder instanceof ImagePick) { 
     ImagePick image = (ImagePick) holder; 
     byte[] decodeValue = new byte[0]; 
     try { 
      decodeValue = Base64.decode(Data.get(position).getPath().getBytes("UTF-8"), Base64.DEFAULT); 
      Log.e("4", decodeValue + ""); 
     } catch (UnsupportedEncodingException e) { 
      e.printStackTrace(); 
     } 
     Bitmap bitmap = BitmapFactory.decodeByteArray(decodeValue, 0, decodeValue.length); 
     image.score.setImageBitmap(bitmap); 
    } 
} 

にごonBindViewHolderを変更すると、あなたを助けるかもしれません。

0

1つのアダプタを作成し、ユーザが何かを選択したときにData変数を更新し、notifyDataSetChangedメソッドを呼び出します。

public class MainActivity extends AppCompatActivity { 

private Dialog dialog; 
private RecyclerView recyclerView; 
ImageAdapter objImageAdapter; 
ArrayList<SetterGetter> FilePaths; 
ArrayList<SetterGetter> imagePaths; 
ArrayList<SetterGetter> pdfPaths; 
SetterGetter setGet; 

public static final int RESULT_LOAD_FILE = 0; 
public static final int RESULT_LOAD_IMAGE = 1; 
public static final int RESULT_OK = -1; 
public static final int REQUEST_IMAGE_CAPTURE = 2; 
private ImageAdapter objAdapter; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    recyclerView = (RecyclerView) findViewById(R.id.recycler); 
    setGet = new SetterGetter(); 
    FilePaths = new ArrayList<SetterGetter>(); 
    recyclerView.setLayoutManager(mLayoutManager); 

        objAdapter = new ImageAdapter(getApplicationContext(), FilePaths); 
        recyclerView.setAdapter(objAdapter); 

} 


@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.menu, menu); 
    return true; 
} 

public boolean onOptionsItemSelected(MenuItem item) { 
    switch (item.getItemId()) { 
     case R.id.image: 
      itemAddClick(); 
      return true; 
     case R.id.file: 
      FilePicker(); 
      return true; 
     default: 
      return super.onOptionsItemSelected(item); 
    } 
} 

public void FilePicker() { 
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); 
    intent.addCategory(Intent.CATEGORY_OPENABLE); 
    intent.setType("*/*"); 
    startActivityForResult(intent, RESULT_LOAD_FILE); 
} 


public void itemAddClick() { 
    dialog = new Dialog(MainActivity.this); 
    dialog.setContentView(R.layout.custom_dialog_box); 
    dialog.setTitle("Select Photo"); 

    Button btnExit = (Button) dialog.findViewById(R.id.btnExit); 
    btnExit.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      dialog.dismiss(); 
     } 
    }); 
    dialog.findViewById(R.id.btnChoosePath).setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      activeGallery(); 
     } 
    }); 
    dialog.findViewById(R.id.btnTakePhoto).setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      activeTakePhoto(); 
     } 
    }); 

    // show dialog on screen 
    dialog.show(); 
} 

private void activeGallery() { 
    Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); 
    startActivityForResult(intent, RESULT_LOAD_IMAGE); 
    dialog.dismiss(); 
} 

private void activeTakePhoto() { 

    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); 
    startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE); 
    dialog.dismiss(); 

} 

//Read Shared Images 

//this method is for resize image 
public Bitmap getResizedBitmap(Bitmap image, int maxSize) { 
    int width = image.getWidth(); 
    int height = image.getHeight(); 

    float bitmapRatio = (float) width/(float) height; 
    if (bitmapRatio > 1) { 
     width = maxSize; 
     height = (int) (width/bitmapRatio); 
    } else { 
     height = maxSize; 
     width = (int) (height * bitmapRatio); 
    } 
    return Bitmap.createScaledBitmap(image, width, height, true); 
} 

public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 
    switch (requestCode) { 

     case RESULT_LOAD_IMAGE: 
      if (requestCode == RESULT_LOAD_IMAGE && 
        resultCode == RESULT_OK && null != data) { 
       Uri filePath = data.getData(); 
       Log.e("IMAGE", filePath + ""); 

       try { 
        InputStream imageStream = this.getContentResolver().openInputStream(filePath); 
        Bitmap selectedImage = BitmapFactory.decodeStream(imageStream); 
        ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
        selectedImage = getResizedBitmap(selectedImage, 400); 
        selectedImage.compress(Bitmap.CompressFormat.PNG, 100, stream); 

        byte[] byteArray = stream.toByteArray(); 
        setGet.path(Base64.encodeToString(byteArray, Base64.DEFAULT)); 
        imagePaths.add(setGet); 
        //Log.e("IMAGE",FilePaths+""); 
        FilePaths.clear(); 
        FilePaths.addAll(imagePaths); 
        objAdapter.notifyDataSetChanged(); 





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

      } 


     case RESULT_LOAD_FILE: 
      if (requestCode == RESULT_LOAD_FILE && 
        resultCode == RESULT_OK && null != data) { 
       String FilePath = data.getData().getPath(); 
       Log.e("FILEPATH", FilePath); 
       String filename =    FilePath.substring(FilePath.lastIndexOf("/") + 1); 
       Log.e("onActivityResult: ", filename); 
       setGet.path(filename); 
       FilePaths.add(setGet); 
       pdfPaths.add(setGet); 
        //Log.e("IMAGE",FilePaths+""); 
        FilePaths.clear(); 
        FilePaths.addAll(pdfPaths); 
        objAdapter.notifyDataSetChanged(); 

      } 
    } 
} 
} 
関連する問題