我们先学会使用静态加载的方式用activity加载Fragment.
关于fragment,个人感觉不太好理解。个人比较脑残,花了近一周的时间才基本明白了一点。
ps:我每天学习android的时间都是下班后地铁上看一章内容,回家再敲一下,理解一下 。
首先我们得创建一个fragment控件。
我们在main_activity的布局文件中创建一个fragment控件。这个控件我们必须给一个id,或者tag也可以,就是唯一标识一下。
然后我们还需要一个name,这个name就是指向一个fragment。
<span style="font-family:Microsoft YaHei;"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/fragment"
android:name="com.example.fragment.MyFragment"
/>
</LinearLayout></span>
然后我们看看在main_activity布局文件中name指向的那个fragment:
这里我们创建一个叫MyFragment的class,这个class继承自Fragment,然后我们重写onCreateView。
这里我们用inflater加载一个布局文件,就是fragment对应的布局文件。
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class MyFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
Button button = (Button) view.findViewById(R.id.button);
button.setText("静态加载按钮");
return view;
}
}
里面就包含了一个TextView和一个Button,在上面的Fragment中,我们就给button设置了显示的文本,值得注意的是获取控件的时候使用inflater加载的view对象来获取控件,直接findViewByID会报错的。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
最后我们再来看看MainActivity:
这里我们可以发现,在MainActivity里,我们直接findViewBYid就可以获取Fragment里面的控件,我们可以理解成fragment就是MainActivity的一部分了。。
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
// 定义fragment里面的控件
private TextView text;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化fragment中的控件
text = (TextView) findViewById(R.id.text);
button = (Button) findViewById(R.id.button);
// 给button设置点击事件 操作fragment中的控件
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
text.setText("MainActivity静态加载并操作fragment中的控件");
}
});
}
}
Fragment不太好理解,唯一的理解办法就是动手敲一敲,看一下效果,再思考一下,应该就能有点收货了。总结了一下就是:
我们可以这样考虑:如果Activity是一个房子,那么Fragment就是一个房间,我们就是一个房子加载了一个房间而已 。
ps:今天还是配置了eclipse的android开发环境,还是习惯eclipse,AndroidStudio还是不太喜欢用,虽然很好看,也很强大,但是习惯了eclipse的快捷键,操作方式。。