1.Activity
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FragmentTransaction far=getSupportFragmentManager().beginTransaction(); Farment fa=new Farment(); far.add(R.id.far,fa,Farment.class.getName()); far.commit(); setView(); } private void setView() { final Button button= (Button) findViewById(R.id.button01); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Button a= (Button) getSupportFragmentManager().findFragmentById(R.id.far).getView().findViewById(R.id.button); a.setText("789"); } }); }
2.碎片
public class Farment extends Fragment { View view; Button button; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.far_main, null); setview(view); return view; } public void setview(View view) { this.view = view; button = (Button) view.findViewById(R.id.button); button.setText("hahah"); }