这是我的java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_starting_point);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
counter = 0;
add = (Button) findViewById(R.id.add_butt);
sub = (Button) findViewById(R.id.sub_butt);
display = (TextView) findViewById(R.id.tv_text);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
counter++;
display.setText("Your Total is " + counter);
}
});
这是我的xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.myfirstapp.StartingPoint$PlaceholderFragment" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your Total is 0"
android:textSize="40sp"
android:layout_gravity="center"
android:id="@+id/tv_text" />
<Button
android:layout_width="250dp"
android:layout_height="wrap_content"
android:text="Add 1"
android:layout_gravity="center"
android:id="@+id/add_butt" />
<Button
android:layout_width="250dp"
android:layout_height="wrap_content"
android:text="Sub 1"
android:layout_gravity="center"
android:id="@+id/sub_butt" />
</LinearLayout>
当我尝试添加侦听器时,我收到NullPointerExeption错误,因为findViewById
方法在所有视图上都返回null ...我认为一切都已到位。所有的观点都在XML中,并且它们具有正确的ID,所以我做错了什么?
答案 0 :(得分:3)
您正在尝试findViewById
中的Fragment
个观看次数。
尝试将此代码移至PlaceholderFragment
班级(OnCreateView
)