0

我目前正在尝试在 android 4.0 的应用程序中开发某种用户配置文件。在此活动中,我将添加未定义数量的以下类型的字段。现在我想为所有字段添加一个上下文菜单并访问这对中两个字段上的文本,无论长按哪个字段。

<GridLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:columnCount="2"
    android:orientation="horizontal"
    android:rowCount="1" 
    android:paddingLeft="5dp">

    <TextView
        android:id="@+id/subscriberFieldTextPrefix"
        android:layout_column="0"
        android:layout_gravity="left"
        android:layout_row="0"
        android:paddingRight="10dp"
        android:paddingTop="5dp"
        android:text="test"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#FFAAAAAA"
        android:textIsSelectable="false" />

    <TextView
        android:id="@+id/subscriberFieldTextText"
        android:layout_column="1"
        android:layout_gravity="left"
        android:layout_row="0"
        android:paddingRight="10dp"
        android:paddingTop="5dp"
        android:text="test"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textIsSelectable="false" />
</GridLayout>

我通过这样的代码添加这些“行”:

view = LayoutInflater.from(this).inflate(R.layout.subscriber_field_text, null);

((TextView) view.findViewById(R.id.subscriberFieldTextPrefix)).setText(currentSubscriber.GetSpecialFields().get(i).GetField() + ": ");
((TextView) view.findViewById(R.id.subscriberFieldTextText)).setText(currentSubscriber.GetSpecialFields().get(i).GetValue());

registerForContextMenu(((TextView) view.findViewById(R.id.subscriberFieldTextPrefix)));
registerForContextMenu(((TextView) view.findViewById(R.id.subscriberFieldTextText)));

layout.addView(view);

这将是我创建菜单的事件:

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) 
{
    menu.add(Menu.NONE, 1, 1, "test2");
}

现在在这种情况下,我可以获得原始字段的 ID,它只会将我引导到 XML 中的模板。而且我也得到了原始字段上的文本,但我不知道如何得到它们。文字完全够用,我不需要对象。

我希望有人可以帮助...谢谢。

4

1 回答 1

0

一种方法是将生成的变量分配给TextView类变量并从那里提取数据。

TextView blahText = ((TextView) view.findViewById(R.id.subscriberFieldTextPrefix)).setText(currentSubscriber.GetSpecialFields().get(i).GetField() + ": ");

TextView稍后访问。通常可见的变量也可以是一个 TextViews 数组(或者可能是一个 Map?),这会给你更多的可见性

List<TextView> textViewRows = new ArrayList<TextView>();

或者

Map<String,TextView> mapOfRows = new HashMap<String,TextView>();

使用地图的一种方法是使用菜单作为键,视图作为值。

Map<MenuItem,View> mapOfTextViews = new HashMap<MenuItem,View>();

这样您的上下文菜单的创建就会填充它们

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) 
{
    MenuItem newMenu = menu.add(Menu.NONE, 1, 1, "test2");
    mapOfTextViews.put(newMenu,v);
}

当 menuItem 被单击时,您使用 MenuItem 来查找当前视图。

于 2013-04-11T22:10:56.640 回答