2013-06-17 21 views
7

私はGridViewでイメージを表示していますが、今はすべてのイメージの下部にテキストを表示するコードを記述しました。イメージにテキストを表示する方法

は、私はこのように私のグリッドを表示したい:

enter image description here

が、このようになっては、[また、画像のテキストを表示する]:

enter image description here

メイン。 xml:

<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    > 
    <GridView 
     android:id="@+id/gridview" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:verticalSpacing="0dp" 
     android:horizontalSpacing="0dp" 
     android:stretchMode="columnWidth" 
     android:numColumns="2" 
     /> 
</FrameLayout> 
+0

を使用して、コンストラクタで定義されるべき? –

+2

GridViewのアイテムのカスタムレイアウトを作成し、そこにimage + TextViewを配置してアダプタに入力します。 – hardartcore

+0

は@ Android-Developerに同意します – Chetan

答えて

7

テキストを割り当てるためのテキストビューを含むカスタムグリッドアイテムレイアウトを定義する必要があります。

<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" > 
    <ImageView 
     android:id="@+id/thumbnail" 
     android:padding="8dp" 
     android:scaleType="cropCenter" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" /> 
    <TextView 
     android:id="@+id/title" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:padding="10dp" 
     android:layout_gravity="bottom" 
     android:textColor="@android:color/white" 
     android:background="#55000000" /> 
</FrameLayout> 

ここでは、親の寸法に合わせて設定ImageViewのを持っているでframeLayoutを作成して、この写真を表示するIm​​ageViewのだろう。次に、項目タイトルを表示するために使用され、FrameLayoutの下部に揃えられたTextViewがあります。

次に、このグリッドアイテムレイアウトを使用して正しい情報を表示するように、アダプタを編集する必要があります。

public View getView(int position, View convertView, ViewGroup parent) { 

    // Inflate the single grid item layout 
    if (convertView == null) { 
     convertView = mLayoutInflater.inflate(R.layout.grid_item, parent, false); 
    } 

    // Set Image 
    ImageView thumbnail = convertView.findViewById(R.id.thumbnail); 
    if (thumbnail != null) { 
     thumbnail.setImageResource(mThumbIds[position]); 
    } 

    // Set Text 
    TextView title = convertView.findViewById(R.id.title); 
    if (title != null) { 
     title.setText("Image Number: " + position); 
    } 

    return convertView;  
} 

mLayoutInflaterは、世界的にここで質問です何

mLayoutInflater = LayoutInflater.from(context); 
+0

これは、あなたが望むことを行う最も効率的な方法ですカスタムアダプタを使用すると、ビューをリサイクルしてコンテンツをカスタマイズできるためです。 –

関連する問題