添加布局到我的标签?

时间:2013-10-18 08:54:15

标签: android layout tabs android-fragments android-viewpager

我正在关注这个turtorial:Implement Tabhost

并且不得不在我的标签上添加一些布局,并且不知道如何添加它们。 这是用于向选项卡添加一些内容的代码,但我可以添加字符串。

private List<Fragment> getFragments(){
    List<Fragment> fList = new ArrayList<Fragment>();
    // TODO (ADD LAYOUTS)

    MySampleFragment f1 = MySampleFragment.newInstance("");
    MySampleFragment f2 = MySampleFragment.newInstance("");
    MySampleFragment f3 = MySampleFragment.newInstance("24");
    fList.add(f1);
    fList.add(f2);
    fList.add(f3);

    return fList;
}

这是MySampleFragment.class

package com.example.soundboard;

  import android.os.Bundle;
  import android.support.v4.app.Fragment;
  import android.view.LayoutInflater;
  import android.view.View;
  import android.view.ViewGroup;
  import android.widget.TextView;
  import com.example.soundboard.R;

public class MySampleFragment extends Fragment {
private static View mView;

public static final MySampleFragment newInstance(String sampleText) {
    MySampleFragment f = new MySampleFragment();

    Bundle b = new Bundle();
    b.putString("bString", sampleText);
    f.setArguments(b);

    return f;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    mView = inflater.inflate(R.layout.fragment, container, false);
    String sampleText = getArguments().getString("bString");

    TextView txtSampleText = (TextView) mView.findViewById(R.id.txtViewSample);
    txtSampleText.setText(sampleText);

    return mView;
}
}

是否有人在选项卡中添加布局而不是写字符串?

1 个答案:

答案 0 :(得分:0)

您正在构造函数中传递字符串 - &gt;然后作为以下代码中的参数

MySampleFragment f1 = MySampleFragment.newInstance("");
MySampleFragment f2 = MySampleFragment.newInstance("");
MySampleFragment f3 = MySampleFragment.newInstance("24");

在你正在检索的片段中。

String sampleText = getArguments().getString("bString");

现在您可以根据字符串加载不同的布局..像这样

if(sampleText.equalsIgnoreCase("Layout1") {
    mView = inflater.inflate(R.layout.fragment, container, false); //R.layout.fragment is the layout you are loading
}
else if // some other condition 
    mView = inflater.inflate(R.layout.fragment2, container, false); //R.layout.fragment2 is the layout you are loading

R.layout.fragment等是您在项目的res-&gt;布局文件夹中创建的xml布局