-1

我正在尝试制作一个按钮,计算点击次数并将它们显示在文本视图中。尝试了我所知道的一切。XML:

       <LinearLayout
        android:id="@+id/gpulay"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="20dp" >
        <TextView
            android:id="@+id/master_control_text_gpulay"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:text="Master Control :"
            android:textAppearance="?android:attr/textAppearanceMedium" />
        <Button
            android:id="@+id/plus_gpulay"
            android:layout_width="35dp"
            android:layout_height="35dip"/>
    </LinearLayout>

这是我的代码:

public class Main extends Fragment { 

    int c=0;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (container == null) {
            return null;
        }

        ListView GPU_LAYOUT = (ListView)inflater.inflate(R.layout.gpu, container, false);

        TextView text = (TextView) GPU_LAYOUT.findViewById(R.id.text1);
        Button plus = (Button) GPU_LAYOUT.findViewById(R.id.butt1);

        plus.setOnClickListener(new OnClickListener() {     //null pointer this line, but it's from .srtText i think
            public void onClick(View v) {
                c++;
                text.setText(c);
            }
        });

    }

    return GPU_LAYOUT;
}

当我打开它时应用程序强制关闭,所以我什至看不到主布局。

4

3 回答 3

3

来自NPE这里

text.setText(c);

你使用了错误的setText()方法。当您将 anint放在那里时,它会查找 a resourcewith that id。你需要给它一个String. 您可以通过多种方式做到这一点。一种方法是将其更改为

text.setText("" + c);

你也可以做

text.setText(String.valueOf(c));

TextView Docs注意到不同的方法。

于 2013-09-19T21:40:02.917 回答
2

在 Activity 中工作时在 onCreateView 中创建应用程序是错误的。

您仍然可以在 onCreate 方法中完成所有这些操作。

我的猜测是 GPU_Layout 为空或不包含您的按钮。这就是为什么按钮(加号)为 Null 并且在其上调用 setOnClickListener 会引发 NullPointerException。

如果您能解释错误发生的时间、膨胀/构建活动期间或实际按下按钮期间,这也会有所帮助

于 2013-09-19T21:38:17.497 回答
0

1)您需要从 Fragment 而不是 Activity 扩展您的类。然后你的方法onCreateView就会奏效。然后将此片段设置为您的 Activity 的 contentView。

2)您不能将 int 设置为 textView 或任何其他小部件的文本。您需要先使用将其转换为字符串String.valueOf(count);

于 2013-09-19T21:55:01.767 回答