如何在列表视图附近显示弹出菜单项目上的每个项目单击事件?
这是我的代码。我想在项目点击的列表视图项目附近显示弹出菜单。但它只显示在底部。所以帮我看一下点击列表项附近的弹出菜单。谢谢。
package saro.example.com.task2_listview;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ListAdapter;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.content.Context;
import android.widget.Toast;
import android.widget.PopupMenu;
public class MainActivity extends AppCompatActivity {
ListView list;
@Override
protected void onCreate(final Bundle savedInstanceState) {
String[] mobileArray = {"Android", "IPhone", "WindowsMobile", "Blackberry",
"WebOS", "Ubuntu", "Windows7", "Max OS X","Android", "IPhone", "WindowsMobile", "Blackberry"};
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter adapter = new ArrayAdapter<String>(this,
R.layout.activity_listview, mobileArray);
list = (ListView) findViewById(R.id.mobile_list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
int pos = parent.getPositionForView(v);
Toast.makeText(getApplicationContext(),pos+"",Toast.LENGTH_SHORT).show();
PopupMenu popup = new PopupMenu(MainActivity.this, list);
popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());
//
popup.show();
}
});
}
}
先谢谢。
答案 0 :(得分:2)
来自PopupMenu (Context context, View anchor)
锚点视图:此弹出窗口的锚点视图。如果有空间,则
The popup will appear below the anchor
,如果没有空间,则为v
。
使用 PopupMenu popup = new PopupMenu(MainActivity.this, v);
v
因为{{1}}这里是视图
单击AdapterView中的视图(这将是一个视图 由适配器提供)
答案 1 :(得分:1)
尝试将您的适配器视图v
的{{1}}作为视图传递到您的弹出式菜单中,如下面的代码
使用此 list
投放 PopupMenu popup = new PopupMenu(MainActivity.this, v);
<强>码强>
PopupMenu popup = new PopupMenu(MainActivity.this, list);