如何在片段中使用 findViewById?
本示例演示如何在片段中使用 findViewById
步骤 1 − 在 Android Studio 中创建新项目,转到“文件 ⇒ 新项目”,然后填写所有必填信息以创建新项目。
步骤 2 − 将以下代码添加到 res/layout/activity_main.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"> <LinearLayout android:id = "@+id/linearlayout01" android:layout_width = "fill_parent" android:layout_height = "fill_parent" android:background = "#ccc" android:layout_weight = "1" android:orientation = "vertical"> <fragment android:name = "com.example.myapplication.FirstFragment" android:id = "@+id/frag_1" android:layout_width = "fill_parent" android:layout_height = "fill_parent" /> </LinearLayout> <LinearLayout android:id = "@+id/linearlayout02" android:layout_width = "fill_parent" android:layout_height = "fill_parent" android:layout_weight = "1" android:background = "#eee" android:orientation = "vertical"> <fragment android:name = "com.example.myapplication.SecondFragment" android:id = "@+id/frag_2" android:layout_width = "fill_parent" android:layout_height = "fill_parent" /> </LinearLayout> </LinearLayout>
在以上代码中,我们采用了两个片段。
步骤 3 − 将以下代码添加到 src/MainActivity.java
<?xml version = "1.0" encoding = "utf-8"?> import android.os.Bundle; import android.support.v4.app.FragmentActivity; public class MainActivity extends FragmentActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
步骤 4 − 将以下代码添加到 src/ FirstFragment.java
<?xml version = "1.0" encoding = "utf-8"?> import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class FirstFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment, null); TextView but = (TextView) root.findViewById(R.id.text); return root; } }
步骤 4 − 将以下代码添加到 src/ SecondFragment.java
<?xml version = "1.0" encoding = "utf-8"?> import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class SecondFragment extends Fragment { TextView textView; View view; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment, container, false); return view; } }
尝试运行你的应用程序。假设你已将真机 Android 移动设备与计算机连接。要从 Android Studio 运行应用,请打开项目的一个活动文件,然后单击工具栏中的运行 图标。选择你的移动设备作为选项,然后检查移动设备显示的默认屏幕 –
点击此处下载项目代码
广告