fragment学两个demo就会用(二)

(转载加编辑)fragment与activity之间通信原理以及例子

首先,如果你想在android3.0及以下版本使用fragment,你必须引用android-support-v4.jar这个包

然后你写的activity不能再继承自Activity类了,而是要继承android.support.v4.app.FragmentActivity,一些其他的父类也有相应的变化.


由于在android的实现机制中fragment和activity会被分别实例化为两个不相干的对象,他们之间的联系由activity的一个成员对象fragmentmanager来维护.fragment实例化后会到activity中的fragmentmanager去注册一下,这个动作封装在fragment对象的onAttach中,所以你可以在fragment中声明一些回调接口,当fragment调用onAttach时,将这些回调接口实例化,这样fragment就能调用各个activity的成员函数了,当然activity必须implements这些接口,否则会包classcasterror

fragment和activity的回调机制又是OOP的一次完美演绎!

下面通过一个例子来说明:

 

我把Activity的UI分为两个部分,左边和右边,左边用来放置点击的按钮(LeftFragment),右边用来放置对应点击后显示的信息(RightFragment).

Activity的布局layout文件:main.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" > 
   
    <LinearLayout 
        android:id="@+id/left_layout"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:orientation="vertical" > 
    </LinearLayout> 
   
    <LinearLayout 
        android:id="@+id/right_layout"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_weight="10"
        android:orientation="vertical" > 
    </LinearLayout> 
   
</LinearLayout>

LeftFragment的布局layout:leftfragment.xml
<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" > 
   
    <Button 
        android:id="@+id/first_button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/first_button" /> 
   
    <Button 
        android:id="@+id/second_button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/second_button" /> 
   
    <Button 
        android:id="@+id/third_button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/third_button" /> 
   
</LinearLayout>

RightFragment的布局layout:rightfragment.xml
<?xml version="1.0" encoding="utf-8"?> 
<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/right_show_message"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@android:color/holo_orange_dark"
        android:textColor="@android:color/white" /> 
   
</LinearLayout>

以上是两个fragment和一个Activity的布局文件,下面来看他们的java文件
Activity:
public class FirstActivity extends Activity implements MyListener 
{ 
    /** 
     * 实现MyListener,当LeftFragment中点击第一页的时候,让RightFragment显示第一页信息,同理当点击第二页的时候,RightFragment显示第二页信息 
     *  
     * @param index 
     *            显示的页数 
     */
    public void showMessage(int index) 
    { 
        if (1 == index) 
            showMessageView.setText(R.string.first_page); 
        if (2 == index) 
            showMessageView.setText(R.string.second_page); 
        if (3 == index) 
            showMessageView.setText(R.string.third_page); 
    } 
   
    /** 得到RightFragment中显示信息的控件 */
    private TextView showMessageView; 
   
    /** Called when the activity is first created. */
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
        System.out.println("Activity--->onCreate"); 
   
        FragmentManager manager = getFragmentManager(); 
        FragmentTransaction transaction = manager.beginTransaction(); 
        // 动态增加Fragment 
        RightFragment rightFragment = new RightFragment(); 
        LeftFragment leftFragment = new LeftFragment(); 
        transaction.add(R.id.left_layout, leftFragment, "leftfragment"); 
        transaction.add(R.id.right_layout, rightFragment, "rightfragment"); 
        transaction.commit(); 
   
    } 
   
    @Override 
    protected void onResume() 
    { 
        super.onResume(); 
        System.out.println("Activity--->onResume"); //注意:findview放到这里
        showMessageView = (TextView) findViewById(R.id.right_show_message); 
    } 
}

LeftFragment:
public class LeftFragment extends Fragment 
{ 
    /** Acitivity要实现这个接口,这样Fragment和Activity就可以共享事件触发的资源了 */
    public interface MyListener 
    { 
        public void showMessage(int index); 
    } 
   
    private MyListener myListener; 
    private Button firstButton; 
    private Button secondButton; 
    private Button thirdButton; 
   
