繁体   English   中英

从自定义视图返回值

[英]Returning values from custom view

我做了一个ShowWeight扩展LinearLayout的类,它有两个自定义Views作为内部类。 我通过main.xml中的XML标记使用此类:

<org.test.ShowWeight  android:id="@+id/sw"..................../>

ShowWeight类中有两个公共变量,它们的变化值需要在main活动中捕获,该活动使用main.xml作为其视图。

我该怎么做呢? 我在主要活动中尝试过这个:

ShowWeight sw=(ShowWeight)this.findViewById(R.id.sw);
Log.d("test",sw.getContentDescription().toString());

这在showWeight类中:

this.setContentDescription(/*required value */);

这导致了NullPointerException

将不胜感激一些建议(数据库,静态变量,不是一个选项)

更新:

不幸的是,我不允许发布任何代码,如果我含糊其ShowWeight ,我深表歉意,不过,我确定ShowWeight类没有改变任何可能导致问题的内容。

我已经通过XML标记添加到main.xml视图中的ShowWeight类看起来很好并且可以正常运行。

当我使用ShowWeight sw=(ShowWeight)this.findViewById(R.id.sw); 在主要活动中,然后举杯或打印ShowWeight,我得到'null'。 setContentDescription(),getContentDescription()也不应抛出错误,因为我在ShowWeight的XML标签中提供了默认的contentDescription。

发布您的ShowWeight类将为我们提供更多帮助。 假设您有这样的课程。

public class ShowWeight extends LinearLayout {

    private Object myObject; 
    public ShowWeight(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        LayoutInflater.from(context).inflate(R.layout.header, this);
    }
    public Object getMyObject()
    {
        return myObject;
    }    
}

在你的MainActivity.java中

ShowWeight sw=(ShowWeight)this.findViewById(R.id.sw);
sw.getMyObject();

暂无
暂无

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

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