9

を使用してGallery、イベントの水平方向のタイムラインを表示しています。いくつかのイベントは取得Gravity.TOPし、いくつかGravity.BOTTOMは年を表示する素敵な線の上または下にそれらを揃えます。ここまでは順調ですね。

上部の要素の左マージンプロパティを変更したいので、大きなギャップはなく、要素はインターリーブされているように見えます。例:上に配置されたすべての要素に負の左マージンを設定します。

の各要素はでGallery構成され、プログラムでマージンを変更するためLinearLayoutのインスタンスを設定できます。MarginLayoutParamsただし、Galleryコードがこれを行うため、アダプター内でClassCastException使用するとが発生します。MarginLayoutParams

    // Respect layout params that are already in the view. Otherwise
    // make some up...
    Gallery.LayoutParams lp = (Gallery.LayoutParams) child.getLayoutParams();

この問題を克服する方法についてのアイデアやヒントはありますか?

4

2 に答える 2

4

ギャラリーの各要素は、LinearLayout

別のものを使用してラップし、内側LinearLayoutの にマージンを設定するだけです。私はそれをチェックしました、そしてそれはあなたが望むことをするようです。LinerLayout.LayoutParamsLinearLayout

したがって、ギャラリー アイテム用にインフレートするレイアウトは次のようになります。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layOuter"
    android:layout_width="wrap_content" android:layout_height="wrap_content">

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

        <ImageView android:id="@+id/imageView1" android:src="@drawable/icon"
            android:layout_height="wrap_content" android:layout_width="wrap_content"
            android:scaleType="fitXY" />

        <TextView android:text="TextView" android:id="@+id/textView"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:visibility="visible" />
    </LinearLayout>
</LinearLayout>

次に、アダプター メソッドで内部 LinearLayout にアクセスgetViewし、条件に応じてそこにマージンを設定できます (convertView 再利用最適化を使用しないサンプル コード)。

public View getView(int position, View convertView, ViewGroup parent) {
  Context context = getContext();
  final float density = context.getResources().getDisplayMetrics().density;

  LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  View layOuter = inflater.inflate(R.layout.row_layout, null);
  View layInner = layOuter.findViewById(R.id.layInner);
  if (...) {  // your condition
    LinearLayout.LayoutParams innerLP = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    innerLP.leftMargin = (int) (50 * density);
    layInner.setLayoutParams(innerLP);
  }
  return layOuter;
}

LinearLayout.LayoutParams内側のレイアウトには (拡張する) を使用する必要があることに注意してくださいMarginLayoutParams。そうしないと機能しません。

于 2011-05-05T11:11:45.633 に答える
-2

Gallery.LayoutParamsは、android.view.ViewGroup.LayoutParamsとはまったく異なるクラスです。

子ビュー(アダプターから作成)は、android.view.ViewGroup.LayoutParamsを返すLinearLayoutですが、GalleryはGallery.LayoutParamsを返します。

Gallery.LayoutParamsの代わりにandroid.view.ViewGroup.LayoutParamsを使用してみてください。両方を使用する必要がある場合は、必要に応じてプロパティを一方から他方に手動で設定します(ただし、両方を使用する必要がある理由はよくわかりません)。

于 2011-05-04T19:11:10.883 に答える