【问题标题】:Inflating fragment through a fragment and passing arguments通过片段膨胀片段并传递参数
【发布时间】:2018-01-26 15:44:15
【问题描述】:

我试图通过一个片段和传递参数来膨胀同一个片段,它的工作但传递的参数应用于前一个片段而不是新片段。

片段包含一个 TextView 和一个 Spinner。

片段类:

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

    return inflater.inflate(R.layout.myfragment,container,false);
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    Bundle b = getArguments();
    qust = b.getString("Question","");
    id = b.getInt("id");

    final connection con = (connection) getActivity();

    question = (TextView) getActivity().findViewById(R.id.question);
    spinner = (Spinner) getActivity().findViewById(R.id.spinner);

    question.setText(qust);
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),id,R.layout.support_simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            if (i!=0)
                con.inflate();
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    });

}

当用户选择前一个片段微调器中的任何项目时,我正在膨胀片段。

MainActivity 类:

    public class MainActivity extends AppCompatActivity implements connection {

    int count;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MyFragments mF = new MyFragments();
        Bundle b = new Bundle();
        b.putString("Question","Where are you?");
        b.putInt("id",R.array.planets_array);
        mF.setArguments(b);
        FragmentManager manage = getFragmentManager();
        FragmentTransaction trans = manage.beginTransaction();
        trans.add(R.id.root,mF,"frag");
        trans.commit();

    }

    @Override
    public void inflate() {

        MyFragments f = new MyFragments();
        Bundle b = new Bundle();
        b.putString("Question","what are you doing?");
        b.putInt("id",R.array.colours);
        f.setArguments(b);
        FragmentTransaction tran = getFragmentManager().beginTransaction();
        tran.add(R.id.root,f,"added");
        tran.commit();
    }
}

用于交流黑白片段的接口:

  public interface connection {

    void inflate();
}

screenshot

【问题讨论】:

    标签: android android-layout android-studio android-fragments android-view


    【解决方案1】:

    我认为这已经发生了,因为您实例化了新片段 你的 inflate() 方法没有唯一的标签。设置唯一的 TAG 或使用不同的 add(@IdRes int containerViewId, Fragment fragment) 代替。

    【讨论】:

    • 把你的任务写给我。你到底想得到什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多