将上下文菜单添加到preferenceScreen子项

时间:2017-03-17 16:05:06

标签: android

我正在使用AppCompatPreferenceActivity作为我的根类

是否可以将上下文菜单添加到<preference>

我设法在answer之后的首选项上实现了长按一下监听器。

我在 onPostCreate()

中添加了 registerForContextMenu(getListView())

我用菜单充气器覆盖了 onCreateContextMenu()

SetingsActivity:

public class SettingsActivity extends AppCompatPreferenceActivity {
    private static ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupActionBar();
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        listView = getListView();    
        registerForContextMenu(listView);
    }
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        menu.setHeaderTitle("Context Menu");
        inflater.inflate(R.menu.context_fingeprint_prints, menu);
        System.out.println("hey");
    }
}

LongClickPrefernce:

public abstract class LongClickPreference  extends Preference implements View.OnLongClickListener {
    private Context context;
    @Override
    protected View onCreateView(ViewGroup parent) {

        ListView listView = (ListView)parent;
        listView.setOnItemLongClickListener(new ListView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                ListView listView = (ListView) parent;
                ListAdapter listAdapter = listView.getAdapter();
                Object obj = listAdapter.getItem(position);
                if (obj != null && obj instanceof View.OnLongClickListener) {
                    View.OnLongClickListener longListener = (View.OnLongClickListener) obj;
                    return longListener.onLongClick(view);
                }
                return false;
            }
        });

        return super.onCreateView(parent);
    }

    public LongClickPreference(Context context) {
        super(context);
        this.context = context;
    }

    @Override
    public abstract boolean onLongClick(View v);

}

使用的偏好:

LongClickPrefernce test = new LongClickPrefernce(getActivity()){
    @Override
    public boolean onLongClick(View v) {
        getActivity().openContextMenu((View)listView);
        return false;
    }
};
test.setTitle("test");

当我长按“首选项”时, onCreateContextMenu()会被调用,但不会显示任何内容

感谢任何帮助。

0 个答案:

没有答案