簡體   English   中英

如何根據 activity_main 中編輯文本中的文本更改片段中的 imageview 圖像

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

我的 activity_main.xml 中有一個文本框,我想根據文本框中的文本更改片段中包含的 imageview 的內容。

我嘗試從字段中讀取文本(ChangeFragment 函數)並將其解析為 ChangeImage function,它具有一些 if 函數,可以根據解析的文本更改 imageview 的內容。

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();
        }

    }
}

片段二.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);
            }
    }
}

任何幫助將非常感激。

謝謝

您可以創建一個 static function 返回您正在查找的資源的 ID,遵循android 文檔中的內容

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

並且,要獲取資源在Fragment中的引用ID,可以調用function如下

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

用你的例子:

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
    }
}

記得在運行時處理異常

在決定使用此方法之前閱讀文檔,那里有以下注釋:不鼓勵使用此 function。 按標識符檢索資源比按名稱檢索資源效率高得多。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM