我在一个活动中有一个网格视图,每次点击网格元素时我都试图显示一个上下文菜单。我希望这个上下文菜单在文本视图中显示一个动态值(点击的网格元素的位置)。我正在创建自己的上下文菜单,因为我不想要警报或默认的 android 上下文菜单。我也在使用 SDK:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="16" />
这是我的网格视图的 java.class
public class Grid_Items extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grid_items);
GridView gridView = (GridView) findViewById(R.id.gridViewLayout);
gridView.setAdapter(new ImageAdapter(this));
gridView.setOnItemClickListener(new OnItemClickListener() {
View contextualMenuView = null;
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// RelativeLayout that contains parent layout
RelativeLayout rootLayout = (RelativeLayout)findViewById(R.id.root);
// in case there is a context menu open, remove it
if(contextualMenuView!=null) {
rootLayout.removeView(contextualMenuView);
}
// inflate contextual menu
contextualMenuView = getLayoutInflater().inflate(R.layout.contextual_menu, rootLayout);
// sets values for the textview
TextView tv = (TextView) findViewById(R.id.tab1);
tv.setText("tab1 = "+String.valueOf(position));
}
- 第一次单击网格元素时,我的上下文菜单会在文本视图中显示正确的文本值
- 第二次和每隔一次,菜单仍然存在,但 textview 文本值为空,每次用户点击网格中的元素时,我都需要“刷新”这个值
gridview 活动的布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent">
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridViewLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center">
</GridView>
</RelativeLayout>
我膨胀的上下文菜单的布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/contextualMenuLayout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#ffffff">
<!-- -->
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tab1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:layout_marginRight="10dip"
android:layout_marginLeft="10dip"
android:layout_marginTop="10dip"
android:layout_marginBottom="10dip"
android:textSize="28sp"
android:textColor="#ff0000">
</TextView>
我错过了什么?