鱼C论坛

 找回密码
 立即注册
查看: 2866|回复: 0

[学习笔记] android编程4.2.3 4.2.4

[复制链接]
发表于 2017-10-4 04:20:51 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
修改mainactivity.java文件
  1. package com.example.xinwei.fragmentactivity;

  2. import android.app.Activity;
  3. import android.content.Intent;
  4. import android.support.v4.app.Fragment;
  5. import android.support.v4.app.FragmentManager;
  6. import android.support.v4.app.FragmentTransaction;
  7. import android.support.v7.app.AppCompatActivity;
  8. import android.os.Bundle;
  9. import android.view.View;
  10. import android.widget.Button;
  11. import android.widget.TextView;

  12. public class MainActivity extends AppCompatActivity implements View.OnClickListener{

  13.     @Override
  14.     protected void onCreate(Bundle savedInstanceState) {
  15.         super.onCreate(savedInstanceState);
  16.         setContentView(R.layout.activity_main);
  17.         Button button = (Button)findViewById(R.id.button);
  18.         button.setOnClickListener(this);
  19.         Button button1 = (Button)findViewById(R.id.button1);
  20.         button1.setOnClickListener(this);
  21.         replaceFragment(new RightFragment());
  22.     }

  23.     private void replaceFragment(Fragment fragment) {
  24.         FragmentManager fragmentManager=getSupportFragmentManager();
  25.         FragmentTransaction transition=fragmentManager.beginTransaction();
  26.         transition.addToBackStack(null);//按back键可以返回
  27.         transition.replace(R.id.right_layout,fragment);
  28.         transition.commit();
  29.     }

  30.     @Override
  31.     public void onClick(View view) {
  32.         switch(view.getId()){
  33.             case R.id.button:
  34.                 replaceFragment(new AnotherRightFragment());
  35.                 break;
  36.             case R.id.button1:
  37.                 TextView textView=(TextView)findViewById(R.id.text_view);
  38.                 if(textView!=null){
  39.                     textView.setText("你好");
  40.                 }

  41.                 break;
  42.         }
  43.     }



  44. }
复制代码

添加的第30行是为了让程序按back键可以返回。另外碎片和活动进行通信其实不用那么费劲,直接找到控件的id就行了,效果图如下:
jdfw.gif

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-18 10:32

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表