【发布时间】:2015-05-02 00:44:15
【问题描述】:
我知道关于这个主题还有很多其他问题,但我已经浏览了所有这些问题,但仍然没有解决问题。
我制作了这段代码用于测试:
public class MainActivity extends Activity {
RelativeLayout layout;
TextView widthtext;
TextView heighttext;
int width;
int height;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = (RelativeLayout) findViewById(R.id.rela);
widthtext = (TextView) findViewById(R.id.textView);
heighttext = (TextView) findViewById(R.id.textView2);
layout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
width = layout.getWidth();
height = layout.getHeight();
}
});
widthtext.setText(width);
heighttext.setText(height);
}
和
<RelativeLayout
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:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:id="@+id/rela">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="123"
android:id="@+id/textView"
android:layout_alignTop="@+id/textView2"
android:layout_toLeftOf="@+id/textView2"
android:layout_toStartOf="@+id/textView2"
android:layout_marginRight="50dp"
android:layout_marginEnd="50dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="123"
android:id="@+id/textView2"
android:layout_marginRight="50dp"
android:layout_marginEnd="50dp"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
经过一番麻烦后,我现在注意到宽度和高度 int 具有正确的值,但我无法让它们显示在我的 TextViews 中,获得 NullPointerExeption。
谁能做到这一点?
额外:
public class MainActivity extends Activity {
RelativeLayout layout;
TextView widthtext;
TextView heighttext;
int width;
int height;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = (RelativeLayout) findViewById(R.id.rela);
widthtext = (TextView) findViewById(R.id.textView);
heighttext = (TextView) findViewById(R.id.textView2);
layout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
width = layout.getWidth();
height = layout.getHeight();
}
});
widthtext.setText(width + "");
heighttext.setText(height + "");
}
}
【问题讨论】:
-
你确定它是 NPE 吗?尝试在将 int 传递给 setText 之前将其转换为字符串。例如
widthtext.setText("""+width);和heighttext.setText(""+height);