Фрагмент не изменит цвет фона других фрагментов - PullRequest
3 голосов
/ 16 марта 2020

У меня есть блесна, у которой есть различные варианты цвета. Я хочу, чтобы верхняя половина включала только спиннер, а нижняя половина меняла цвет фона на цвет, выбранный из счетчика. Пример: синий выбран из прядильщика Нижняя половина дисплея: синий цвет в качестве фона и отображение текста синего цвета

Я создал пакет в PaletteFragment (который включает в себя вращатель) , который использует setArguments() чтобы передать позицию, на которую нажали CanvasFragment (который должен изменить цвет фона на соответствующую позицию, которую он получает)

Не удается понять, почему он не меняет цвет фона нижних макетов, потому что я не ошибки в Logcat, даже когда я выбираю цвет из счетчика.

PaletteFragment:

package edu.temple.coloractivity;


import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import java.util.Locale;


/**
 * A simple {@link Fragment} subclass.
 * Use the {@link PaletteFragment #newInstance} factory method to
 * create an instance of this fragment.
 */
public class PaletteFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    public static PaletteFragment newIntance(){
        return new PaletteFragment();
    }
    public PaletteFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment PaletteFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static PaletteFragment newInstance(String param1, String param2) {
        PaletteFragment fragment = new PaletteFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_palette, container, false);
        Spinner spinner = (Spinner) view.findViewById(R.id.spinner);
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
                getActivity(), R.array.myColors, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(
                android.R.layout.simple_spinner_dropdown_item);
        ArrayAdapter<CharSequence> stringNames = ArrayAdapter.createFromResource(getActivity(), R.array.myStrings, android.R.layout.simple_spinner_item);
        stringNames.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        ArrayAdapter<CharSequence> stringName = ArrayAdapter.createFromResource(getActivity(),R.array.myStrings, android.R.layout.simple_spinner_item);
        stringName.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        View v = inflater.inflate(R.layout.fragment_palette,container,false);
        spinner = v.findViewById(R.id.spinner);
        spinner.setAdapter(new ColorAdapter(getActivity()));

        spinner = v.findViewById(R.id.spinner);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                ViewGroup container;
                if(position == 0){
                }
                else if(position == 1){
                    Bundle args = new Bundle();
                    args.putInt("position",position);
                    CanvasFragment newFragment = new CanvasFragment();
                    newFragment.setArguments(args);
                }else if(position == 2){
                    Bundle args = new Bundle();
                    args.putInt("position",position);
                    CanvasFragment newFragment = new CanvasFragment();
                    newFragment.setArguments(args);
                }else if(position == 3){
                    Bundle args = new Bundle();
                    args.putInt("position",position);
                    CanvasFragment newFragment = new CanvasFragment();
                    newFragment.setArguments(args);
                }else if(position == 4){
                    Bundle args = new Bundle();
                    args.putInt("position",position);
                    CanvasFragment newFragment = new CanvasFragment();
                    newFragment.setArguments(args);
                }else if(position == 5){
                    Bundle args = new Bundle();
                    args.putInt("position",position);
                    CanvasFragment newFragment = new CanvasFragment();
                    newFragment.setArguments(args);
                }else if(position == 6){
                    Bundle args = new Bundle();
                    args.putInt("position",position);
                    CanvasFragment newFragment = new CanvasFragment();
                    newFragment.setArguments(args);
                }else if(position == 7){
                    Bundle args = new Bundle();
                    args.putInt("position",position);
                    CanvasFragment newFragment = new CanvasFragment();
                    newFragment.setArguments(args);
                }else if(position == 8){
                    Bundle args = new Bundle();
                    args.putInt("position",position);
                    CanvasFragment newFragment = new CanvasFragment();
                    newFragment.setArguments(args);
                }else if(position == 9){
                    Bundle args = new Bundle();
                    args.putInt("position",position);
                    CanvasFragment newFragment = new CanvasFragment();
                    newFragment.setArguments(args);
                }else if(position == 10){
                    Bundle args = new Bundle();
                    args.putInt("position",position);
                    CanvasFragment newFragment = new CanvasFragment();
                    newFragment.setArguments(args);
                }

            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        return v;
    }

}

CanvasActivity:

package edu.temple.coloractivity;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import org.w3c.dom.Text;

