【问题标题】:Android Fragments - Edit Text Of Another FragmentAndroid Fragments - 编辑另一个 Fragment 的文本
【发布时间】:2018-01-27 18:02:43
【问题描述】:

所以我制作了一个简单的加热文本控制应用程序,它都可以使用权限和所有这些,但它使用 2 个片段,其中有两个文本框,我希望在其中包含相同的文本——电话号码。我无法让 rel1 更改 rel2 中的编辑文本。

第 1 版:

package com.danielkern.relswitcher;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.telephony.SmsManager;

import static android.content.SharedPreferences.*;

/**
 * Created by Daniel Kern on 03/01/2018.
 */

public class Rel1 extends Fragment{
    Button BtnHOFF, BtnHON, BtnHST, saveB;
    EditText txtPhoneNo;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.rel1, container, false);
        final View view2 = inflater.inflate(R.layout.rel2, container, false);
        final SharedPreferences sharedPref = this.getActivity().getSharedPreferences("settings", Context.MODE_PRIVATE);
        String savedNo = sharedPref.getString("phoneNo", "07599070551");
        BtnHOFF = (Button) view.findViewById(R.id.Hoff);
        BtnHON = (Button) view.findViewById(R.id.Hon);
        BtnHST = (Button) view.findViewById(R.id.Hstatus);
        txtPhoneNo = (EditText) view.findViewById(R.id.editText);
        saveB = (Button) view.findViewById(R.id.saveB);
        ((EditText) view.findViewById(R.id.editText)).setText(savedNo);
        Toast.makeText(getActivity().getApplicationContext(), savedNo, Toast.LENGTH_LONG).show();
        BtnHOFF.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                sendMsg("#REL1=ON", txtPhoneNo.getText().toString());
            }
        });
        BtnHON.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                sendMsg("#REL1=OFF", txtPhoneNo.getText().toString());
                Log.i(getActivity().toString(), "Done!");
            }
        });
        BtnHST.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                sendMsg("#STATUS", txtPhoneNo.getText().toString());
            }
        });
        saveB.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                sharedPref.edit().putString("phoneNo", txtPhoneNo.getText().toString());
                Log.i("me", "Saved!");
                Toast.makeText(getActivity().getApplicationContext(),
                        "Saved!",
                        Toast.LENGTH_LONG).show();
                ((EditText) view2.findViewById(R.id.editText)).setText(txtPhoneNo.getText().toString());
            }
        });
        return view;
    }
    public void sendMsg(String msg, String num){
        try {
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(num, null, msg, null, null);
            Toast.makeText(getActivity().getApplicationContext(), "SMS Sent!",
                    Toast.LENGTH_LONG).show();
            } catch (Exception e) {
            Toast.makeText(getActivity().getApplicationContext(),
                    "SMS failed, contact administrator!",
                    Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

}

第 2 版:

package com.danielkern.relswitcher;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Created by Daniel Kern on 03/01/2018.
 */

public class Rel2 extends Fragment {
    Button BtnWOFF, BtnWON, BtnWST, saveB;
    EditText txtPhoneNo;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.rel2, container, false);
        final View view1 = inflater.inflate(R.layout.rel1, container, false);
        final SharedPreferences sharedPref = this.getActivity().getSharedPreferences("settings", Context.MODE_PRIVATE);
        String savedNo = sharedPref.getString("phoneNo", "07599070551");
        BtnWOFF = (Button) view.findViewById(R.id.Woff);
        BtnWON = (Button) view.findViewById(R.id.Won);
        BtnWST = (Button) view.findViewById(R.id.Wstatus);
        saveB = (Button) view.findViewById(R.id.saveB);
        txtPhoneNo = (EditText) view.findViewById(R.id.editText);
        ((EditText) view.findViewById(R.id.editText)).setText(savedNo);
        Toast.makeText(getActivity().getApplicationContext(), savedNo, Toast.LENGTH_LONG).show();
        BtnWOFF.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                sendMsg("#REL2=ON", txtPhoneNo.getText().toString());
            }
        });
        BtnWON.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                sendMsg("#REL2=OFF", txtPhoneNo.getText().toString());
            }
        });
        BtnWST.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                sendMsg("#STATUS", txtPhoneNo.getText().toString());
            }
        });
        saveB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sharedPref.edit().putString("phoneNo", txtPhoneNo.getText().toString());
                ((EditText) view1.findViewById(R.id.editText)).setText(txtPhoneNo.getText().toString());
                Log.d("me", "Saved!");
            }
        });
        return view;
    }
    public void sendMsg(String msg, String num){
        try {
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(num, null, msg, null, null);
            Toast.makeText(getActivity().getApplicationContext(), "SMS Sent!",
                    Toast.LENGTH_LONG).show();
            } catch (Exception e) {
            Toast.makeText(getActivity().getApplicationContext(),
                    "SMS failed, contact administrator!",
                    Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }
}

第 1 版 xml:

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

    <Button
        android:id="@+id/Hon"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="44dp"
        android:text="Heating ON (REL1 OFF)"
        android:textSize="18sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/Hoff"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/Hon"
        android:layout_marginTop="13dp"
        android:text="Heating OFF (REL1 ON)"
        android:textSize="18sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/Hstatus"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/Hoff"
        android:layout_marginTop="15dp"
        android:text="STATUS"
        android:textSize="18sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/texts"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="46dp"
        android:text="Coming Soon!"
        android:textSize="24sp" />

    <EditText
        android:id="@+id/editText"
        android:text="07599070551"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:inputType="phone" />

    <Button
        android:id="@+id/saveB"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:layout_alignBaseline="@+id/editText"
        android:layout_alignBottom="@+id/editText"
        android:layout_alignParentEnd="true"
        android:text="Save" />

</RelativeLayout>

第 2 版 XML:

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

    <Button
        android:id="@+id/Won"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="44dp"
        android:text="Water ON (REL2 OFF)"
        android:textSize="18sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/Woff"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/Won"
        android:layout_marginTop="13dp"
        android:text="Water OFF (Rel2 On)"
        android:textSize="18sp"
        android:textStyle="bold" />

    <Button
        android:id="@+id/Wstatus"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/Woff"
        android:layout_marginTop="15dp"
        android:text="STATUS"
        android:textSize="18sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/texts"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="46dp"
        android:text="Coming Soon!"
        android:textSize="24sp" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:ems="10"
        android:inputType="phone" />

    <Button
        android:id="@+id/saveB"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:layout_alignBaseline="@+id/editText"
        android:layout_alignBottom="@+id/editText"
        android:layout_alignParentEnd="true"
        android:text="Save" />

</RelativeLayout>

编辑: 我希望当我在 rel1 中按保存时更改 Rel2 中的编辑文本,因此电话号码框将始终相同。 rel1

编辑 2: 我已经修复了共享首选项问题,但我仍然想知道是否有人可以使文本框与文本更新或保存按钮按下时的文本框相同。

【问题讨论】:

  • 请详细解释一下您要做什么...您希望 Rel2 中的 EditText 在您输入 Rel1 中的 EditText 时立即更新?
  • Fragments是否同时加载到Activity中?
  • 我希望 Rel2 中的 EditText 在我按下保存按钮时发生变化
  • @SaranSankaran 抱歉,我该如何检查?

标签: java android xml android-layout android-fragments


【解决方案1】:

有两种方法可以做到这一点。

  1. 使用界面

使用类似TextChangeListener 的方法创建一个接口并声明一个方法onTextChange(String text)。

interface TextChangeListener{
    void onTextChange(String number);
}

在HostActivity中实现接口

class HostActivity extends Activity implements TextChangeListener{
   ...
   void onTextChange(String number){
       secondFragment.updateNumber(number)
   }
   ...
}

在 FirstFragment 中使用 TextWatcher 的 afterTextChanged() 侦听器中实现的接口调用活动

class FirstFragment extends Fragment{
    private TextChangeListener activity;

    @Override
    public onAttach(Context context){
         if(context instanceof TextChangeListener){
              activity = (TextChangeListener) context;
         }
    }

    phNumEditText.addTextChangedListener(new TextWatcher() {

        @Override           
        public void afterTextChanged(Editable s) {
            activity.onTextChange(s.toString);
        }
        ...
    );

...
}

在 SecondFragment 中收到来自 Activity 的调用时,使用新数据更新 EditText。

class SecondFragment extends Fragment{
    ...
    public void updateNumber(String number){
        editText.setText(number);
    }
}
  1. 使用EventBus

使用EventBus 发布来自FirstFragment 的事件。该事件将包含要填充到SecondFragment 中的数据。 SecondFragment 将订阅该事件,并在收到事件后将数据填充到 EditText。

【讨论】:

  • 我也推荐使用接口。我仍然不能 100% 确定 OP 试图完成什么。
  • 界面答案看起来但是我该怎么做呢?
猜你喜欢
  • 2020-06-22
  • 2016-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-28
  • 1970-01-01
  • 1970-01-01
  • 2019-01-10
相关资源
最近更新 更多