码迷,mamicode.com
首页 > 其他好文 > 详细

Fragemnt和TextView的交互(TextView在LinearLayout中)

时间:2016-04-07 22:15:01      阅读:307      评论:0      收藏:0      [点我收藏+]

标签:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends FragmentActivity {
private LinearLayout mlinearlayout; //装载TextView的布局
private FragmentManager mFragmentManager;
private List<Fragment> mfragmentList; //fragment的集合
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化
init();
//开启事务 将所有Fragment加入布局
mFragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = mFragmentManager.beginTransaction();
//处理事务
XinWen_Fragment xinWenFragment= new XinWen_Fragment();
mfragmentList.add(xinWenFragment);
transaction.add(R.id.fragment_layout, xinWenFragment, "XINWEN");
transaction.hide(xinWenFragment);

TuPian_Fragment tuPinFragment = new TuPin_Fragment();
mfragmentList.add(tuPinFragment);
transaction.add(R.id.fragment_layout, tuPinFragment, "TUPIN");
transaction.hide(tuPinFragment);

ShiPin_Fragment shiPinFragment = new ShiPin_Fragment();
mfragmentList.add(shiPinFragment);
transaction.add(R.id.fragment_layout, shiPinFragment, "SHIPIN");
transaction.hide(shiPinFragment);

WoDe_Fragment woDeFragment = new WoDe_Fragment();
mfragmentList.add(woDeFragment);
transaction.add(R.id.fragment_layout,woDeFragment,"WODE");
transaction.hide(woDeFragment);
//展示一个Fragment
transaction.show(xinWenFragment);
//提交事务
transaction.commit();



}
public void init(){
mlinearlayout = (LinearLayout)findViewById(R.id.main_layout);
mfragmentList = new ArrayList<Fragment>();
//设置默认选中的TextView
mlinearlayout.getChildAt(0).setSelected(true);
//外层for循环是为view添加标签
for (int i=0;i<4;i++){
TextView view = (TextView) mlinearlayout.getChildAt(i);
view.setTag(i);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int index= (int) v.getTag();
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
//内层循环是把Fragment和TextView交互起来
for(int i=0;i<4;i++){
if (i==index){
mlinearlayout.getChildAt(i).setSelected(true);
fragmentTransaction.show(mfragmentList.get(i)) ;
}else{
mlinearlayout.getChildAt(i).setSelected(false);
fragmentTransaction.hide(mfragmentList.get(i)) ;
}

}
fragmentTransaction.commit();
}
});
}
}
}

Fragemnt和TextView的交互(TextView在LinearLayout中)

标签:

原文地址:http://www.cnblogs.com/niupi/p/5365691.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!