Как отобразить контекстные меню для GridLayout в Android - PullRequest
1 голос
/ 11 августа 2011

Итак, я сделал расширение класса 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 долго нажимали, когда пользователь выбирает параметр в контекстном меню. Все учебные пособия продолжают делать это со статическими представлениями в действии, но не так.

1 Ответ

4 голосов
/ 12 августа 2011

Так что я в итоге выяснил ответ.Таким образом, очевидно, что когда вы регистрируете GridView для контекстного меню в вашей Активности, используя 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);
}

}

Так что решение было достаточно простым, но иногда мы слишком усложняли вещи.

...