ошибка после добавления relativelayout внутри linearlayout?

Я хочу отображать миниатюры видео в списке, я использую изображения вместо миниатюр и добавляю ImageView (кнопка воспроизведения изображений) спереди, но не прошел мой код xml, подобный этому

   <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    <TextView
        android:id="@+id/txttgl"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:layout_margin="5dip"
         android:paddingLeft="10dip"
         android:gravity="center_horizontal"/>
    <TextView
        android:id="@+id/tv_batas_unread"
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:layout_margin="5dip"
         android:paddingLeft="12dip"
         android:background="@drawable/counter_shape_birudonker"
         android:visibility="gone"
         android:gravity="center_horizontal"/>

<LinearLayout android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/ll_chat_item"
    android:orientation="horizontal" >
    <com.ltvie.chatkrawala.ImageViewRounded
        android:id="@+id/img_photo_pp_chatbox"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:paddingBottom="0dp"
        android:paddingLeft="2dp"
        android:paddingRight="2dp"
        android:adjustViewBounds="true"
        android:paddingTop="0dp"
        android:layout_marginTop="5dp"
        android:layout_marginLeft="3dp"
        android:src="@drawable/gada_photo"
        android:scaleType="fitXY" />
    <LinearLayout
        android:id="@+id/wrapper"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:gravity="left"
        android:orientation="vertical"
        android:layout_marginBottom="12dp"
        android:layout_weight="1"
        android:cacheColorHint="@android:color/transparent"
        >
        <TextView
            android:id="@+id/txtKodeGbr"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="gone"/>
        <TextView
            android:id="@+id/txtPesan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="gone"/>

        <TextView
            android:id="@+id/comment"
            android:layout_marginTop="9dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/buble_kiri"
            android:text="Bismillahirohmanirrohim"
            android:textColor="#000"
            android:textSize="15sp" />

        <LinearLayout
        android:id="@+id/rowFile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
            <RelativeLayout
            android:layout_height="match_parent"
            android:layout_width="wrap_content"
             >
                <ImageView
                android:id="@+id/img_dilvChat"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="3dp"
                android:contentDescription="@string/descGambar"
                android:background="@drawable/buble_kanan"
                android:src="@drawable/gada_photo"
                />
                <ImageView
                android:id="@+id/img_btn_play"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:contentDescription="@string/descGambar"
                android:layout_centerInParent="true"
                android:src="@drawable/play_icon"

                />
                <ProgressBar
                    android:id="@+id/chatBox_progress_img"
                    style="?android:attr/progressBarStyleSmallInverse"
                    android:visibility="gone"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true" />
            </RelativeLayout>
            <LinearLayout
            android:id="@+id/rowFileDesc"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:visibility="gone"
            android:layout_gravity="bottom"
            android:orientation="vertical">

                <TextView
                android:id="@+id/txtFileName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="10dip"            
                android:gravity="left"
                android:text="Nama File : test.zip"
                android:textSize="12sp" />

                <TextView
                android:id="@+id/txtFileSize"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="10dip"            
                android:gravity="left"
                android:text="Ukuran : 2324342 bytes"
                android:textSize="12sp" />
            </LinearLayout>
        </LinearLayout>

        <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
        <ImageView
            android:id="@+id/img_statusBaca"
            android:layout_marginTop="2dip"
            android:layout_width="15dip"
            android:layout_height="15dip"
            android:layout_marginRight="1dip"
            android:background="@drawable/indicator_sending"
            android:contentDescription="@string/descGambar"
            />

        <TextView
            android:id="@+id/txtjamchatMasuk"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dip"            
            android:gravity="left"
            android:text="setatus baca"
            android:textSize="12sp" />
        <TextView
            android:id="@+id/txtKiriKanan"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"            
            android:paddingLeft="5dip"
            android:paddingRight="5dip"
            android:text="right"
            android:visibility="gone" 
            />
    </LinearLayout>
  </LinearLayout>
<ImageView
        android:id="@+id/imgselected"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:contentDescription="@string/kosongan"
        android:src="@drawable/ico_member" />

</LinearLayout>
</LinearLayout>

