片段交流的活动

时间:2016-12-26 05:35:07

标签: java android android-fragments

我有一个活动类和一个片段。我正在使用Intent从MainActivity.java移动到我的SimpleFragment.java但是当我点击按钮" Simple Fragment"我的应用程序崩溃而没有显示任何错误和异常。

MainActivity.java

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

public void simple(View view) {

    Intent intent = new Intent(this.getApplicationContext(),SimpleFragment.class);
    startActivity(intent);
}
}

activity_main.xml中

<Button
    android:text="Simple Fragment"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/btnSimpleFragment"
    android:onClick="simple"
    />

SimpleFragment.java

public class SimpleFragment extends Fragment {


private Button btnClickMe;

public SimpleFragment() {
    // Required empty public constructor
}


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

    View view = inflater.inflate(R.layout.fragment_simple, container, false);

    btnClickMe = (Button) view.findViewById(R.id.buttonSimpleFrag);
    btnClickMe.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getActivity(), "You clicked me.", Toast.LENGTH_SHORT).show();
        }
    });

    return view;
}
}

fragment_simple.xml

<Button
    android:text="@string/click_me"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:id="@+id/buttonSimpleFrag"/>

0 个答案:

没有答案