标签:
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