为什么在片段上按下按钮时TextView中的文本不会更新?

时间:2015-01-18 08:40:10

标签: android button android-fragments textview

我使用选项卡式活动创建了我的应用。我创建了一些片段和简单的UI。滑动和标签工作。我想制作一个非常简单的类似计算器的应用程序,但我甚至无法更改文本 我在互联网上尝试了很多解决方案,但没有任何效果。我是Android开发的初学者,现在我的代码真是一团糟。 有什么改变让它起作用?我只想在点击计算按钮后更改一些TextView的文本。

SingleLeg.java

package com.mycompany.hoptestcalculator;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
//import android.text.Editable;
//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.ImageButton;
//import android.widget.ImageView;
import android.widget.TextView;
import android.view.View.OnClickListener;




/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link SingleLeg.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link SingleLeg#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SingleLeg 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;

/**
 * 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 SingleLeg.
 */
// TODO: Rename and change types and number of parameters
public static SingleLeg newInstance(String param1, String param2) {
    SingleLeg fragment = new SingleLeg();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

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







@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }



//        ImageButton calculate = (ImageButton)      getView().findViewById(R.id.calculate);
//
//
//        calculate.setOnClickListener(this);

}

//    @Override
//    public void onClick(View v) {
//        int id = v.getId();
//
//
//        left1 = (EditText) getView().findViewById(R.id.LeftTr1);
//        right1 = (EditText) getView().findViewById(R.id.RightTr1);
//        left2 = (EditText) getView().findViewById(R.id.LeftTr2);
//        right2 = (EditText) getView().findViewById(R.id.RightTr2);
//
//        if(id == R.id.calculate && (!left1.getText().equals("")) ) {
//            avgL.setText("2");
//    }

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    //return inflater.inflate(R.layout.fragment_single_leg, container, false);

    View v = inflater.inflate(R.layout.fragment_single_leg,
            container, false);

    Button calculate = (Button) getView().findViewById(R.id.calculate);
    final TextView textView = (TextView) getView().findViewById(R.id.avgLeft);

    calculate.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
           textView.setText("abc");



        }
    });
    return v;
}
//
//    EditText left1 = (EditText) getView().findViewById(R.id.LeftTr1);
//    EditText right1 = (EditText) getView().findViewById(R.id.RightTr1);
//    EditText left2 = (EditText) getView().findViewById(R.id.LeftTr2);
//    EditText right2 = (EditText) getView().findViewById(R.id.RightTr2);
//    TextView avgL; //= (TextView) getView().findViewById(R.id.avgLeft);
//    TextView avgR = (TextView) getView().findViewById(R.id.avgRight);
//    TextView leftOfRight = (TextView) getView().findViewById(R.id.Left_Right);
//    TextView rightOfLeft = (TextView) getView().findViewById(R.id.Right_Left);

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
    if (mListener != null) {
        mListener.onFragmentInteraction(uri);
    }
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnFragmentInteractionListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.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
    public void onFragmentInteraction(Uri uri);
}


//    //Declaration
//    private class GenericTextWatcher implements TextWatcher{
//
//        private View view;
//        private GenericTextWatcher(View view) {
//            this.view = view;
//        }
//
//        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
//        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
//
//        public void afterTextChanged(Editable editable) {
//            String text = editable.toString();
//            switch(view.getId()){
//                case R.id.LeftTr1:
//                    text.setName(text);
//                    break;
//                case R.id.RightTr1:
//                    model.setEmail(text);
//                    break;
//                case R.id.LeftTr2:
//                    model.setPhone(text);
//                    break;
//            }
//        }
//    }



//    left1.addTextChangedListener(new TextWatcher() {
//        @Override
//        public void afterTextChanged(Editable arg0) {
//            enableSubmitIfReady();
//        }
//
//        @Override
//        public void beforeTextChanged(CharSequence s, int start, int  count, int after) {
//        }
//
//        @Override
//        public void onTextChanged(CharSequence s, int start, int before, int count) {
//        }
//    });

public void updateTextView(String toThis) {

    TextView avg = (TextView) getView().findViewById(R.id.avgLeft);
    avg.setText("567");
    return;
}
}

fragment_single_leg.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context="com.mycompany.hoptestcalculator.SingleLeg"
android:id="@+id/container"
>

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    >

    <View
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="50dp"/>

    <TextView
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/left_leg"
        android:id="@+id/textView"
        android:background="@drawable/back"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="5dp"
        android:paddingBottom="5dp" />

    <View
        android:layout_weight="0.05"
        android:layout_width="0dp"
        android:layout_height="50dp"/>

    <TextView
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/right_leg"
        android:id="@+id/textView2"
        android:background="@drawable/back"
        android:paddingLeft="10dp"
        android:paddingTop="5dp"
        android:paddingBottom="5dp"
        android:paddingRight="10dp" />
</LinearLayout>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/trial_1"
        android:id="@+id/trial1" />

    <EditText
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:id="@+id/LeftTr1"
        android:layout_gravity="center_horizontal" />

    <View
        android:layout_weight="0.05"
        android:layout_width="0dp"
        android:layout_height="50dp"/>

    <EditText
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:id="@+id/RightTr1"
        android:layout_gravity="center_horizontal" />

</LinearLayout>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/trial_2"
        android:id="@+id/trial2" />

    <EditText
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:id="@+id/LeftTr2"
        android:layout_gravity="center_horizontal" />

    <View
        android:layout_weight="0.05"
        android:layout_width="0dp"
        android:layout_height="50dp"/>

    <EditText
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:id="@+id/RightTr2"
        android:layout_gravity="center_horizontal" />

</LinearLayout>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/average"
        android:id="@+id/avg" />

    <TextView
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:id="@+id/avgLeft"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:background="@drawable/bg_avg"
        android:text="rgrrgrgrg"
        android:enabled="true"
        android:editable="false" />

    <View
        android:layout_weight="0.05"
        android:layout_width="0dp"
        android:layout_height="50dp"/>

    <TextView
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:id="@+id/avgRight"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:background="@drawable/bg_avg" />

</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="50dp"></LinearLayout>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/left_of_right"
        android:id="@+id/lofR"
        android:layout_gravity="center_vertical"/>

    <TextView
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:id="@+id/Left_Right"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:background="@drawable/bg_avg" />



</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="10dp"></LinearLayout>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/right_of_left"
        android:id="@+id/RofL"
        android:layout_gravity="center_vertical"/>

    <TextView
        android:layout_weight="1"
        android:layout_width="0dp"
        android:layout_height="50dp"
        android:id="@+id/Right_Left"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:background="@drawable/bg_avg" />



</LinearLayout>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Calculate"
    android:id="@+id/calculate"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="50dp"
    android:textSize="35dp" />

的AndroidManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mycompany.hoptestcalculator" >
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

        </activity>

    </application>

</manifest>

1 个答案:

答案 0 :(得分:0)

片段的onCreateView()内部:

Button calculate = (Button) convertView.findViewById(R.id.calculate);
final TextView textView = (TextView) convertView.findViewById(R.id.textViewId);

然后在按钮上设置单击侦听器。 :

    calculate.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            textView.setText("Here goes sample text");
        }
    });