**我想点击我的片段 2 中的一个按钮,并将片段 1 替换为片段 3,如代码所示。
但是 findViewById(r.id.mybutton) 正在返回 'null' 。
我尝试调试代码,但它无法使用创建的“buttontoggle”
希望你能帮我解决上述问题提前谢谢:)
package com.vivekmishra1991.testfrag;
import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.View;
import android.view.View;
import android.widget.Button;
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(findViewById(R.id.fragment_container)!=null){
if(savedInstanceState!=null){
return;
}
//fragment 1
f1 F1= new f1();
F1.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container, F1).commit();
//fragment2(the fragment with the button)
f2 F2=new f2();
F2.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().add(R.id.fragment_container1, F2).addToBackStack(null).commit();
}
//code for buttton onclick function
Button toggleButton = (Button)findViewById(R.id.mybutton);
toggleButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{ // fragment 3 that has to be replaced with fragment 1
f3 F3=new f3();
F3.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,F3).addToBackStack(null).commit();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
编辑
这是我的activityMain.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="vertical" >
<FrameLayout
android:id="@+id/fragment_container"
android:layout_height="0dp"
android:layout_weight="6"
android:layout_width="match_parent" />
<FrameLayout
android:id="@+id/fragment_container1"
android:layout_height="0dp"
android:layout_weight="1"
android:layout_width="match_parent"/>
</LinearLayout>
f2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="Next!"
android:id="@+id/mybutton"
android:layout_gravity="left|center_vertical"/>
</LinearLayout>