мой код Java

    public class ChatboxArrayAdapter extends ArrayAdapter<OneComment> implements SectionIndexer{
    private TextView countryName;
    private LinearLayout wrapper,rowFileDesc,ll_chat_item;
    private TextView TanggalMasuk,txtKodeGbr,txtPesan,txtJam,txtKiriKanan,txtUkuranFile;
    private ImageView img_upload,img_statusbaca,imgPp_round;
    ImageView imgPhoto,imgCheck,imgBtnPlay;
    String namafileGambar,strPath,varStsBaca,tampilTgl;
    public CacheImageLoader imageLoader;
    Context ctx;
    Options opts = new BitmapFactory.Options();

    String TAG="chatboxArrayAdapter";
    File dir = new File(Environment.getExternalStorageDirectory()+"");
    File dirImage=new File(dir+"/a");
    File dirVideo=new File(dir+"/a");
    List<OneComment> countries;
    @Override
    public void add(OneComment object) {
        countries.add(object);
        super.add(object);

    }
    public void hapus_semua(){
        countries.clear();
    }
    public void hapus_item(int nomerx){
        countries.remove(nomerx);
        notifyDataSetChanged();
    }
    public void refresh_lv(){
        notifyDataSetChanged();
        Log.d("notify", "datachange");
    }

    public ChatboxArrayAdapter(Context context, int textViewResourceId, List<OneComment> datanya) {
        super(context, textViewResourceId);
        this.countries=datanya;
        this.ctx=context;
        imageLoader=new CacheImageLoader(context.getApplicationContext());
    }
    public int getCount() {
        return this.countries.size();
    }

    @Override
    public OneComment getItem(int index) {
        return this.countries.get(index);
    }
    public View getView(final int position, View convertView, ViewGroup parent) {
        View row = convertView;
        try{

        if (row == null) {
            LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.chatbox_detail, parent, false);
        }

        OneComment isiOneComen = getItem(position);

        wrapper = (LinearLayout) row.findViewById(R.id.wrapper);
        rowFileDesc=(LinearLayout) row.findViewById(R.id.rowFileDesc);
        ll_chat_item=(LinearLayout) row.findViewById(R.id.ll_chat_item);

        imgPhoto = (ImageView) row.findViewById(R.id.img_dilvChat);
        countryName = (TextView) row.findViewById(R.id.comment);
        txtKiriKanan = (TextView) row.findViewById(R.id.txtKiriKanan); //isi dari coment untuk menentukan letak buble di kiri ato dikanan,hanya untuk buble file untuk menentukan filenya masih di server apa sudah di downloa
        TanggalMasuk= (TextView) row.findViewById(R.id.txttgl);
        img_upload=(ImageView) row.findViewById(R.id.img_dilvChat);
        txtKodeGbr = (TextView) row.findViewById(R.id.txtKodeGbr);
        txtPesan=(TextView) row.findViewById(R.id.txtPesan);
        txtJam=(TextView) row.findViewById(R.id.txtjamchatMasuk);
        txtUkuranFile=(TextView) row.findViewById(R.id.txtFileSize);
        imgCheck=(ImageView) row.findViewById(R.id.imgselected);
        img_statusbaca=(ImageView) row.findViewById(R.id.img_statusBaca);
        imgPp_round=(ImageView) row.findViewById(R.id.img_photo_pp_chatbox); 
        imgBtnPlay=(ImageView) row.findViewById(R.id.img_btn_play);         

        txtPesan.setVisibility(View.GONE);
        txtKodeGbr.setVisibility(View.GONE);        
        img_upload.setVisibility(View.GONE);
        rowFileDesc.setVisibility(View.GONE);
            if(isiOneComen.comment.trim().equalsIgnoreCase("video")){   
//error goes here
                countryName.setVisibility(View.GONE);

                Log.d("fileDesc", isiOneComen.Filedesc);
                //strPath = namafileGambar;
                strPath = moduleGlobal.dirImageSent+"/"+isiOneComen.Filedesc;
                imgPhoto.setImageBitmap(changeSize(strPath));
                scaleImage(imgPhoto, ((int) isiOneComen.lebarScreen)-((int) isiOneComen.lebarScreen/4));
                imgBtnPlay.setVisibility(View.VISIBLE);
            }else{ //run work well
                countryName.setVisibility(View.VISIBLE);
                try{
                countryName.setText(getSmiledText(getContext(),isiOneComen.comment.toString()));
                }catch (Exception e) {
                    // TODO: handle exception
                    Log.e("addsmiley", e.toString());
                }
                countryName.setBackgroundResource(isiOneComen.left ? R.drawable.buble_kiri : R.drawable.buble_kanan);
            }

        }catch (Exception ez) {
            ll_chat_item.setVisibility(View.GONE);
            Log.e(TAG, ez.toString());
        }
        return row;
    }
    private Bitmap changeSize(String path){
        opts.inSampleSize = 1;                          
        Bitmap bm = BitmapFactory.decodeFile(path);
                    if (bm.getHeight() > 150 || bm.getWidth() > 150) {

            final int halfHeight = bm.getHeight() / 2;
            final int halfWidth = bm.getWidth() / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / opts.inSampleSize) > 150
                    && (halfWidth / opts.inSampleSize) > 150) {
                opts.inSampleSize *= 2;
            }
        }

        bm = BitmapFactory.decodeFile(path,opts); // this bitmap will be 1/8 the size of the original
        return bm;
    }

    private void scaleImage(ImageView view, int boundBoxInDp)
    {
        // Get the ImageView and its bitmap
        Drawable drawing = view.getDrawable();
        Bitmap bitmap = ((BitmapDrawable)drawing).getBitmap();

        // Get current dimensions
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        // Determine how much to scale: the dimension requiring less scaling is
        // closer to the its side. This way the image always stays inside your
        // bounding box AND either x/y axis touches it.
        float xScale = ((float) boundBoxInDp) / width;
        float yScale = ((float) boundBoxInDp) / height;
        float scale = (xScale <= yScale) ? xScale : yScale;

        // Create a matrix for the scaling and add the scaling data
        Matrix matrix = new Matrix();
        matrix.postScale(scale, scale);

        // Create a new bitmap and convert it to a format understood by the ImageView
        Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
        @SuppressWarnings("deprecation")
        BitmapDrawable result = new BitmapDrawable(scaledBitmap);
        width = scaledBitmap.getWidth();
        height = scaledBitmap.getHeight();

        // Apply the scaled bitmap
        view.setImageDrawable(result);

        // Now change ImageView's dimensions to match the scaled image
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
        params.width = width;
        params.height = height;
        view.setLayoutParams(params);
    }


    public Bitmap decodeToBitmap(byte[] decodedByte) {
        return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
    }
    /**tambah smiley
     * 
     */
    private static final HashMap<String, Integer> emoticons = new HashMap<String, Integer>();
    static {
        emoticons.put(":)", R.drawable.s1);
        emoticons.put(":D", R.drawable.s2);
        emoticons.put(":(", R.drawable.s3);
        emoticons.put("8o|", R.drawable.s16);
        emoticons.put(":/", R.drawable.s17);
       }
    // Get image for each text smiles
    public static Spannable getSmiledText(Context context, String text) {
          SpannableStringBuilder builder = new SpannableStringBuilder(text);
          int index;
          for (index = 0; index < builder.length(); index++) {
            for (Entry<String, Integer> entry : emoticons.entrySet()) {
              int length = entry.getKey().length();
              if (index + length > builder.length())
                continue;
              if (builder.subSequence(index, index + length).toString().equals(entry.getKey())) {
                builder.setSpan(new ImageSpan(context, entry.getValue()), index, index + length,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                index += length - 1;
                break;
              }
            }
          }
          return builder;
        }
    @Override
    public int getPositionForSection(int arg0) {
        // TODO Auto-generated method stub
        return 0;
    }
    @Override
    public int getSectionForPosition(int arg0) {
        // TODO Auto-generated method stub
        return 0;
    }
    @Override
    public Object[] getSections() {
        // TODO Auto-generated method stub
        return null;
    }
}

