簡體   English   中英

如何在充氣視圖上顯示上下文菜單?

[英]How to show contextmenu on inflated view?

我想為膨脹的視圖顯示上下文菜單。 這是代碼示例:

對於grid_layout.xml:

<?xml version="1.0" encoding="utf-8"?>    
    <ImageView
            xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="centerInside"
        android:antialias="true" />

現在我在我的活動課中使用它:

  @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {       
            menu.setHeaderTitle("Select action");       
            menu.add(0, 1, 0, "Action1");
            menu.add(0, 2, 0, "Action2");

            super.onCreateContextMenu(menu, v, menuInfo);
    }

    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    ImageView imageView = (ImageView) inflater.inflate(R.layout.grid_layout, null);
    imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               registerForContextMenu(v);
                       openContextMenu(v);
            }

        });

此代碼運行時沒有任何錯誤,但單擊imageView時上下文菜單不顯示。 這段代碼有什么問題嗎?

我找到了解決此問題的方法並解決了我的問題。 正如我所說,相同的代碼工作正常並顯示ContextMenu,如果我在我在setContentView()方法中設置的XML中定義ImageView。 我只是使用該imageView的對象來注冊contextMenu並在點擊膨脹項目時顯示ContextMenu。 以下是示例代碼:

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {       
            menu.setHeaderTitle("Select action");       
            menu.add(0, 1, 0, "Action1");
            menu.add(0, 2, 0, "Action2");

            super.onCreateContextMenu(menu, v, menuInfo);
    }

    ImageView imageViewInContext = (ImageView) findViewById(R.id.imageview_in_main_xml);
    registerForContextMenu(imageViewInContext);

    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    ImageView imageView = (ImageView) inflater.inflate(R.layout.grid_layout, null);
    imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {                   
                 openContextMenu(imageViewInContext);
            }

        });

希望這會對某人有所幫助!

添加您的代碼:

imageView.setFocusable(true);
imageView.setClickable(true);

之后,Imageview將獲得clickEvent。

因為您正在創建一個匿名內部類(通過執行new View.OnClickListener ),所以您不再在UI線程(您的Activity類)中操作,因此當您想要registerForContextMenuopenContextMenu時,不會加載上下文菜單。 您可以使用Handler將消息發送到UI線程(您的Activity類)來執行這些操作,或者嘗試在內部類中引用您的Activity類。 像這樣的東西:

activityClassName.this.registerForContextMenu(v);
activityClassName.this.openContextMenu(v);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM