0

我在关注这个教程:实现 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;
}
}

有没有办法添加布局而不是在选项卡中写入字符串?

4

1 回答 1

0

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

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->layout 文件夹中创建的 xml 布局

于 2013-10-18T08:58:57.077 回答