如何将imageview添加到片段?

时间:2016-06-15 00:55:02

标签: android android-layout android-fragments

有很多像这样的问题,但它们都解决了在返回根布局之前在onCreateView()中添加视图的问题。我想在onClick()

中的代码执行过程中添加一个视图

请注意,这是一个片段,这就是我无法在没有onCreateView()的情况下更新用户界面的原因:

public void onClick(View v) {
    switch (v.getId()) {
        case R.id.button:

            //RelativeLayout Setup
            RelativeLayout relativeLayout = new RelativeLayout(getActivity());

            relativeLayout.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                    RelativeLayout.LayoutParams.MATCH_PARENT));

            //ImageView Setup
            ImageView imageView = new ImageView(getActivity());

            //setting image resource
            imageView.setImageResource(R.drawable.lit);

            //setting image position
            imageView.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT));

            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            params.addRule(RelativeLayout.BELOW, R.id.button);

            imageView.setLayoutParams(params);
            //adding view to layout
            relativeLayout.addView(imageView);


            break;
    }
}

这里我得到一个布局实例并进行修改。但是,我无法将此修改后的片段布局应用回应用程序UI。片段UI修改后如何更新app界面?

感谢您的时间。

2 个答案:

答案 0 :(得分:0)

我将如何做到这一点:

  1. 在我的片段视图xml中,有一个名为R.id.container的ViewGroup来保存你的ImageViews。在onCreateView中,保存对此容器的引用。
  2. 有一个单独的xml只包含ImageView。这样,您就不必进行任何编程布局。
  3. 然后在onClick或您需要添加ImageView的任何地方:

    ImageView newView = LayoutInflater.from(getActivity).inflate(R.layout.image.xml);
    mImageContainer.addView(newView);
    // Ta da!
    

答案 1 :(得分:0)

您刚刚创建了一个视图,但还没有添加到片段的布局

方法onCreateView()将返回此片段的容器,保存此实例(例如:ViewGroup container

创建视图时,如onClick()中的RelativeLayout,将其添加到容器中,您的UI将会更新。

container.addView(relativeLayout);

示例:

public class MyFragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.example_fragment, container, false);
    }

    @Override
    public void onResume() {
        super.onResume();

        // i did this to see what see how button displays
        getView().postDelayed(new Runnable() {
            @Override
            public void run() {
                // I create a new button and add it to the fragment's layout.
                Button button = new Button(getActivity());
                ((LinearLayout)getView()).addView(button);
            }
        }, 2000);
    }
}

布局example_fragment只是一个LinearLayout

相关问题