0

所以我做了一个类扩展 BaseAdaper,看起来像这样:

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;
}

}

在我的活动中,有一个 GridLayout 并将其适配器设置为 ProfileTileAdapter 的一个实例。在我的活动中,当用户长按其中一个视图(在本例中为 ProfileTile)时,我想打开一个上下文菜单,但我不知道如何操作。我还需要找出当用户在上下文菜单中选择一个选项时,ProfileTile 长按了什么所有的教程都在活动中使用静态视图进行操作,但不是这样。

4

1 回答 1

3

所以我最终想出了答案。因此,显然,当您将 GridView 注册到 Activity 中的上下文菜单时,使用Activity.registerForContextMenu(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);
}

}

所以解决方案很简单,但有时我们把事情复杂化了。

于 2011-08-12T02:57:03.217 回答