2012-09-26 50 views
1

在我的Activity中,我在Viewpager中使用了Fragment。我的片段包含一些項目,如ImageView和ImageButton。是否有可能訪問我的片段中的sepecified項目?我想控制這一點。在我的項目中,當我按下鍵盤上的指定按鈕時,我想將焦點設置爲片段中的第一個ImageButton? Thx爲您提供幫助!Android:如何在Viewpager中訪問片段中的項目

main.xml中 ..........

  <android.support.v4.view.ViewPager 
       android:id="@+id/viewPagerDetail" 
       android:layout_width="1170dp" 
       android:layout_height="140dp" > 
      </android.support.v4.view.ViewPager> 

      <LinearLayout 
       android:id="@+id/motionCotrol" 
       android:layout_marginTop="10dp" 
       android:layout_width="84dp" 
       android:layout_height="120dp" 
       android:paddingBottom="15dp"> 

       <ImageView 
        android:id="@+id/img" 
        android:layout_width="84dp" 
        android:layout_height="105dp" 
        android:scaleType="fitXY" 
        android:src="@drawable/selection_thick" 
        /> 

      </LinearLayout> 
     </RelativeLayout> 

..........

fragment.xml之

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

    <!-- 
     <ImageView 
     android:layout_width="wrap_content" 
     android:layout_height="fill_parent" 
     android:layout_gravity="center_vertical" 
     android:layout_weight="0.1" 
     /> 
    --> 

    <include 

     android:layout_width="100dp" 
     android:layout_height="wrap_content" 
     layout="@layout/items" /> 

    <include 
     android:layout_width="100dp" 
     android:layout_height="wrap_content" 
     layout="@layout/items" /> 

    <include 
     android:layout_width="100dp" 
     android:layout_height="wrap_content" 
     layout="@layout/items" /> 

回答

0

1。在你的片段類中創建一個自定義的KeyDown事件。


    public void keyDownInFragment(int keyCode){ 
     // Your Implementation for focusing a widget goes here 
    } 

2。在您的Activity(FragmentActivity或MainActivity)中,使用以下代碼捕獲KeyDown事件:

@Override 
    public boolean onKeyDown(int keyCode, KeyEvent event) { 
    // Replace the key you have pressed in Keyboard for KeyEvent.KEYCODE_HOME in the following line 
     if (keyCode == KeyEvent.KEYCODE_HOME) { 
      // Call your fragment's keydown event method 
        ((FragmentName)fragments.get(0)).myOnKeyDown(keyCode); 
      // get(0) instead of zero user the index number at which you have inserted your fragment in the Page Adapter 
     } 
    } 
+0

thx u,我試過了,但它不起作用!因爲我在片段中使用ImageButton(在Activty中,當我按下鍵盤上的按鍵時,ImageButton將設置焦點)。我在Viewpager中使用的片段,我無法使用這個片段。我只能顯示片段視圖... – achilles205

+0

像((FragmentName)fragments.get(0))在onKeyDown函數內訪問您的片段。myOnKeyDown(keyCode);查看上面的更新代碼 – 2012-09-26 11:54:54

+0

在我的項目中,我只有一個片段,我將它設置爲FragmentStatePageAdapter。在我的fragment.xml中,我包含了一些項目(ImageButton)。現在我想處理片段上的第一項(我想在按下鍵盤上的按鍵時設置焦點)。我怎麼辦? (我只能顯示片段的視圖,但我無法使用它) – achilles205

相關問題