【发布时间】:2017-07-15 10:15:05
【问题描述】:
我是编码初学者,希望得到一些帮助。我想做一个报警应用程序。在我的主页片段上,我添加了一个按钮,该按钮将向 ScrollView 内的 LinearLayout 添加警报。警报中将包含三个 TextView,以及一个用于激活/停用的按钮。
这是我希望闹钟的样子(目前在我的编码中没有使用它;我创建它只是为了对我的目标有一个直观的帮助):
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:id="@+id/alarm_fl"
android:background="@mipmap/white_box">
<Button
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="9.5dp"
android:id="@+id/alarm_activation_button"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="70dp"
android:layout_marginTop="5dp"
android:textSize="10pt"
android:id="@+id/alarm_time"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="165dp"
android:layout_marginTop="11.5dp"
android:textSize="7pt"
android:id="@+id/alarm_ampm"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="70dp"
android:layout_marginTop="30dp"
android:textSize="5pt"
android:id="@+id/alarm_day"/>
</FrameLayout>
这就是我目前在片段中测试我的警报的方式:
addAlarm.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
LayoutInflater alarm_inflater = (LayoutInflater) getContext().getSystemService(LAYOUT_INFLATER_SERVICE);
ViewGroup parent = (ViewGroup) getActivity().findViewById(R.id.alarm_ll);
View alarm_view = alarm_inflater.inflate(R.layout.alarm_layout, parent);
TextView alarm_time = (TextView) alarm_view.findViewById(R.id.alarm_time);
alarm_time.setText("9시 45분");
TextView alarm_ampm = (TextView) alarm_view.findViewById(R.id.alarm_ampm);
alarm_ampm.setText("오후");
TextView alarm_day = (TextView) alarm_view.findViewById(R.id.alarm_day);
alarm_day.setText("월,화,수,목,금");
Button activation_button = (Button) alarm_view.findViewById(R.id.alarm_activation_button);
activation_button.setBackgroundResource(R.mipmap.checkbox_deactivated);
}
});
其中 alarm_ll 是我想用新创建的警报填充的 LinearLayout。
在我看来,我需要每个 Button 和 TextView 的唯一 ID 来分别操作它们。
现在是我的问题:
如果我想在单击按钮时以编程方式添加视图,这是正确的方法吗?还是有更好、更简单的方法?
我的警报最终需要成为对象。像 User 这样的非活动类,或者在这种情况下是 Alarm,是否有可能拥有自己的布局?
如何在通过按钮单击创建时为每个视图赋予唯一的 ID?
当我现在测试运行我的应用程序时,我添加到alarm_ll 中的布局不会被保存,所以如果我切换到另一个活动并返回,alarm_ll 将被重置。当它们不是原始数据类型时,如何将它们保存在片段中?
很抱歉一次问这么多问题,但我真的很想得到一些答案或建议。谢谢。
【问题讨论】:
-
为每个视图分配 ID 的目的是什么?此 ID 将用于什么用途?
标签: android android-layout android-fragments android-custom-view