碎片到活动意图不起作用

时间:2014-07-27 07:54:12

标签: android android-intent android-activity android-fragments

所以,我正在做一个项目,我有一个名为homepg_fragment.java的片段,我正在尝试将一个imageButton链接到另一个名为MensAllShoes的活动。但它一直在崩溃。有人能帮我吗?你可以看到,我对Android编程有点新鲜。

这是我的homepg_fragment.java

package com.OP.slidingmenu.slidelist;

import com.nyp.integrateshoebox.MensAllShoes;

@SuppressLint("NewApi")
public class HOMEPG_Fragment extends Fragment {

ImageButton ladies, gentlemen;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.homepg_fragment);


    ladies = (ImageButton)findViewById(R.id.ladies1);
    gentlemen = (ImageButton)findViewById(R.id.men1);

}

public void cookie(View view) {
    Intent cookie = new Intent(getActivity(), MensAllShoes.class);
    startActivity(cookie);
}

private void setContentView(int viewallFragment) {
    // TODO Auto-generated method stub

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.homepg_fragment, container,
            false);
    return rootView;

}

private Context getApplicationContext() {
    // TODO Auto-generated method stub
    return null;
}

private ImageView findViewById(int ladies1) {
    // TODO Auto-generated method stub
    return null;
}

}

这就是XML。          

<ImageView
    android:id="@+id/welcome"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:src="@drawable/wctext" />

<ImageButton
    android:id="@+id/ladies1"
    android:layout_width="320dp"
    android:layout_height="210dp"
    android:layout_below="@+id/welcome"
    android:layout_marginBottom="18dp"
    android:layout_marginLeft="31dp"
    android:src="@drawable/ladieshome" />

<ImageButton
    android:id="@+id/men1"
    android:layout_width="320dp"
    android:layout_height="212dp"
    android:layout_below="@+id/ladies1"
    android:layout_marginBottom="18dp"
    android:layout_marginLeft="31dp"
    android:src="@drawable/menhome"
    android:onClick="cookie" />


</RelativeLayout>

2 个答案:

答案 0 :(得分:1)

为什么要为setContentViewfindViewByIdgetApplicationContext定义自己的方法?摆脱它们 - 它绝对是你不应该做的事情。

onCreate ...

中删除以下行
setContentView(R.layout.homepg_fragment);

...并在您为rootView充气的行之后将以下行移至onCreateView ...

ladies = (ImageButton)findViewById(R.id.ladies1);
gentlemen = (ImageButton)findViewById(R.id.men1);

另外,Fragment应该是自包含且可重复使用的,并且不应该直接启动Activity。相反,你应该创建一个回调&#39;由托管Activity的{​​{1}}实施的界面。然后,您调用一个接口方法告诉Fragment哪个Activity被按下,让Button启动另一个Activity

答案 1 :(得分:0)

更改你的方法

public void cookie(View view) {
     Intent cookie = new Intent(getActivity(), MensAllShoes.class);
     startActivity(cookie);
}

public void cookie(View view) {
     Intent cookie = new Intent(getActivity(), MensAllShoes.class);
     getActivity().startActivity(cookie);
}