如何在动态视图中处理控件

loading...


0

我有一个允许用户动态生成事件的活动 . 为简洁起见,该事件有2个控件,一个EditText“etText”和一个Button“pbToggle” . 用户可以在事件的正确实例中的etText字段中输入文本 . 但是,当他推送pbToggle时,onClick后面的代码将在事件的第一个实例中的Button上执行,而不是Button所在的实例 .

event.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true">

<EditText
    android:id="@+id/etText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="time"
    android:textSize="10sp"/>

<Button
    android:id="@+id/pbToggle"
    android:layout_width="35dp"
    android:layout_height="35dp"
    android:onClick="onToggle"
    android:text=">>"
    android:textSize="10sp" />

</android.support.constraint.ConstraintLayout>

activity_scedule.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/parent_linear_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:orientation="vertical"
tools:context=".ScheduleActivity">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:orientation="horizontal" >
</LinearLayout>

<Button
    android:id="@+id/pbAddEvent"
    style="@style/Widget.AppCompat.Button.Borderless"
    android:layout_width="134dp"
    android:layout_height="32dp"
    android:layout_marginStart="124dp"
    android:layout_marginLeft="124dp"
    android:layout_marginTop="26dp"
    android:onClick="onAddEvent"
    android:text="Add Event ..."
    android:textAllCaps="false"
    android:textColor="@color/colorAccent"
    android:textSize="12sp" />

</LinearLayout>

ScheduleActivity.java

package ...
import ....

public class ScheduleActivity extends AppCompatActivity {
private LinearLayout parentEventLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_schedule);
        parentEventLayout = findViewById(R.id.parent_linear_layout);
    }

    public void onAddEvent(View v) {
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View rowView = inflater.inflate(R.layout.event, null);
        // Add the new row before the add field button.
        parentEventLayout.addView(rowView, parentEventLayout.getChildCount() - 1);
    }

    public void onToggle(View v) {
        Button btn = findViewById(R.id.pbToggle);
        btn.setText((btn.getText() == ">>") ? "<<" : ">>");
    }
}

loading...

0回答

No Data

评论

暂时没有评论!