我的完整代码在这里给出。但没有显示活动。 添加clickListener()时显示空指针异常。
如何使用片段
访问膨胀的按钮//无法添加完整代码。显示添加更多详细信息.//
public class Activity extends Activity{
private static final String KEY_SUCCESS="success";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
FragmentManager fragmentManager=getFragmentManager();
FragmentTransaction transaction=fragmentManager.beginTransaction();
Fragment fragment=new PlaceholderFragment();
transaction.add(R.id.container,fragment);
transaction.addToBackStack("welcome");
transaction.commit();
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
Button loginButton;
private String userNameString;
private String passwordString;
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView;
rootView = inflater.inflate(R.layout.fragment_welcome, container, false);
try{
loginButton= (Button) rootView.findViewById(R.id.LoginFormButton);
}catch (NullPointerException e){
e.printStackTrace();
}
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent logIntent = new Intent(getActivity(), BearerLoggedActivity.class);
startActivity(logIntent);
}
});
return rootView;
}
}
}
答案 0 :(得分:10)
fragment.getView().findViewById(id)
应该这样做,但我通常更喜欢在Fragment中拥有所有的监听器和业务逻辑,使Activity尽可能保持最小化。一个小型演示:
public class FirstFragment extends Fragment {
Button btn;
private OnFragmentClickListener listener;
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_fragment,
container, false);
//Do stuff to the fragment view in here if you want
btn = (Button) v.findViewById(R.id.breplace);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent mainIntent = new Intent(getActivity(),
MyActivity.class);
startActivity(mainIntent);
}
});
return v;
}
希望这有帮助!
答案 1 :(得分:2)
如果我理解正确,你要找的是:
fragment.getView().findViewById(id);
答案 2 :(得分:0)
请在Fragment类中添加此内容
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.image_layout, container, false);
//ImageView imageView = (ImageView) view.findViewById(R.id.imageView1);
//imageView.setImageResource(imageResourceId);
//imageView.setBackgroundResource(imageResourceId);
Button button = (Button) view.findViewById(R.id.btn1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent mainIntent = new Intent(getActivity(),
NextActivity.class);
startActivity(mainIntent);
}
});
return view;
}
您的问题将得到解决