现在,在有人说任何话之前,我知道以前已经有人问过这种事情,我在这里查看了很多问题,但找不到任何有帮助的东西
在我的自定义 View 中,我试图在布局文件中找到一个始终返回 null 的 TextView 。
这是我的代码:
Main.java
public class Main extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView( R.layout.game );
}
.....
自定义 View .java
public class CustomView extends SurfaceView
{
TextView MyTextView; // <-- THIS SHOULD BE SET
public CustomView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
游戏.XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gamelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@drawable/background">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_gravity="center"
android:orientation="horizontal"
android:layout_weight="0.025">
<TextView
android:id="@+id/MyTextView" // This needs to be found
android:layout_width="0dip"
android:layout_weight="1"
android:textSize="16sp"
android:text="@string/health"
android:layout_height="fill_parent"
android:contentDescription="@string/health"/>
</LinearLayout>
<package.CustomView
....... />
</LinearLayout>
最佳答案
假设您已将布局文件中 TextView
的 id
设置为 TextView1
,您需要做的就是将其分配为这个:
MyTextView = (TextView) findViewById(R.id.TextView1);
但是您要么需要addView()
或在自定义 View 中膨胀布局。
关于java - 自定义 View 中的 TextView 出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20906789/