[英]Buttons don't work in android fragments
我正在开发一个应用程序,并且有以下代码:
package com.S.A.Productions.android.first;
import com.S.A.Productions.android.first.R;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class FirstActivity extends Fragment implements OnClickListener {
int counter;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
super.onCreate(savedInstanceState);
View v = inflater.inflate(R.layout.lin, container, false);
TextView temp = (TextView) v.findViewById(R.id.textView2);
//Set the buttons
Button button2 = (Button) v.findViewById(R.id.button2);
//+++ BUTTON
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub//Get content of TextView
TextView temp = (TextView) v.findViewById(R.id.textView2);
//Convert the string to an integer
counter = Integer.parseInt(temp.getText().toString());
counter++;
temp.setText("" + counter);
String stringData = temp.getText().toString();
SharedPreferences.Editor editor = someData.edit();
editor.putString("sharedString", stringData);
editor.commit();
}
});
//END OF +++ BUTTON
return v;
}
}
但是,当我运行该应用程序并单击该按钮时,该应用程序崩溃了。 我正在使用“ v.findViewById”,最后我返回了v。所以我不知道到底是什么错。 有任何想法吗?
onClick(View v)
的参数v是单击的元素(在您的情况下是button
。
错误是您通过尝试从button
本身的ID查找文本视图而将参数V(这是一个button
)用作视图组。 textView
将为null。 setText()
将导致崩溃。
您需要使用findviewbyid()
在任何的容器的textView
视图层次结构。
冲突来,因为的onclick和膨胀视图V内部视图V是不同的。 该代码将起作用:
public class FirstActivity extends Fragment implements OnClickListener {
int counter;
View v ;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
super.onCreate(savedInstanceState);
v = inflater.inflate(R.layout.lin, container, false);
TextView temp = (TextView) v.findViewById(R.id.textView2);
//Set the buttons
Button button2 = (Button) v.findViewById(R.id.button2);
//+++ BUTTON
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub//Get content of TextView
TextView temp = (TextView) this.v.findViewById(R.id.textView2);
//Convert the string to an integer
counter = Integer.parseInt(temp.getText().toString());
counter++;
temp.setText("" + counter);
String stringData = temp.getText().toString();
SharedPreferences.Editor editor = someData.edit();
editor.putString("sharedString", stringData);
editor.commit();
}
});
//END OF +++ BUTTON
return v;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.