    /** Fragment第一次附属于Activity时调用,在onCreate之前调用 */
    @Override 
    public void onAttach(Activity activity) 
    { 
        super.onAttach(activity); 
        System.out.println("LeftFragment--->onAttach"); 
   
        myListener = (MyListener) activity; 
    } 
   
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
        super.onCreate(savedInstanceState); 
        System.out.println("LeftFragment--->onCreate"); 
    } 
   
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    { 
        System.out.println("LeftFragment--->onCreateView"); 
        return inflater.inflate(R.layout.leftfragment, container, false); 
    } 
   
    @Override 
    public void onResume() 
    { 
        super.onResume(); 
        System.out.println("LeftFragment--->onResume"); 
   
        firstButton = (Button) getActivity().findViewById(R.id.first_button); 
        secondButton = (Button) getActivity().findViewById(R.id.second_button); 
        thirdButton = (Button) getActivity().findViewById(R.id.third_button); 
   
        MyButtonClickListener clickListener = new MyButtonClickListener(); 
        firstButton.setOnClickListener(clickListener); 
        secondButton.setOnClickListener(clickListener); 
        thirdButton.setOnClickListener(clickListener); 
    } 
   
    /** 按钮的监听器 */
    class MyButtonClickListener implements OnClickListener 
    { 
        public void onClick(View v) 
        { 
            Button button = (Button) v; 
            if (button == firstButton) 
                myListener.showMessage(1); 
            if (button == secondButton) 
                myListener.showMessage(2); 
            if (button == thirdButton) 
                myListener.showMessage(3); 
        } 
    } 
}

RightFragment:
public class RightFragment extends Fragment 
{ 
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
        System.out.println("RightFragment--->onCreate"); 
        super.onCreate(savedInstanceState); 
    } 
   
    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    { 
        System.out.println("RightFragment--->onCreateView"); 
        return inflater.inflate(R.layout.rightfragment, container, false); 
    } 
}
注意,Fragment的生命周期和Activity生命周期之间的关系。在Activity里动态生成Fragment,首先是Activity调用onCreate()方法,但是这时候还没有加载到Fragment里的组件,当Fragment调用其onCreateView()方法后,Activity才能得到Fragment中的组件

