简体   繁体   English

如何使用主活动中的按钮将随机 colors 添加到主活动的片段布局

[英]How to add random colors to fragment layout from main activity with button in main activity

I want to add random colors to fragment layout with the button on main activity.我想使用主要活动上的按钮将随机 colors 添加到片段布局中。 When I click on a button that is in main activity the color of fragment layout must be changed.当我单击主要活动中的按钮时,必须更改片段布局的颜色。

I tried with bundle, but it is not working.我尝试使用捆绑包,但它不起作用。

btn1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
       Bundle bundle=new Bundle();
       bundle.putInt("key",getRandomColor());
       fragmentOne.setArguments(bundle);
     }
});

public int getRandomColor(){
    Random rnd = new Random();
    return Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
}

as you said:如你所说:

btn1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            Bundle bundle=new Bundle();
            bundle.putInt("color",getRandomColor());
            fragmentOne.setArguments(bundle);

        }
    });

and in your fragment class:在您的片段 class 中:

 @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.item_1, container, false);

        RelativeLayout relativeLayout = view.findViewById(R.id.relative_frag);
        int color = getArguments().getInt("color");
        relativeLayout.setBackgroundColor(color);


        return view;
    }

and fragment layout:和片段布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:id="@+id/relative_frag"
    android:layout_height="match_parent">


    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_centerVertical="true"
        android:text="Text"/>


</RelativeLayout>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM