2011-08-11 162 views
1

所以我做了一個類擴展BaseAdaper,看起來像這樣:如何顯示上下文菜單網格佈局中的Android

public class ProfileTileAdapter extends BaseAdapter { 

private Context context; 
private ForwardingProfile[] profiles; 

public ProfileTileAdapter(Context context, ForwardingProfile[] profiles) { 
    this.context = context; 
    this.profiles = profiles; 
} 

@Override 
public int getCount() { 
    return profiles.length; 
} 

@Override 
public Object getItem(int position) { 
    return profiles[position]; 
} 

@Override 
public long getItemId(int position) { 
    return profiles[position].getID(); 
} 

@Override 
public View getView(int position, View convertView, ViewGroup arg2) { 
    ProfileTile tile = null; 
    if (convertView == null) { 
     tile = new ProfileTile(context, profiles[position]); 
     LayoutParams lp = new GridView.LayoutParams(
       LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT); 
     tile.setLayoutParams(lp); 
    } else { 
     tile = (ProfileTile) convertView; 
    } 
    return tile; 
} 

}

在我的活動有一個網格佈局和它的適配器設置爲ProfileTileAdapter的實例。在我的活動中,我想打開一個上下文菜單,當用戶長按其中一個視圖(在這種情況下是一個ProfileTile),但我不知道如何。當用戶在上下文菜單中選擇一個選項時,我還需要找出ProfileTile長時間按下的內容。所有的教程都在活動中使用靜態視圖進行操作,但不是這樣。

回答

4

所以我最終找出答案。很顯然,當你使用Activity.registerForContextMenu(GridView)註冊一個GridView到你的Activity中的上下文菜單時,它會獨立地註冊你從適配器返回的每個視圖。因此,這是該活動的樣子(適配器保持不變):

public class SMSForwarderActivity extends Activity { 
private GridView profilesGridView; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    this.setContentView(R.layout.main); 
    setUpProfilesGrid(); 
} 

    private void setUpProfilesGrid() { 
    profilesGridView = (GridView) this.findViewById(R.id.profilesGrid); 
    this.registerForContextMenu(profilesGridView); 
} 

@Override 
public void onCreateContextMenu(ContextMenu menu, View v, 
     ContextMenuInfo menuInfo) { 
    super.onCreateContextMenu(menu, v, menuInfo); 
    AdapterContextMenuInfo aMenuInfo = (AdapterContextMenuInfo) menuInfo; 
    ProfileTile tile = (ProfileTile) aMenuInfo.targetView;//This is how I get a grip on the view that got long pressed. 
} 

    @Override 
public boolean onContextItemSelected(MenuItem item) { 
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item 
      .getMenuInfo(); 
    ProfileTile tile = (ProfileTile) info.targetView;//Here we get a grip again of the view that opened the Context Menu 
    return super.onContextItemSelected(item); 
} 

}

因此,解決辦法是相當簡單的,但有時我們在複雜的事情。