[英]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.