android编程4.2.3 4.2.4
修改mainactivity.java文件package com.example.xinwei.fragmentactivity;import android.app.Activity;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.button);
button.setOnClickListener(this);
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
replaceFragment(new RightFragment());
}
private void replaceFragment(Fragment fragment) {
FragmentManager fragmentManager=getSupportFragmentManager();
FragmentTransaction transition=fragmentManager.beginTransaction();
transition.addToBackStack(null);//按back键可以返回
transition.replace(R.id.right_layout,fragment);
transition.commit();
}
@Override
public void onClick(View view) {
switch(view.getId()){
case R.id.button:
replaceFragment(new AnotherRightFragment());
break;
case R.id.button1:
TextView textView=(TextView)findViewById(R.id.text_view);
if(textView!=null){
textView.setText("你好");
}
break;
}
}
}
添加的第30行是为了让程序按back键可以返回。另外碎片和活动进行通信其实不用那么费劲,直接找到控件的id就行了,效果图如下:
页:
[1]