import java.util.Locale;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link CanvasFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link CanvasFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class CanvasFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    public CanvasFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment CanvasFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static CanvasFragment newInstance(String param1, String param2) {
        CanvasFragment fragment = new CanvasFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_canvas, container, false);
        String CurrentLang = Locale.getDefault().getLanguage();
        TextView text = (TextView) view.findViewById(R.id.newColor);
        Fragment fragment = (Fragment) getFragmentManager().findFragmentById(R.id.secondLayout);
        final View newBackground;
        fragment.getView().setBackgroundResource(R.color.white);
        System.out.println(Locale.getDefault().getLanguage());
        Bundle b = getArguments();
        int pos = b.getInt("position");
        if(pos == 1){
            fragment.getView().setBackgroundResource(R.color.silver);
            if(CurrentLang=="es"){
                displayColorName(pos,text);
            }else{
                displayColorName(pos,text);
            }
        }else if(pos == 2){
            fragment.getView().setBackgroundResource(R.color.pink);
            if(CurrentLang=="es"){
                displayColorName(pos,text);
            }else{
                displayColorName(pos,text);
            }
        }else if(pos == 3){
            fragment.getView().setBackgroundResource(R.color.red);
            if(CurrentLang=="es"){
                displayColorName(pos,text);
            }else{
                displayColorName(pos,text);
            }
        }else if(pos == 4){
            fragment.getView().setBackgroundResource(R.color.orange);
            if(CurrentLang=="es"){
                displayColorName(pos,text);
            }else{
                displayColorName(pos,text);
            }
        }else if(pos == 5){
            fragment.getView().setBackgroundResource(R.color.yellow);
            if(CurrentLang=="es"){
                displayColorName(pos,text);
            }else{
                displayColorName(pos,text);
            }
        }else if(pos == 6){
            fragment.getView().setBackgroundResource(R.color.green);
            if(CurrentLang=="es"){
                displayColorName(pos,text);
            }else{
                displayColorName(pos,text);
            }
        }else if(pos == 7){
            fragment.getView().setBackgroundResource(R.color.blue);
            if(CurrentLang=="es"){
                displayColorName(pos,text);
            }else{
                displayColorName(pos,text);
            }
        }else if(pos == 8){
            fragment.getView().setBackgroundResource(R.color.indigo);
            if(CurrentLang=="es"){
                displayColorName(pos,text);
            }else{
                displayColorName(pos,text);
            }
        }else if(pos == 9){
            fragment.getView().setBackgroundResource(R.color.violet);
            if(CurrentLang=="es"){
                displayColorName(pos,text);
            }else{
                displayColorName(pos,text);
            }
        }else if(pos == 10){
            fragment.getView().setBackgroundResource(R.color.brown);
            if(CurrentLang=="es"){
                displayColorName(pos,text);
            }else{
                displayColorName(pos,text);
            }
        }
        return view;
    }
    private void displayColorName(int pos, TextView text){
        String retrieve[] = getResources().getStringArray(R.array.myStrings);
        String color = retrieve[pos];
        text.setText(color);
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

CanvasActivity:

package edu.temple.coloractivity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;

import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Locale;

public class CanvasActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_canvas);
        CanvasFragment CanvasFragment = new CanvasFragment();
        FragmentManager manager = getSupportFragmentManager();
        manager.beginTransaction().replace(R.id.secondLayout,CanvasFragment,CanvasFragment.getTag())
                .commit();
    }
}

PaletteActivity:

package edu.temple.coloractivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;

import java.util.Locale;


public class PaletteActivity extends AppCompatActivity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        PaletteFragment PaletteFragment = new PaletteFragment();
        FragmentManager manager = getSupportFragmentManager();
        manager.beginTransaction().replace(R.id.firstLayout,PaletteFragment,PaletteFragment.getTag())
                .commit();
    }
}

ColorAdapter:

package edu.temple.coloractivity;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Locale;

public class ColorAdapter extends BaseAdapter {
    ArrayList<Integer> colors;
    Context context;

    public ColorAdapter(Context context){

        this.context=context;
        colors = new ArrayList<Integer>();
        int retrieve []=context.getResources().getIntArray(R.array.myColors);
        for(int i:retrieve)
        {
            colors.add(i);
        }
    }
    @Override
    public int getCount() {
        return colors.size();
    }

    @Override
    public Object getItem(int args) {
        return colors.get(args);
    }

    @Override
    public long getItemId(int args) {
        return args;
    }

    public String getElementFromColors(int position){
        String CurrentLang = Locale.getDefault().getLanguage();
        if(CurrentLang.equals("es")){
            String retrieve[] = context.getResources().getStringArray(R.array.myStrings);
            return retrieve[position];
        }else{

            String retrieve[] = context.getResources().getStringArray(R.array.myStrings);
            return retrieve[position];
        }
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater=LayoutInflater.from(context);
        convertView=inflater.inflate(android.R.layout.simple_spinner_dropdown_item, null);
        TextView txv=(TextView)convertView.findViewById(android.R.id.text1);
        txv.setBackgroundColor(colors.get(position));
        txv.setText(getElementFromColors(position));
        return convertView;
    }

}

enter image description here

Верхняя половина включает только раскрывающийся список счетчика

После выбора цвета я хочу получить нижняя половина меняет фон этого макета на выбранный цвет

1 Ответ

1 голос
/ 16 марта 2020

Ваша проблема:

Ваш код создает CanvasFragment для каждого выбора элемента в счетчике , но ничего не делает с ним . Фрагмент должен быть добавлен к FragmentManager, чтобы быть видимым!

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                ViewGroup container;
                if(position == 0){
                }
                else if(position == 1){

                    // New fragment is created, arguments are set, and then ... nothing.
                    // That's it. It's just left hanging.
                    Bundle args = new Bundle();
                    args.putInt("position",position);
                    CanvasFragment newFragment = new CanvasFragment();
                    newFragment.setArguments(args);

             // MORE CODE LIKE THIS

Ваше решение:

Вам необходимо обновить код поэтому PaletteFragment уведомляет CanvasActivity о том, что был сделан новый выбор, и затем update текущий CanvasFragment.

У вас должно быть одна деятельность, которой принадлежат оба фрагмента. Ваша деятельность должна реализовывать интерфейс, который вызывается при выборе цвета. PaletteFragment должен получить доступ к своему Activity, привести его к типу интерфейса и вызвать метод для него, чтобы уведомить, что был сделан выбор. В Упражнении метод интерфейса должен затем обновить текущий выбранный цвет на CanvasFragment на основе заданного аргумента.

Надеюсь, это поможет!

См. Документацию для получения подробной информации о общение между фрагментами.

...