这里最关键的就是Fragment要有一个接口和这个接口的引用,而这个接口需要Activity去实现它。当Fragment调用onAttach(Activity acitivity)方法的时候,将这个activity传递给这个接口引用,这样,就可以和Activity进行交互了.



  • 0
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
好的,下面是一个简单的用 WebGL 实现地球自转的 Demo: 首先,需要在 HTML 文件创建一个 canvas 元素: ```html <canvas id="myCanvas" width="800" height="600"></canvas> ``` 然后,在 JavaScript 文件获取 canvas 元素,并创建 WebGL 上下文: ```javascript const canvas = document.getElementById('myCanvas'); const gl = canvas.getContext('webgl'); ``` 接下来,需要编写着色器代码。这里我们需要两个着色器,一个用于顶点着色,一个用于片元着色。着色器代码如下: ```glsl // 顶点着色器代码 attribute vec3 aPosition; attribute vec2 aTexCoord; uniform mat4 uModelViewMatrix; uniform mat4 uProjectionMatrix; varying vec2 vTexCoord; void main() { gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(aPosition, 1.0); vTexCoord = aTexCoord; } // 片元着色器代码 precision mediump float; uniform sampler2D uSampler; varying vec2 vTexCoord; void main() { gl_FragColor = texture2D(uSampler, vTexCoord); } ``` 接着,创建着色器程序,并将着色器代码编译链接: ```javascript // 顶点着色器代码 const vertexShaderSource = ` attribute vec3 aPosition; attribute vec2 aTexCoord; uniform mat4 uModelViewMatrix; uniform mat4 uProjectionMatrix; varying vec2 vTexCoord; void main() { gl_Position = uProjectionMatrix * uModelViewMatrix * vec4(aPosition, 1.0); vTexCoord = aTexCoord; } `; // 片元着色器代码 const fragmentShaderSource = ` precision mediump float; uniform sampler2D uSampler; varying vec2 vTexCoord; void main() { gl_FragColor = texture2D(uSampler, vTexCoord); } `; // 创建着色器程序 const shaderProgram = gl.createProgram(); // 编译链接顶点着色器 const vertexShader = gl.createShader(gl.VERTEX_SHADER); gl.shaderSource(vertexShader, vertexShaderSource); gl.compileShader(vertexShader); gl.attachShader(shaderProgram, vertexShader); // 编译链接片元着色器 const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER); gl.shaderSource(fragmentShader, fragmentShaderSource); gl.compileShader(fragmentShader); gl.attachShader(shaderProgram, fragmentShader); // 链接着色器程序 gl.linkProgram(shaderProgram); ``` 然后,需要创建一个地球的顶点数据和纹理数据。这里我们使用了球体的顶点数据和 uv 坐标,以及地球的纹理图像。顶点数据和纹理数据如下: ```javascript // 球体顶点数据 const sphereVertices = []; const sphereUVs = []; const radius = 1; const segments = 32; const rings = 32; for (let r = 0; r < rings + 1; r++) { const theta = r * Math.PI / rings; const sinTheta = Math.sin(theta); const cosTheta = Math.cos(theta); for (let s = 0; s < segments + 1; s++) { const phi = s * 2 * Math.PI / segments; const sinPhi = Math.sin(phi); const cosPhi = Math.cos(phi); const x = cosPhi * sinTheta; const y = cosTheta; const z = sinPhi * sinTheta; sphereVertices.push(radius * x, radius * y, radius * z); sphereUVs.push(s / segments, r / rings); } } // 地球纹理图像 const textureImage = new Image(); textureImage.src = 'earth.jpg'; ``` 接下来,需要将顶点数据和纹理数据上传到 WebGL ,并为着色器程序的变量赋值: ```javascript // 将顶点数据和纹理数据上传到 WebGL const positionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(sphereVertices), gl.STATIC_DRAW); const uvBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, uvBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(sphereUVs), gl.STATIC_DRAW); // 为着色器程序的变量赋值 const aPosition = gl.getAttribLocation(shaderProgram, 'aPosition'); gl.enableVertexAttribArray(aPosition); gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); gl.vertexAttribPointer(aPosition, 3, gl.FLOAT, false, 0, 0); const aTexCoord = gl.getAttribLocation(shaderProgram, 'aTexCoord'); gl.enableVertexAttribArray(aTexCoord); gl.bindBuffer(gl.ARRAY_BUFFER, uvBuffer); gl.vertexAttribPointer(aTexCoord, 2, gl.FLOAT, false, 0, 0); const uModelViewMatrix = gl.getUniformLocation(shaderProgram, 'uModelViewMatrix'); const uProjectionMatrix = gl.getUniformLocation(shaderProgram, 'uProjectionMatrix'); const uSampler = gl.getUniformLocation(shaderProgram, 'uSampler'); // 加载纹理图像 const texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, textureImage); gl.generateMipmap(gl.TEXTURE_2D); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR); ``` 最后,需要在循环更新地球的旋转角度,并渲染场景: ```javascript let angle = 0; function render() { // 更新角度 angle += 0.01; // 计算模型视图矩阵和投影矩阵 const modelViewMatrix = mat4.create(); mat4.translate(modelViewMatrix, modelViewMatrix, [0, 0, -5]); mat4.rotateY(modelViewMatrix, modelViewMatrix, angle); const projectionMatrix = mat4.create(); mat4.perspective(projectionMatrix, 45 * Math.PI / 180, canvas.width / canvas.height, 0.1, 100); // 清空画布并绘制地球 gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); gl.useProgram(shaderProgram); gl.uniformMatrix4fv(uModelViewMatrix, false, modelViewMatrix); gl.uniformMatrix4fv(uProjectionMatrix, false, projectionMatrix); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, texture); gl.uniform1i(uSampler, 0); gl.drawArrays(gl.TRIANGLE_STRIP, 0, sphereVertices.length / 3); requestAnimationFrame(render); } render(); ``` 这样,一个简单的地球自转的 WebGL Demo 就完成了。完整代码如下:
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值