自定义布局与其他布局TextView交互

时间:2012-05-06 11:41:38

标签: java android xml

我有一个如下所示的自定义布局,我想从该布局文件中更新TextViews文本。但TextView根本不在布局文件中。

抱歉,我不知道如何正确描述我正在实施的内容。如果有人甚至可以就正确的术语提出建议,那将非常感激。

基本上我想在单击从com.grogorian.android.control.MinutePicker膨胀的按钮时将TextView从AM更改为PM。我在com.grogorian.android.control.MinutePicker中使用下面的java,但是一直得到一个空指针

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/L"
   android:orientation="horizontal"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:gravity="center_vertical|center_horizontal">  
<com.grogorian.android.control.MinutePicker
        android:id="@+id/Picker2"
        android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </com.grogorian.android.control.MinutePicker>
    <TextView android:id="@+id/AMPMIdentifier" 
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="AM" />

这是Java

    LinearLayout L = (LinearLayout)findViewById(R.id.L);
    TextView Identifier = (TextView)L.findViewById(R.id.AMPMIdentifier);
    Identifier.setText("PM");

编辑:这是来自

的代码
    but = new Button( context );
    but.setTextSize( TEXT_SIZE );
    but.setText( "-" );

    // Decrement once for a click
    but.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
LinearLayout L = (LinearLayout)findViewById(R.id.L);
    TextView Identifier = (TextView)L.findViewById(R.id.AMPMIdentifier);
    Identifier.setText("PM");
        }
    });
            this.setLayoutParams( new LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT ) );
    LayoutParams elementParams = new LinearLayout.LayoutParams( ELEMENT_WIDTH, ELEMENT_HEIGHT );

        addView( but, elementParams );

1 个答案:

答案 0 :(得分:0)

如果我猜,现在你正试图在OnCLickListener听众中找到你发布的布局文件中的LinearLayout L (你可能用作Activity的布局?!)。这将失败,因为找不到LinearLayout且对象将为null。如果这是你正在做的,那么尝试另一种方法:

but.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
      LinearLayout parent = (LinearLayout) v.getParent(); // I assumed your MinutePicker extends LinearLayout
      LinearLayout L = (LinearLayout) parent.getParent();
      TextView Identifier = (TextView)L.findViewById(R.id.AMPMIdentifier);
      Identifier.setText("PM");
    }
});

我没有测试过上面的代码(好吧,我甚至不知道你的MinutePicker是如何构建的)。如果这不是问题,您可能想要添加完整的异常堆栈跟踪。

相关问题