繁体   English   中英

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

[英]Custom Layout Interact with another layouts TextView

我有一个如下所示的自定义布局,我想从该布局文件中更新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 );

如果我猜到了,现在您正在尝试在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是如何构建的)。 如果这不是问题,则可能要添加可能获得的完整异常堆栈跟踪。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM