简体   繁体   中英

How can I change the imageview image in a fragment based on the text in a edittext from my activity_main

I have a textbox in my activity_main.xml and I would like to change the content of the imageview held within a fragment based on the text in the textbox.

I have tried reading in the text from the field (ChangeFragment function) and parsing it into a ChangeImage function which has some if functions to change the content of the imageview based on the parsed in text.

EditDataActivity.java

package com.example.attempttwo;

import android.content.Intent;
import android.media.Image;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentTransaction;

import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.Fragment;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

public class EditDataActivity extends AppCompatActivity {

    private static final String TAG = "EditDataActivity";

    private Button btnSave,btnDelete, btnImage;
    private EditText editable_item;

    DatabaseHelper mDatabaseHelper;

    private String selectedName;
    private int selectedID;

    public String edit_name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_data_layout);
        btnSave = (Button) findViewById(R.id.btnSave);
        btnDelete = (Button) findViewById(R.id.btnDelete);
        btnImage = (Button) findViewById(R.id.btnViewImage);

        editable_item = (EditText) findViewById(R.id.editable_item);
        mDatabaseHelper = new DatabaseHelper(this);

        //get the intent extra from the ListDataActivity
        Intent receivedIntent = getIntent();

        //now get the itemID we passed as an extra
        selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value

        //now get the name we passed as an extra
        selectedName = receivedIntent.getStringExtra("name");

        //set the text to show the current selected name
        editable_item.setText(selectedName);

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String item = editable_item.getText().toString();
                if(!item.equals("")){
                    mDatabaseHelper.updateName(item,selectedID,selectedName);
                }else{
                    toastMessage("You must enter a name");
                }
            }
        });

        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDatabaseHelper.deleteName(selectedID,selectedName);
                editable_item.setText("");
                toastMessage("removed from database");
            }
        });
    }

    private void toastMessage(String message){
        Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
    }

    public void ChangeFragment(View view){
        Fragment fragment;
        //FragmentTwo fTwo = new FragmentTwo();
        edit_name = editable_item.getText().toString();

        //Checking the text is getting read properly
        Toast.makeText(this, edit_name, Toast.LENGTH_LONG).show();

        if( view == findViewById(R.id.btnViewImage)){
            fragment = new FragmentTwo();
            ((FragmentTwo) fragment).ChangeImage(edit_name);

            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            ft.replace(R.id.fragment_place, fragment);
            ft.commit();

        }if( view == findViewById(R.id.btnClose)){
            fragment = new FragmentImage();
            FragmentManager fm = getSupportFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
            ft.replace(R.id.fragment_place, fragment);
            ft.commit();
        }

    }
}

FragmentTwo.java

package com.example.attempttwo;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link FragmentTwo#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FragmentTwo 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;

    ViewGroup rootView;
    ImageView imgView;

    public FragmentTwo() {
        // 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 FragmentTwo.
     */
    // TODO: Rename and change types and number of parameters
    public static FragmentTwo newInstance(String param1, String param2) {
        FragmentTwo fragment = new FragmentTwo();
        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) {

        rootView = (ViewGroup) inflater.inflate(R.layout.fragment_two, container, false);
        imgView = (ImageView)rootView.findViewById(R.id.imageViewShow);
        // Inflate the layout for this fragment
        return rootView;
    }

    public void ChangeImage(String edit_name){
        if(edit_name == "Sabo"){
                ImageView img = (ImageView) rootView.findViewById(R.id.imageViewShow);
                img.setImageResource(R.drawable.sabo);
                img.setVisibility(View.VISIBLE);
            } if (edit_name == "Tsunade"){
                ImageView img = (ImageView)rootView.findViewById(R.id.imageViewShow);
                img.setImageResource(R.drawable.tsunade);
                img.setVisibility(View.VISIBLE);
            } if(edit_name == "Tanjiro"){
                ImageView img = (ImageView)rootView.findViewById(R.id.imageViewShow);
                img.setImageResource(R.drawable.tanjiro);
                img.setVisibility(View.VISIBLE);
            } if(edit_name == "Saitama"){
                ImageView img = (ImageView)rootView.findViewById(R.id.imageViewShow);
                img.setImageResource(R.drawable.saitama);
                img.setVisibility(View.VISIBLE);
            } if(edit_name == "Boruto"){
                ImageView img = (ImageView) rootView.findViewById(R.id.imageViewShow);
                img.setImageResource(R.drawable.boruto);
                img.setVisibility(View.VISIBLE);
            }
    }
}

Any help would be much appreciated.

Thanks

you can create a static function that returns the ID of the resource you are looking for following what is in the android documentation

public static int getResourceIDByName(Context context, String name, String defType, String defPackage) throws RuntimeException {
    try {
        return context.getResources().getIdentifier(name, defType, defPackage);
    } catch (Exception e) {
        throw new RuntimeException("Error to getting Resource id for "+name, e);
    }
}

and, to obtain the reference ID of the resource in Fragment, you can call the function as follows

getResourceIDByName(getActivity(), "iconName", "drawable", getActivity().getPackageName());

with your example:

public void ChangeImage(String edit_name){
    try {
        ImageView img = (ImageView) rootView.findViewById(R.id.imageViewShow);
        int resourseID = getResourceIDByName(getActivity(), edit_name, "drawable", getActivity().getPackageName());
        img.setImageResource(resourseID);
        img.setVisibility(View.VISIBLE);
    }catch (RuntimeException e){
        //TODO Handler error
    }
}

Remember to handle the exception at run time

Read the documentation before deciding to use this method, there is the following note there: use of this function is discouraged. It is much more efficient to retrieve resources by identifier than by name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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