我试图在onClick函数上处理3个ImageButtons。但我的应用程序崩溃了,这就是我在logcat上得到的东西:
03-17 21:30:25.372: E/AndroidRuntime(17838): at me.hicham.resume.HomeFragment.onCreate(HomeFragment.java:32)
它指向我设置我的ImageButton的行:
ImageButton fb_button = (ImageButton) getView().findViewById(R.id.button_facebook);
我不知道可能导致此问题的原因(logcat错误不够明确)。
这是我的班级:
package me.hicham.resume;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
import me.hicham.resume.R;
public class HomeFragment extends Fragment implements OnClickListener {
public HomeFragment(){}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
ImageButton fb_button = (ImageButton) getView().findViewById(R.id.button_facebook);
fb_button.setOnClickListener(this);
ImageButton tw_button = (ImageButton) getView().findViewById(R.id.button_twitter);
tw_button.setOnClickListener(this);
ImageButton ln_button = (ImageButton) getView().findViewById(R.id.button_linkedin);
ln_button.setOnClickListener(this);
return rootView;
}
public void onViewCreated (View view, Bundle savedInstanceState){
/*cool stuff in here*/
}
@Override
public void onClick(View v) {
Intent socialintent;
if (v.getId()== R.id.button_facebook){
socialintent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://"));
this.startActivity(socialintent);
}
else if (v.getId()== R.id.button_twitter){
socialintent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://"));
this.startActivity(socialintent);
}
else if (v.getId()== R.id.button_linkedin){
socialintent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://"));
this.startActivity(socialintent);
}
}
}
感谢帮助人员:)
答案 0 :(得分:1)
您应该在findViewById
上进行所有rootView
来电。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
ImageButton fb_button = (ImageButton) rootView.findViewById(R.id.button_facebook);
fb_button.setOnClickListener(this);
ImageButton tw_button = (ImageButton) rootView.findViewById(R.id.button_twitter);
tw_button.setOnClickListener(this);
ImageButton ln_button = (ImageButton) rootView.findViewById(R.id.button_linkedin);
ln_button.setOnClickListener(this);
return rootView;
}