我需要在活动中将RelativeLayout
块设置为VISIBLE
。但我似乎无法给RelativeLayout
分配给一个变量,像这样:android:如何使用XML中定义的id初始化/膨胀一个RelativeLayout?
Relative Layout alarmSetBlock = (RelativeLayout) findViewById(R.id.sleep_text_block);
alarmSetBlock
分配null
代替。
我想我应该使用类似inflater.inflate的东西,但不知道如何在碎片之外使用它。
请告诉我解决这个问题的最简单/最好的方法。
布局的xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp">
<Button
android:id="@+id/alarm_set_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:background="@color/mediumGray"
android:text="SET ALARM"
android:onClick="showTimePickerDialog"/>
</RelativeLayout>
<RelativeLayout
android:id="@+id/sleep_text_block"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dp"
android:visibility="gone">
<TextView
android:id="@+id/sleep_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:layout_centerHorizontal="true"
android:textSize="20sp"
android:text="Alarm set to :"/>
<TextView
android:id="@+id/alarm_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
android:layout_below="@id/sleep_text"
android:textColor="@color/colorAccent"
android:textSize="36sp" />
</RelativeLayout>
</LinearLayout>
的RelativeLayout
我想初始化是第二个布局。
这是上述布局的片段文件。我试图初始化RelativeLayout
里面的活动java文件,它包含这个片段。
public class SleepSetFragment extends Fragment {
public static SleepSetFragment newInstance()
{
SleepSetFragment fragment = new SleepSetFragment();
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_sleep_set, container, false);
}
}
您可以添加活动的XML? –
这应该工作,你使用多个布局文件夹?确保这些ID也在每个XML中设置。 –
我所有的布局都在我的res/layout文件夹中。我如何在每个XML中设置ID?如果你的意思是使用'android:id'来定义ID,我已经在这里完成了。 –