все работает хорошо, прежде чем я добавлю относительный макет, я хочу добавить центр просмотра изображений с другим просмотром изображений, но я получаю журнал ошибок

java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams

person ltvie    schedule 25.02.2015    source источник
comment
Очистите свой проект, затем запустите. Также в любом месте вашего проекта, если вы устанавливаете LayoutParam, отправьте этот код   -  person IshRoid    schedule 25.02.2015
comment
Это весь ваш XML-код? Кажется, не хватает закрывающих тегов 2 linearLayout.   -  person Mel    schedule 25.02.2015
comment
Вы использовали setLayoutParam метод? если да, опубликуйте этот код   -  person frogatto    schedule 25.02.2015
comment
Выложите пожалуйста код changsizeImage,   -  person IshRoid    schedule 25.02.2015
comment
@Ishrat: весь мой полный код .. извините, если структура не очень красивая ..: D   -  person ltvie    schedule 25.02.2015
comment
Пожалуйста, проверьте мой ответ ниже,   -  person IshRoid    schedule 25.02.2015


Ответы (3)


Проблема с

 LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();

Эта строка Измените эту строку на

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) view.getLayoutParams();
person IshRoid    schedule 25.02.2015
comment
никогда не задумывался, если в методе scaleImage грязное расположение .. спасибо ,, - person ltvie; 25.02.2015
comment
Спасибо @ltvie за то, что приняли мой ответ. :) (Upvote будет оценен по достоинству) - person IshRoid; 25.02.2015

Потому что вы забыли добавить

</LinearLayout>
 </LinearLayout>

at the end of your xml.
person Hanish Sharma    schedule 25.02.2015
comment
Без ‹/LinearLayout› программа не запустится, это не связано с вопросом - person IshRoid; 25.02.2015

Использовать этот

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dip"
        android:gravity="center_horizontal"
        android:paddingLeft="10dip" />

    <LinearLayout
        android:id="@+id/ll_chat_item"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/tv2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="gone" />

        <LinearLayout
            android:id="@+id/wrapper"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginBottom="12dp"
            android:layout_weight="1"
            android:cacheColorHint="@android:color/transparent"
            android:gravity="left"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/tv3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:visibility="gone" />

            <LinearLayout
                android:id="@+id/rowFile"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical" >

                <RelativeLayout
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" >

                    <ImageView
                        android:id="@+id/img_dilvChat"
                        android:layout_width="200dp"
                        android:layout_height="200dp"
                        android:layout_margin="3dp"
                        android:background="@drawable/buble_kanan"
                        android:contentDescription="@string/descGambar" />

                    <ImageView
                        android:id="@+id/img_btn_play"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerInParent="true"
                        android:contentDescription="@string/descGambar"
                        android:src="@drawable/play_icon" />
                </RelativeLayout>

                <TextView
                    android:id="@+id/tv4"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="5dip"
                    android:gravity="center_horizontal"
                    android:paddingLeft="10dip" />
            </LinearLayout>
        </LinearLayout>
    </LinearLayout>


</LinearLayout>
person Jignesh Jain    schedule 25.02.2015