马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
修改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就行了,效果图如下:
|