如何根据activity_main中EditText中的文本更改片段中的ImageView图像。

huangapple go评论82阅读模式
英文:

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

问题

以下是翻译后的内容:

EditDataActivity.java

package com.example.attempttwo;

import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
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);

        Intent receivedIntent = getIntent();

        selectedID = receivedIntent.getIntExtra("id", -1);

        selectedName = receivedIntent.getStringExtra("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;
        edit_name = editable_item.getText().toString();
        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;

public class FragmentTwo extends Fragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private String mParam1;
    private String mParam2;

    ViewGroup rootView;
    ImageView imgView;

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

    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);
        return rootView;
    }

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

如有需要,还请随时提问。

英文:

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

答案1

得分: 0

你可以创建一个静态函数,根据安卓文档中的内容,返回你要查找的资源的ID:

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("获取资源ID失败:" + name, e);
    }
}

此外,在 Fragment 中获取资源的引用ID,你可以按照以下方式调用该函数:

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

结合你的示例:

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

在运行时记得处理异常。

在决定使用该方法之前,请阅读文档,文档中有以下注意事项:
不建议使用此函数。通过标识符而不是名称检索资源要更加高效。

英文:

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.

huangapple
  • 本文由 发表于 2020年10月8日 16:12:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/64258408.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定