我的布局xml有一个带有TextViews的Tablelayout用于单元格:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stretchColumns="1">
<TableRow>
<TextView
android:text="Style Details..."
android:padding="3dip" />
</TableRow>
<TableRow>
<TextView
android:text="Style"
android:padding="3dip" />
<TextView
android:id="@+id/StyleName"
android:gravity="right"
android:padding="3dip" />
</TableRow>
<TableRow>
<TextView
android:text="Price (Euro)"
android:padding="3dip" />
<TextView
android:id="@+id/StylePrice"
android:gravity="right"
android:padding="3dip" />
</TableRow>
<TableRow>
<TextView
android:text="Price for Volume <60<90 pcs"
android:padding="3dip" />
<TextView
android:id="@+id/PriceVolume6090"
android:gravity="right"
android:padding="3dip" />
</TableRow>
<TableRow>
<TextView
android:text="Price for Volume <100<250pcs"
android:padding="3dip" />
<TextView
android:id="@+id/PriceVoume100250"
android:gravity="right"
android:padding="3dip" />
</TableRow>
<TableRow>
<TextView
android:text="Price for Volume <251<500pcs"
android:padding="3dip" />
<TextView
android:id="@+id/PriceVoume251500"
android:gravity="right"
android:padding="3dip" />
</TableRow>
<TableRow>
<TextView
android:text="Price for Volume <501pcs"
android:padding="3dip" />
<TextView
android:id="@+id/PriceVolume501"
android:gravity="right"
android:padding="3dip" />
</TableRow>
</TableLayout>
我想通过我的Activity设置StyleName的值。以下是我正在使用的代码:
import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class StyleDetailsActivity extends Activity {
private TextView tvStyleName;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.styledetailsview);
String styleName = "Testing Style Name";
tvStyleName = (TextView)findViewById(R.id.StyleName);
tvStyleName.setText(styleName);
}
}
代码编译正常,应用程序启动。在运行应用程序时,我得到一个nullpointer异常。当我调试时,我看到tvStyleName为null。关于为什么它不会初始化的任何建议
答案 0 :(得分:0)
这是由于具有相同id的不同视图(android:id in xml)。在不同的布局文件中可能存在具有相同id的文本视图。
答案 1 :(得分:-1)
解决了这个问题。
更改:
<TextView
android:id="@+id/StyleName"
android:gravity="right"
android:padding="3dip" />
要:
<TextView
android:id="@id/StyleName"
android:gravity="right"
android:padding="3dip" />
在Strings.xml中为StyleName添加了一个Item